1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2016],{19:function(e,t,n){n.d(t,{u7:function(){return kl},Jj:function(){return Cc},IX:function(){return gc},my:function(){return Pu},xU:function(){return Ml},Lz:function(){return Ac},WA:function(){return S},F8:function(){return Rc},$q:function(){return Ll},W:function(){return Ol},EK:function(){return P},PU:function(){return nh},l7:function(){return we},Ky:function(){return Q},Xb:function(){return $},Cf:function(){return Vu},K9:function(){return b},Me:function(){return xe},yq:function(){return y},Wi:function(){return Cu},ET:function(){return Yl},Ab:function(){return ch},vr:function(){return uh},Fc:function(){return Tc},hJ:function(){return Ku},B$:function(){return Gu},at:function(){return qu},oe:function(){return Hl},AK:function(){return oh},TF:function(){return xc},JU:function(){return $u},ST:function(){return vc},fH:function(){return Ic},Ix:function(){return Sc},Wu:function(){return xl},Lx:function(){return Sl},qY:function(){return yc},GL:function(){return Jl},QT:function(){return Ul},kl:function(){return Kl},Xk:function(){return Gl},PL:function(){return $l},UQ:function(){return Ql},zN:function(){return zl},nP:function(){return lh},b9:function(){return wl},vh:function(){return vl},Pb:function(){return _c},L$:function(){return Dc},cf:function(){return Xl},sc:function(){return Zl},Xo:function(){return pl},IO:function(){return hl},iE:function(){return zu},Eo:function(){return Qu},i3:function(){return ih},Bt:function(){return ah},pl:function(){return jl},Ub:function(){return m},qK:function(){return Pl},TQ:function(){return Tl},e0:function(){return bl},r7:function(){return Wl},Mx:function(){return Ec},ar:function(){return fl}});var r=n(10389),s=n(8463),i=n(53333),o=n(74444),a=n(43510),u=n(34155);const c="@firebase/firestore";class l{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}l.UNAUTHENTICATED=new l(null),l.GOOGLE_CREDENTIALS=new l("google-credentials-uid"),l.FIRST_PARTY=new l("first-party-uid"),l.MOCK_USER=new l("mock-user");let h="9.15.0";const d=new i.Yd("@firebase/firestore");function f(){return d.logLevel}function m(e){d.setLogLevel(e)}function g(e,...t){if(d.logLevel<=i.in.DEBUG){const n=t.map(w);d.debug(`Firestore (${h}): ${e}`,...n)}}function p(e,...t){if(d.logLevel<=i.in.ERROR){const n=t.map(w);d.error(`Firestore (${h}): ${e}`,...n)}}function y(e,...t){if(d.logLevel<=i.in.WARN){const n=t.map(w);d.warn(`Firestore (${h}): ${e}`,...n)}}function w(e){if("string"==typeof e)return e;try{return t=e,JSON.stringify(t)}catch(t){return e}var t}function v(e="Unexpected state"){const t=`FIRESTORE (${h}) INTERNAL ASSERTION FAILED: `+e;throw p(t),new Error(t)}function I(e,t){e||v()}function b(e,t){e||v()}function T(e,t){return e}const E={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class S extends o.ZR{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class x{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class _{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class D{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(l.UNAUTHENTICATED)))}shutdown(){}}class N{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}}class C{constructor(e){this.t=e,this.currentUser=l.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let s=new x;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new x,e.enqueueRetryable((()=>r(this.currentUser)))};const i=()=>{const t=s;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},o=e=>{g("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),i()};this.t.onInit((e=>o(e))),setTimeout((()=>
1{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(g("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new x)}}),0),i()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(g("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(I("string"==typeof t.accessToken),new _(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return I(null===e||"string"==typeof e),new l(e)}}class A{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r,this.type="FirstParty",this.user=l.FIRST_PARTY,this.p=new Map}I(){return this.g?this.g():(I(!("object"!=typeof this.h||null===this.h||!this.h.auth||!this.h.auth.getAuthHeaderValueForFirstParty)),this.h.auth.getAuthHeaderValueForFirstParty([]))}get headers(){this.p.set("X-Goog-AuthUser",this.l);const e=this.I();return e&&this.p.set("Authorization",e),this.m&&this.p.set("X-Goog-Iam-Authorization-Token",this.m),this.p}}class k{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r}getToken(){return Promise.resolve(new A(this.h,this.l,this.m,this.g))}start(e,t){e.enqueueRetryable((()=>t(l.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class R{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class V{constructor(e){this.T=e,this.forceRefresh=!1,this.appCheck=null,this.A=null}start(e,t){const n=e=>{null!=e.error&&g("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const n=e.token!==this.A;return this.A=e.token,g("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{g("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.T.onInit((e=>r(e))),setTimeout((()=>{if(!this.appCheck){const e=this.T.getImmediate({optional:!0});e?r(e):g("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(I("string"==typeof e.token),this.A=e.token,new R(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}function F(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let r=0;r<e;r++)n[r]=Math.floor(256*Math.random());return n}class M{static R(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=Math.floor(256/e.length)*e.length;let n="";for(;n.length<20;){const r=F(40);for(let s=0;s<r.length;++s)n.length<20&&r[s]<t&&(n+=e.charAt(r[s]%e.length))}return n}}function L(e,t){return e<t?-1:e>t?1:0}function O(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}function q(e){return e+"\0"}class P{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new S(E.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new S(E.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new S(E.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new S(E.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return P.fromMillis(Date.now())}static fromDate(e){return P.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new P(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?L(this.nanoseconds,e.nanoseconds):L(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{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}
1}class U{constructor(e){this.timestamp=e}static fromTimestamp(e){return new U(e)}static min(){return new U(new P(0,0))}static max(){return new U(new P(253402300799,999999999))}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}}class B{constructor(e,t,n){void 0===t?t=0:t>e.length&&v(),void 0===n?n=e.length-t:n>e.length-t&&v(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===B.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof B?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?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 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),s=t.get(r);if(n<s)return-1;if(n>s)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class K extends B{construct(e,t,n){return new K(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new S(E.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new K(t)}static emptyPath(){return new K([])}}const G=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class $ extends B{construct(e,t,n){return new $(e,t,n)}static isValidIdentifier(e){return G.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),$.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new $(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const s=()=>
vendor: 5,213 bytes, line 1
1{if(0===n.length)throw new S(E.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new S(E.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new S(E.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(i=!i,r++):"."!==t||i?(n+=t,r++):(s(),r++)}if(s(),i)throw new S(E.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new $(t)}static emptyPath(){return new $([])}}class Q{constructor(e){this.path=e}static fromPath(e){return new Q(K.fromString(e))}static fromName(e){return new Q(K.fromString(e).popFirst(5))}static empty(){return new Q(K.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=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 null!==e&&0===K.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return K.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new Q(new K(e.slice()))}}class z{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function j(e){return e.fields.find((e=>2===e.kind))}function W(e){return e.fields.filter((e=>2!==e.kind))}z.UNKNOWN_ID=-1;class H{constructor(e,t){this.fieldPath=e,this.kind=t}}class Y{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Y(0,J.min())}}function X(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,s=U.fromTimestamp(1e9===r?new P(n+1,0):new P(n,r));return new J(s,Q.empty(),t)}function Z(e){return new J(e.readTime,e.key,-1)}class J{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new J(U.min(),Q.empty(),-1)}static max(){return new J(U.max(),Q.empty(),-1)}}function ee(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=Q.comparator(e.documentKey,t.documentKey),0!==n?n:L(e.largestBatchId,t.largestBatchId))}const te="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ne{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function re(e){if(e.code!==E.FAILED_PRECONDITION||e.message!==te)throw e;g("LocalStore","Unexpectedly lost primary lease")}class se{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&v(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new se(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof se?t:se.resolve(t)}catch(e){return se.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):se.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):se.reject(t)}static resolve(e){return new se(((t,n)=>{t(e)}))}static reject(e){return new se(((t,n)=>{n(e)}))}static waitFor(e){return new se(((t,n)=>{let r=0,s=0,i=!1;e.forEach((e=>{++r,e.next((()=>{++s,i&&s===r&&t()}),(e=>n(e)))})),i=!0,s===r&&t()}))}static or(e){let t=se.resolve(!1);for(const n of e)t=t.next((e=>e?se.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}static mapArray(e,t){return new se(((n,r)=>{const s=e.length,i=new Array(s);let o=0;for(let a=0;a<s;a++){const u=a;t(e[u]).next((e=>{i[u]=e,++o,o===s&&n(i)}),(e=>r(e)))}}))}static doWhile(e,t){return new se(((n,r)=>{const s=()=>{!0===e()?t().next((()=>{s()}),r):n()};s()}))}}class ie{constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.P=new x,this.transaction.oncomplete=()=>{this.P.resolve()},this.transaction.onabort=()=>{t.error?this.P.reject(new ue(e,t.error)):this.P.resolve()},this.transaction.onerror=t=>{const n=fe(t.target.error);this.P.reject(new ue(e,n))}}static open(e,t,n,r){try{return new ie(t,e.transaction(r,n))}catch(e){throw new ue(t,e)}}get v(){return this.P.promise}abort(e){e&&this.P.reject(e),this.aborted||(g("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}V(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){const t=this.transaction.objectStore(e);return new le(t)}}class oe{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===oe.D((0,o.z$)())&&p("Firestore persistence suffers from a bug in
1iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return g("SimpleDb","Removing database:",e),he(window.indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!(0,o.hl)())return!1;if(oe.N())return!0;const e=(0,o.z$)(),t=oe.D(e),n=0<t&&t<10,r=oe.k(e),s=0<r&&r<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||n||s)}static N(){var e;return"undefined"!=typeof u&&"YES"===(null===(e=u.env)||void 0===e?void 0:e.O)}static M(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static k(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async F(e){return this.db||(g("SimpleDb","Opening database:",this.name),this.db=await new Promise(((t,n)=>{const r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{const n=e.target.result;t(n)},r.onblocked=()=>{n(new ue(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{const r=t.target.error;"VersionError"===r.name?n(new S(E.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.")):"InvalidStateError"===r.name?n(new S(E.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: "+r)):n(new ue(e,r))},r.onupgradeneeded=e=>{g("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);const t=e.target.result;this.S.$(t,r.transaction,e.oldVersion,this.version).next((()=>{g("SimpleDb","Database upgrade to version "+this.version+" complete")}))}}))),this.B&&(this.db.onversionchange=e=>this.B(e)),this.db}L(e){this.B=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){const s="readonly"===t;let i=0;for(;;){++i;try{this.db=await this.F(e);const t=ie.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).next((e=>(t.V(),e))).catch((e=>(t.abort(e),se.reject(e)))).toPromise();return i.catch((()=>{})),await t.v,i}catch(e){const t=e,n="FirebaseError"!==t.name&&i<3;if(g("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class ae{constructor(e){this.q=e,this.U=!1,this.K=null}get isDone(){return this.U}get G(){return this.K}set cursor(e){this.q=e}done(){this.U=!0}j(e){this.K=e}delete(){return he(this.q.delete())}}class ue extends S{constructor(e,t){super(E.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function ce(e){return"IndexedDbTransactionError"===e.name}class le{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(g("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(g("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),he(n)}add(e){return g("SimpleDb","ADD",this.store.name,e,e),he(this.store.add(e))}get(e){return he(this.store.get(e)).next((t=>(void 0===t&&(t=null),g("SimpleDb","GET",this.store.name,e,t),t)))}delete(e){return g("SimpleDb","DELETE",this.store.name,e),he(this.store.delete(e))}count(){return g("SimpleDb","COUNT",this.store.name),he(this.store.count())}W(e,t){const n=this.options(e,t);if(n.index||"function"!=typeof this.store.getAll){const e=this.cursor(n),t=[];return this.H(e,((e,n)=>{t.push(n)})).next((()=>t))}{const e=this.store.getAll(n.range);return new se(((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}}))}}J(e,t){const n=this.store.getAll(e,null===t?void 0:t);return new se(((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}}))}Y(e,t){g("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.X=!1;const r=this.cursor(n);
1return this.H(r,((e,t,n)=>n.delete()))}Z(e,t){let n;t?n=e:(n={},t=e);const r=this.cursor(n);return this.H(r,t)}tt(e){const t=this.cursor({});return new se(((n,r)=>{t.onerror=e=>{const t=fe(e.target.error);r(t)},t.onsuccess=t=>{const r=t.target.result;r?e(r.primaryKey,r.value).next((e=>{e?r.continue():n()})):n()}}))}H(e,t){const n=[];return new se(((r,s)=>{e.onerror=e=>{s(e.target.error)},e.onsuccess=e=>{const s=e.target.result;if(!s)return void r();const i=new ae(s),o=t(s.primaryKey,s.value,i);if(o instanceof se){const e=o.catch((e=>(i.done(),se.reject(e))));n.push(e)}i.isDone?r():null===i.G?s.continue():s.continue(i.G)}})).next((()=>se.waitFor(n)))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.X?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function he(e){return new se(((t,n)=>{e.onsuccess=e=>{const n=e.target.result;t(n)},e.onerror=e=>{const t=fe(e.target.error);n(t)}}))}let de=!1;function fe(e){const t=oe.D((0,o.z$)());if(t>=12.2&&t<13){const t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){const e=new S("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 de||(de=!0,setTimeout((()=>{throw e}),0)),e}}return e}class me{constructor(e,t){this.asyncQueue=e,this.et=t,this.task=null}start(){this.nt(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}nt(e){g("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{g("IndexBackiller",`Documents written: ${await this.et.st()}`)}catch(e){ce(e)?g("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await re(e)}await this.nt(6e4)}))}}class ge{constructor(e,t){this.localStore=e,this.persistence=t}async st(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",(t=>this.it(t,e)))}it(e,t){const n=new Set;let r=t,s=!0;return se.doWhile((()=>!0===s&&r>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t=>{if(null!==t&&!n.has(t))return g("IndexBackiller",`Processing collection: ${t}`),this.rt(e,t,r).next((e=>{r-=e,n.add(t)}));s=!1})))).next((()=>t-r))}rt(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next((r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next((n=>{const s=n.changes;return this.localStore.indexManager.updateIndexEntries(e,s).next((()=>this.ot(r,n))).next((n=>(g("IndexBackiller",`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n)))).next((()=>s.size))}))))}ot(e,t){let n=e;
1return t.changes.forEach(((e,t)=>{const r=Z(t);ee(r,n)>0&&(n=r)})),new J(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class pe{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ut(e),this.ct=e=>t.writeSequenceNumber(e))}ut(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.ct&&this.ct(e),e}}pe.at=-1;class ye{constructor(e,t,n,r,s,i,o,a){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class we{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new we("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof we&&e.projectId===this.projectId&&e.database===this.database}}function ve(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function Ie(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function be(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function Te(e){return null==e}function Ee(e){return 0===e&&1/e==-1/0}function Se(e){return"number"==typeof e&&Number.isInteger(e)&&!Ee(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function xe(){return"undefined"!=typeof atob}class _e{constructor(e){this.binaryString=e}static fromBase64String(e){const t=atob(e);return new _e(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new _e(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return L(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}_e.EMPTY_BYTE_STRING=new _e("");const De=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Ne(e){if(I(!!e),"string"==typeof e){let t=0;const n=De.exec(e);if(I(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const r=new Date(e);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:Ce(e.seconds),nanos:Ce(e.nanos)}}function Ce(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ae(e){return"string"==typeof e?_e.fromBase64String(e):_e.fromUint8Array(e)}function ke(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function Re(e){const t=e.mapValue.fields.__previous_value__;return ke(t)?Re(t):t}function Ve(e){const t=Ne(e.mapValue.fields.__local_write_time__.timestampValue);return new P(t.seconds,t.nanos)}const Fe={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Me={nullValue:"NULL_VALUE"};function Le(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?ke(e)?4:Ye(e)?9007199254740991:10:v()}function Oe(e,t){if(e===t)return!0;const n=Le(e);if(n!==Le(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Ve(e).isEqual(Ve(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=Ne(e.timestampValue),r=Ne(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return Ae(e.bytesValue).isEqual(Ae(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return Ce(e.geoPointValue.latitude)===Ce(t.geoPointValue.latitude)&&Ce(e.geoPointValue.longitude)===Ce(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Ce(e.integerValue)===Ce(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=Ce(e.doubleValue),r=Ce(t.doubleValue);return n===r?Ee(n)===Ee(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return O(e.arrayValue.values||[],t.arrayValue.values||[],Oe);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(ve(n)!==ve(r))return!1;for(const s in n)if(n.hasOwnProperty(s)&&(void 0===r[s]||!Oe(n[s],r[s])))return!1;return!0}(e,t);default:return v()}}function qe(e,t){return void 0!==(e.values||[]).find((e=>Oe(e,t)))}function Pe(e,t){if(e===t)return 0;const n=Le(e),r=Le(t);if(n!==r)return L(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return L(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=Ce(e.integerValue||e.doubleValue),r=Ce(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return Ue(e.timestampValue,t.timestampValue);case 4:return Ue(Ve(e),Ve(t));case 5:return L(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ae(e),r=Ae(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let s=0;s<n.length&&s<r.length;s++){const e=L(n[s],r[s]);if(0!==e)return e}return L(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=L(Ce(e.latitude),Ce(t.latitude));return 0!==n?n:L(Ce(e.longitude),Ce(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return function(e,t){const n=e.values||[],r=t.values||[];for(let s=0;s<n.length&&s<r.length;++s){const e=Pe(n[s],r[s]);if(e)return e}return L(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Fe.mapValue&&t===Fe.mapValue)return 0;if(e===Fe.mapValue)return 1;if(t===Fe.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),s=t.fields||{},i=Object.keys(s);r.sort(),i.sort();for(let o=0;o<r.length&&o<i.length;++o){const e=L(r[o],i[o]);if(0!==e)return e;const t=Pe(n[r[o]],s[i[o]]);if(0!==t)return t}return L(r.length,i.length)}(e.mapValue,t.mapValue);default:throw v()}}function Ue(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return L(e,t);const n=Ne(e),r=Ne(t),s=L(n.seconds,r.seconds);return 0!==s?s:L(n.nanos,r.nanos)}function Be(e){return Ke(e)}function Ke(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=Ne(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?Ae(e.bytesValue).toBase64():"referenceValue"in e?(n=e.referenceValue,Q.fromName(n).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=Ke(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const s of t)r?r=!1:n+=",",n+=`${s}:${Ke(e.fields[s])}`;return n+"}"}(e.mapValue):v();var t,n}function Ge(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function $e(e){return!!e&&"integerValue"in e}function Qe(e){return!!e&&"arrayValue"in e}function ze(e){return!!e&&"nullValue"in e}function je(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function We(e){return!!e&&"mapValue"in e}function He(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return Ie(e.mapValue.fields,((e,n)=>t.mapValue.fields[e]=He(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=He(e.arrayValue.values[n]);return t}return Object.assign({},e)}function Ye(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Xe(e){return"nullValue"in e?Me:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}
1:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?Ge(we.empty(),Q.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?{mapValue:{}}:v()}function Ze(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?Ge(we.empty(),Q.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?{mapValue:{}}:"mapValue"in e?Fe:v()}function Je(e,t){const n=Pe(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function et(e,t){const n=Pe(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class tt{constructor(e,t){this.position=e,this.inclusive=t}}function nt(e,t,n){let r=0;for(let s=0;s<e.position.length;s++){const i=t[s],o=e.position[s];if(r=i.field.isKeyField()?Q.comparator(Q.fromName(o.referenceValue),n.key):Pe(o,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return r}function rt(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Oe(e.position[n],t.position[n]))return!1;return!0}class st{}class it extends st{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new gt(e,t,n):"array-contains"===t?new vt(e,n):"in"===t?new It(e,n):"not-in"===t?new bt(e,n):"array-contains-any"===t?new Tt(e,n):new it(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new pt(e,n):new yt(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Pe(t,this.value)):null!==t&&Le(this.value)===Le(t)&&this.matchesComparison(Pe(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return v()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class ot extends st{constructor(e,t){super(),this.filters=e,this.op=t,this.ht=null}static create(e,t){return new ot(e,t)}matches(e){return at(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.ht||(this.ht=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.ht}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){const e=this.lt((e=>e.isInequality()));return null!==e?e.field:null}lt(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function at(e){return"and"===e.op}function ut(e){return"or"===e.op}function ct(e){return lt(e)&&at(e)}function lt(e){for(const t of e.filters)if(t instanceof ot)return!1;return!0}function ht(e){if(e instanceof it)return e.field.canonicalString()+e.op.toString()+Be(e.value);{const t=e.filters.map((e=>ht(e))).join(",");return`${e.op}(${t})`}}function dt(e,t){return e instanceof it?function(e,t){return t instanceof it&&e.op===t.op&&e.field.isEqual(t.field)&&Oe(e.value,t.value)}(e,t):e instanceof ot?function(e,t){return t instanceof ot&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,r)=>e&&dt(n,t.filters[r])),!0)}(e,t):void v()}function ft(e,t){const n=e.filters.concat(t);return ot.create(n,e.op)}function mt(e){return e instanceof it?function(e){return`${e.field.canonicalString()} ${e.op} ${Be(e.value)}`}(e):e instanceof ot?function(e){return e.op.toString()+" {"+e.getFilters().map(mt).join(" ,")+"}"}(e):"Filter"}class gt extends it{constructor(e,t,n){super(e,t,n),this.key=Q.fromName(n.referenceValue)}matches(e){const t=Q.comparator(e.key,this.key);return this.matchesComparison(t)}}class pt extends it{constructor(e,t){super(e,"in",t),this.keys=wt("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class yt extends it{constructor(e,t){super(e,"not-in",t),this.keys=wt("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function wt(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>Q.fromName(e.referenceValue)))}class vt extends it{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Qe(t)&&qe(t.arrayValue,this.value)}}class It extends it{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&qe(this.value.arrayValue,t)}}class bt extends it{constructor(e,t){super(e,"not-in",t)}matches(e){if(qe(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!qe(this.value.arrayValue,t)}}class Tt extends it{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);
vendor: 4,881 bytes, line 1
1return!(!Qe(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>qe(this.value.arrayValue,e)))}}class Et{constructor(e,t="asc"){this.field=e,this.dir=t}}function St(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class xt{constructor(e,t){this.comparator=e,this.root=t||Dt.EMPTY}insert(e,t){return new xt(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Dt.BLACK,null,null))}remove(e){return new xt(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Dt.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new _t(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new _t(this.root,e,this.comparator,!1)}getReverseIterator(){return new _t(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new _t(this.root,e,this.comparator,!0)}}class _t{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const 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(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class Dt{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:Dt.RED,this.left=null!=r?r:Dt.EMPTY,this.right=null!=s?s:Dt.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new Dt(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=s?s: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,n){let r=this;const s=n(e,r.key);return r=s<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===s?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return Dt.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 n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return Dt.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.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(){const e=this.copy(null,null,Dt.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,Dt.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const 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(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw v();if(this.right.isRed())throw v();const e=this.left.check();if(e!==this.right.check())throw v();return e+(this.isRed()?0:1)}}
vendor: 7,254 bytes, line 1
1Dt.EMPTY=null,Dt.RED=!0,Dt.BLACK=!1,Dt.EMPTY=new class{constructor(){this.size=0}get key(){throw v()}get value(){throw v()}get color(){throw v()}get left(){throw v()}get right(){throw v()}copy(e,t,n,r,s){return this}insert(e,t,n){return new Dt(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}};class Nt{constructor(e){this.comparator=e,this.data=new xt(this.comparator)}has(e){return null!==this.data.get(e)}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,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new Ct(this.data.getIterator())}getIteratorFrom(e){return new Ct(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<e.size&&(t=e,e=this),e.forEach((e=>{t=t.add(e)})),t}isEqual(e){if(!(e instanceof Nt))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new Nt(this.comparator);return t.data=e,t}}class Ct{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function At(e){return e.hasNext()?e.getNext():void 0}class kt{constructor(e){this.fields=e,e.sort($.comparator)}static empty(){return new kt([])}unionWith(e){let t=new Nt($.comparator);for(const n of this.fields)t=t.add(n);for(const n of e)t=t.add(n);return new kt(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return O(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class Rt{constructor(e){this.value=e}static empty(){return new Rt({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!We(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=He(t)}setAll(e){let t=$.emptyPath(),n={},r=[];e.forEach(((e,s)=>{if(!t.isImmediateParentOf(s)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=s.popLast()}e?n[s.lastSegment()]=He(e):r.push(s.lastSegment())}));const s=this.getFieldsMap(t);this.applyChanges(s,n,r)}delete(e){const t=this.field(e.popLast());We(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Oe(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];We(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){Ie(t,((t,n)=>e[t]=n));for(const r of n)delete e[r]}clone(){return new Rt(He(this.value))}}function Vt(e){const t=[];return Ie(e.fields,((e,n)=>{const r=new $([e]);if(We(n)){const e=Vt(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new kt(t)}class Ft{constructor(e,t,n,r,s,i,o){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=s,this.data=i,this.documentState=o}static newInvalidDocument(e){return new Ft(e,0,U.min(),U.min(),U.min(),Rt.empty(),0)}static newFoundDocument(e,t,n,r){return new Ft(e,1,t,U.min(),n,r,0)}static newNoDocument(e,t){return new Ft(e,2,t,U.min(),U.min(),Rt.empty(),0)}static newUnknownDocument(e,t){return new Ft(e,3,t,U.min(),U.min(),Rt.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(U.min())||2!==this.documentType&&0!==this.documentType||(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=Rt.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Rt.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=U.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Ft&&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 Ft(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}})`}}class Mt{constructor(e,t=null,n=[],r=[],s=null,i=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=o,this.ft=null}}function Lt(e,t=null,n=[],r=[],s=null,i=null,o=null){return new Mt(e,t,n,r,s,i,o)}function Ot(e){const t=T(e);if(null===t.ft){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>ht(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),Te(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Be(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Be(e))).join(",")),t.ft=e}return t.ft}function qt(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!St(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!dt(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!rt(e.startAt,t.startAt)&&rt(e.endAt,t.endAt)}function Pt(e){return Q.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Ut(e,t){return e.filters.filter((e=>e instanceof it&&e.field.isEqual(t)))}function Bt(e,t,n){let r=Me,s=!0;
1for(const i of Ut(e,t)){let e=Me,t=!0;switch(i.op){case"<":case"<=":e=Xe(i.value);break;case"==":case"in":case">=":e=i.value;break;case">":e=i.value,t=!1;break;case"!=":case"not-in":e=Me}Je({value:r,inclusive:s},{value:e,inclusive:t})<0&&(r=e,s=t)}if(null!==n)for(let i=0;i<e.orderBy.length;++i)if(e.orderBy[i].field.isEqual(t)){const e=n.position[i];Je({value:r,inclusive:s},{value:e,inclusive:n.inclusive})<0&&(r=e,s=n.inclusive);break}return{value:r,inclusive:s}}function Kt(e,t,n){let r=Fe,s=!0;for(const i of Ut(e,t)){let e=Fe,t=!0;switch(i.op){case">=":case">":e=Ze(i.value),t=!1;break;case"==":case"in":case"<=":e=i.value;break;case"<":e=i.value,t=!1;break;case"!=":case"not-in":e=Fe}et({value:r,inclusive:s},{value:e,inclusive:t})>0&&(r=e,s=t)}if(null!==n)for(let i=0;i<e.orderBy.length;++i)if(e.orderBy[i].field.isEqual(t)){const e=n.position[i];et({value:r,inclusive:s},{value:e,inclusive:n.inclusive})>0&&(r=e,s=n.inclusive);break}return{value:r,inclusive:s}}class Gt{constructor(e,t=null,n=[],r=[],s=null,i="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=s,this.limitType=i,this.startAt=o,this.endAt=a,this.dt=null,this._t=null,this.startAt,this.endAt}}function $t(e,t,n,r,s,i,o,a){return new Gt(e,t,n,r,s,i,o,a)}function Qt(e){return new Gt(e)}function zt(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function jt(e){return e.explicitOrderBy.length>0?e.explicitOrderBy[0].field:null}function Wt(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function Ht(e){return null!==e.collectionGroup}function Yt(e){const t=T(e);if(null===t.dt){t.dt=[];const e=Wt(t),n=jt(t);if(null!==e&&null===n)e.isKeyField()||t.dt.push(new Et(e)),t.dt.push(new Et($.keyField(),"asc"));else{let e=!1;for(const n of t.explicitOrderBy)t.dt.push(n),n.field.isKeyField()&&(e=!0);if(!e){const e=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";t.dt.push(new Et($.keyField(),e))}}}return t.dt}function Xt(e){const t=T(e);if(!t._t)if("F"===t.limitType)t._t=Lt(t.path,t.collectionGroup,Yt(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const s of Yt(t)){const t="desc"===s.dir?"asc":"desc";e.push(new Et(s.field,t))}const n=t.endAt?new tt(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new tt(t.startAt.position,t.startAt.inclusive):null;t._t=Lt(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t._t}function Zt(e,t){t.getFirstInequalityField(),Wt(e);const n=e.filters.concat([t]);return new Gt(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Jt(e,t,n){return new Gt(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function en(e,t){return qt(Xt(e),Xt(t))&&e.limitType===t.limitType}function tn(e){return`${Ot(Xt(e))}|lt:${e.limitType}`}function nn(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>mt(e))).join(", ")}]`),Te(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Be(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Be(e))).join(",")),`Target(${t})`}(Xt(e))}; limitType=${e.limitType})`}function rn(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):Q.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of Yt(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=nt(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,Yt(e),t))&&!(e.endAt&&!function(e,t,n){const r=nt(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Yt(e),t))}(e,t)}function sn(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function on(e){return(t,n)=>{let r=!1;for(const s of Yt(e)){const e=an(s,t,n);if(0!==e)return e;r=r||s.field.isKeyField()}return 0}}function an(e,t,n){const r=e.field.isKeyField()?Q.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),s=n.data.field(e);return null!==r&&null!==s?Pe(r,s):v()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return v()}}function un(e,t){if(e.wt){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Ee(t)?"-0":t}}function cn(e){return{integerValue:""+e}}function ln(e,t){return Se(t)?cn(t):un(e,t)}class hn{constructor(){this._=void 0}}function dn(e,t,n){return e instanceof gn?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof pn?yn(e,t):e instanceof wn?vn(e,t):function(e,t){const n=mn(e,t),r=bn(n)+bn(e.gt);return $e(n)&&$e(e.gt)?cn(r):un(e.yt,r)}(e,t)}function fn(e,t,n){return e instanceof pn?yn(e,t):e instanceof wn?vn(e,t):n}function mn(e,t){return e instanceof In?$e(n=t)||function(e){return!!e&&"doubleValue"in e}(n)?t:{integerValue:0}:null;var n}class gn extends hn{}class pn extends hn{constructor(e){super(),this.elements=e}}function yn(e,t){const n=Tn(t);for(const r of e.elements)n.some((e=>Oe(e,r)))||n.push(r);return{arrayValue:{values:n}}}class wn extends hn{constructor(e){super(),this.elements=e}}function vn(e,t){let n=Tn(t);for(const r of e.elements)n=n.filter((e=>!Oe(e,r)));return{arrayValue:{values:n}}}class In extends hn{constructor(e,t){super(),this.yt=e,this.gt=t}}function bn(e){return Ce(e.integerValue||e.doubleValue)}function Tn(e){return Qe(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class En{constructor(e,t){this.field=e,this.transform=t}}class Sn{constructor(e,t){this.version=e,this.transformResults=t}}class xn{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new xn}static exists(e){return new xn(void 0,e)}static updateTime(e){return new xn(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function _n(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Dn{}function Nn(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new qn(e.key,xn.none()):new Vn(e.key,e.data,xn.none());{const n=e.data,r=Rt.empty();let s=new Nt($.comparator);for(let e of t.fields)if(!s.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),s=s.add(e)}return new Fn(e.key,r,new kt(s.toArray()),xn.none())}}function Cn(e,t,n){e instanceof Vn?function(e,t,n){const r=e.value.clone(),s=Ln(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}
1(e,t,n):e instanceof Fn?function(e,t,n){if(!_n(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=Ln(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(Mn(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function An(e,t,n,r){return e instanceof Vn?function(e,t,n,r){if(!_n(e.precondition,t))return n;const s=e.value.clone(),i=On(e.fieldTransforms,r,t);return s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null}(e,t,n,r):e instanceof Fn?function(e,t,n,r){if(!_n(e.precondition,t))return n;const s=On(e.fieldTransforms,r,t),i=t.data;return i.setAll(Mn(e)),i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,r):function(e,t,n){return _n(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function kn(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),s=mn(r.transform,e||null);null!=s&&(null===n&&(n=Rt.empty()),n.set(r.field,s))}return n||null}function Rn(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&O(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof pn&&t instanceof pn||e instanceof wn&&t instanceof wn?O(e.elements,t.elements,Oe):e instanceof In&&t instanceof In?Oe(e.gt,t.gt):e instanceof gn&&t instanceof gn}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class Vn extends Dn{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class Fn extends Dn{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}getFieldMask(){return this.fieldMask}}function Mn(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function Ln(e,t,n){const r=new Map;I(e.length===n.length);for(let s=0;s<n.length;s++){const i=e[s],o=i.transform,a=t.data.field(i.field);r.set(i.field,fn(o,a,n[s]))}return r}function On(e,t,n){const r=new Map;for(const s of e){const e=s.transform,i=n.data.field(s.field);r.set(s.field,dn(e,i,t))}return r}class qn extends Dn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Pn extends Dn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Un{constructor(e){this.count=e}}var Bn,Kn;function Gn(e){switch(e){default:return v();case E.CANCELLED:case E.UNKNOWN:case E.DEADLINE_EXCEEDED:case E.RESOURCE_EXHAUSTED:case E.INTERNAL:case E.UNAVAILABLE:case E.UNAUTHENTICATED:return!1;case E.INVALID_ARGUMENT:case E.NOT_FOUND:case E.ALREADY_EXISTS:case E.PERMISSION_DENIED:case E.FAILED_PRECONDITION:case E.ABORTED:case E.OUT_OF_RANGE:case E.UNIMPLEMENTED:case E.DATA_LOSS:return!0}}function $n(e){if(void 0===e)return p("GRPC error has no .code"),E.UNKNOWN;switch(e){case Bn.OK:return E.OK;case Bn.CANCELLED:return E.CANCELLED;case Bn.UNKNOWN:return E.UNKNOWN;case Bn.DEADLINE_EXCEEDED:return E.DEADLINE_EXCEEDED;case Bn.RESOURCE_EXHAUSTED:return E.RESOURCE_EXHAUSTED;case Bn.INTERNAL:return E.INTERNAL;case Bn.UNAVAILABLE:return E.UNAVAILABLE;case Bn.UNAUTHENTICATED:return E.UNAUTHENTICATED;case Bn.INVALID_ARGUMENT:return E.INVALID_ARGUMENT;case Bn.NOT_FOUND:return E.NOT_FOUND;case Bn.ALREADY_EXISTS:return E.ALREADY_EXISTS;case Bn.PERMISSION_DENIED:return E.PERMISSION_DENIED;case Bn.FAILED_PRECONDITION:return E.FAILED_PRECONDITION;case Bn.ABORTED:return E.ABORTED;case Bn.OUT_OF_RANGE:return E.OUT_OF_RANGE;case Bn.UNIMPLEMENTED:return E.UNIMPLEMENTED;case Bn.DATA_LOSS:return E.DATA_LOSS;default:return v()}}(Kn=Bn||(Bn={}))[Kn.OK=0]="OK",Kn[Kn.CANCELLED=1]="CANCELLED",Kn[Kn.UNKNOWN=2]="UNKNOWN",Kn[Kn.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Kn[Kn.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Kn[Kn.NOT_FOUND=5]="NOT_FOUND",Kn[Kn.ALREADY_EXISTS=6]="ALREADY_EXISTS",Kn[Kn.PERMISSION_DENIED=7]="PERMISSION_DENIED",Kn[Kn.UNAUTHENTICATED=16]="UNAUTHENTICATED",Kn[Kn.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Kn[Kn.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Kn[Kn.ABORTED=10]="ABORTED",Kn[Kn.OUT_OF_RANGE=11]="OUT_OF_RANGE",Kn[Kn.UNIMPLEMENT
1ED=12]="UNIMPLEMENTED",Kn[Kn.INTERNAL=13]="INTERNAL",Kn[Kn.UNAVAILABLE=14]="UNAVAILABLE",Kn[Kn.DATA_LOSS=15]="DATA_LOSS";class Qn{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[r,s]of n)if(this.equalsFn(r,e))return s}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let s=0;s<r.length;s++)if(this.equalsFn(r[s][0],e))return void(r[s]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){Ie(this.inner,((t,n)=>{for(const[r,s]of n)e(r,s)}))}isEmpty(){return be(this.inner)}size(){return this.innerSize}}const zn=new xt(Q.comparator);function jn(){return zn}const Wn=new xt(Q.comparator);function Hn(...e){let t=Wn;for(const n of e)t=t.insert(n.key,n);return t}function Yn(e){let t=Wn;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Xn(){return Jn()}function Zn(){return Jn()}function Jn(){return new Qn((e=>e.toString()),((e,t)=>e.isEqual(t)))}const er=new xt(Q.comparator),tr=new Nt(Q.comparator);function nr(...e){let t=tr;for(const n of e)t=t.add(n);return t}const rr=new Nt(L);function sr(){return rr}class ir{constructor(e,t,n,r,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,or.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new ir(U.min(),r,sr(),jn(),nr())}}class or{constructor(e,t,n,r,s){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new or(n,t,nr(),nr(),nr())}}class ar{constructor(e,t,n,r){this.It=e,this.removedTargetIds=t,this.key=n,this.Tt=r}}class ur{constructor(e,t){this.targetId=e,this.Et=t}}class cr{constructor(e,t,n=_e.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class lr{constructor(){this.At=0,this.Rt=fr(),this.bt=_e.EMPTY_BYTE_STRING,this.Pt=!1,this.vt=!0}get current(){return this.Pt}get resumeToken(){return this.bt}get Vt(){return 0!==this.At}get St(){return this.vt}Dt(e){e.approximateByteSize()>0&&(this.vt=!0,this.bt=e)}Ct(){let e=nr(),t=nr(),n=nr();return this.Rt.forEach(((r,s)=>{switch(s){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:v()}})),new or(this.bt,this.Pt,e,t,n)}xt(){this.vt=!1,this.Rt=fr()}Nt(e,t){this.vt=!0,this.Rt=this.Rt.insert(e,t)}kt(e){this.vt=!0,this.Rt=this.Rt.remove(e)}Ot(){this.At+=1}Mt(){this.At-=1}Ft(){this.vt=!0,this.Pt=!0}}class hr{constructor(e){this.$t=e,this.Bt=new Map,this.Lt=jn(),this.qt=dr(),this.Ut=new Nt(L)}Kt(e){for(const t of e.It)e.Tt&&e.Tt.isFoundDocument()?this.Gt(t,e.Tt):this.Qt(t,e.key,e.Tt);for(const t of e.removedTargetIds)this.Qt(t,e.key,e.Tt)}jt(e){this.forEachTarget(e,(t=>{const n=this.Wt(t);switch(e.state){case 0:this.zt(t)&&n.Dt(e.resumeToken);break;case 1:n.Mt(),n.Vt||n.xt(),n.Dt(e.resumeToken);break;case 2:n.Mt(),n.Vt||this.removeTarget(t);break;case 3:this.zt(t)&&(n.Ft(),n.Dt(e.resumeToken));break;case 4:this.zt(t)&&(this.Ht(t),n.Dt(e.resumeToken));break;default:v()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Bt.forEach(((e,n)=>{this.zt(n)&&t(n)}))}Jt(e){const t=e.targetId,n=e.Et.count,r=this.Yt(t);if(r){const e=r.target;if(Pt(e))if(0===n){const n=new Q(e.path);this.Qt(t,n,Ft.newNoDocument(n,U.min()))}else I(1===n);else this.Xt(t)!==n&&(this.Ht(t),this.Ut=this.Ut.add(t))}}Zt(e){const t=new Map;this.Bt.forEach(((n,r)=>{const s=this.Yt(r);if(s){if(n.current&&Pt(s.target)){const t=new Q(s.target.path);null!==this.Lt.get(t)||this.te(r,t)||this.Qt(r,t,Ft.newNoDocument(t,e))}n.St&&(t.set(r,n.Ct()),n.xt())}}));let n=nr();this.qt.forEach(((e,t)=>{let r=!0;
1t.forEachWhile((e=>{const t=this.Yt(e);return!t||2===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))})),this.Lt.forEach(((t,n)=>n.setReadTime(e)));const r=new ir(e,t,this.Ut,this.Lt,n);return this.Lt=jn(),this.qt=dr(),this.Ut=new Nt(L),r}Gt(e,t){if(!this.zt(e))return;const n=this.te(e,t.key)?2:0;this.Wt(e).Nt(t.key,n),this.Lt=this.Lt.insert(t.key,t),this.qt=this.qt.insert(t.key,this.ee(t.key).add(e))}Qt(e,t,n){if(!this.zt(e))return;const r=this.Wt(e);this.te(e,t)?r.Nt(t,1):r.kt(t),this.qt=this.qt.insert(t,this.ee(t).delete(e)),n&&(this.Lt=this.Lt.insert(t,n))}removeTarget(e){this.Bt.delete(e)}Xt(e){const t=this.Wt(e).Ct();return this.$t.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ot(e){this.Wt(e).Ot()}Wt(e){let t=this.Bt.get(e);return t||(t=new lr,this.Bt.set(e,t)),t}ee(e){let t=this.qt.get(e);return t||(t=new Nt(L),this.qt=this.qt.insert(e,t)),t}zt(e){const t=null!==this.Yt(e);return t||g("WatchChangeAggregator","Detected inactive target",e),t}Yt(e){const t=this.Bt.get(e);return t&&t.Vt?null:this.$t.ne(e)}Ht(e){this.Bt.set(e,new lr),this.$t.getRemoteKeysForTarget(e).forEach((t=>{this.Qt(e,t,null)}))}te(e,t){return this.$t.getRemoteKeysForTarget(e).has(t)}}function dr(){return new xt(Q.comparator)}function fr(){return new xt(Q.comparator)}const mr={asc:"ASCENDING",desc:"DESCENDING"},gr={"<":"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"},pr={and:"AND",or:"OR"};class yr{constructor(e,t){this.databaseId=e,this.wt=t}}function wr(e,t){return e.wt?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function vr(e,t){return e.wt?t.toBase64():t.toUint8Array()}function Ir(e,t){return wr(e,t.toTimestamp())}function br(e){return I(!!e),U.fromTimestamp(function(e){const t=Ne(e);return new P(t.seconds,t.nanos)}(e))}function Tr(e,t){return function(e){return new K(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function Er(e){const t=K.fromString(e);return I(Qr(t)),t}function Sr(e,t){return Tr(e.databaseId,t.path)}function xr(e,t){const n=Er(t);if(n.get(1)!==e.databaseId.projectId)throw new S(E.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new S(E.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new Q(Cr(n))}function _r(e,t){return Tr(e.databaseId,t)}function Dr(e){const t=Er(e);return 4===t.length?K.emptyPath():Cr(t)}function Nr(e){return new K(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Cr(e){return I(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function Ar(e,t,n){return{name:Sr(e,t),fields:n.value.mapValue.fields}}function kr(e,t,n){const r=xr(e,t.name),s=br(t.updateTime),i=t.createTime?br(t.createTime):U.min(),o=new Rt({mapValue:{fields:t.fields}}),a=Ft.newFoundDocument(r,s,i,o);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Rr(e,t){let n;if(t instanceof Vn)n={update:Ar(e,t.key,t.value)};else if(t instanceof qn)n={delete:Sr(e,t.key)};else if(t instanceof Fn)n={update:Ar(e,t.key,t.data),updateMask:$r(t.fieldMask)};else{if(!(t instanceof Pn))return v();n={verify:Sr(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof gn)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof pn)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof wn)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof In)return{fieldPath:t.field.canonicalString(),increment:n.gt};throw v()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:Ir(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:v()}(e,t.precondition)),n}function Vr(e,t){const n=t.currentDocument?function(e){return void 0!==e.updateTime?xn.updateTime(br(e.updateTime)):void 0!==e.exists?xn.exists(e.exists):xn.none()}(t.currentDocument):xn.none(),r=t.updateTransforms?t.updateTransforms.map((t=>function(e,t){let n=null;if("setToServerValue"in t)I("REQUEST_TIME"===t.setToServerValue),n=new gn;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new pn(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new wn(e)}else"increment"in t?n=new In(e,t.increment):v();const r=$.fromServerFormat(t.fieldPath);return new En(r,n)}(e,t))):[];if(t.update){t.update.name;const s=xr(e,t.update.name),i=new Rt({mapValue:{fields:t.update.fields}});if(t.updateMask){const e=function(e){const t=e.fieldPaths||[];return new kt(t.map((e=>$.fromServerFormat(e))))}(t.updateMask);return new Fn(s,i,e,n,r)}return new Vn(s,i,n,r)}if(t.delete){const r=xr(e,t.delete);return new qn(r,n)}if(t.verify){const r=xr(e,t.verify);return new Pn(r,n)}return v()}function Fr(e,t){return{documents:[_r(e,t.path)]}}function Mr(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=_r(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=_r(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const s=function(e){if(0!==e.length)return Gr(ot.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);const i=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:Br(e.field),direction:qr(e.dir)}}(e)))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);const o=function(e,t){return e.wt||Te(t)?t:{value:t}}(e,t.limit);var a;return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt={before:(a=t.startAt).inclusive,values:a.position}),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function Lr(e){let t=Dr(e.parent);
1const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(r>0){I(1===r);const e=n.from[0];e.allDescendants?s=e.collectionId:t=t.child(e.collectionId)}let i=[];n.where&&(i=function(e){const t=Or(e);return t instanceof ot&&ct(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map((e=>function(e){return new Et(Kr(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e))));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,Te(t)?null:t}(n.limit));let u=null;n.startAt&&(u=function(e){const t=!!e.before,n=e.values||[];return new tt(n,t)}(n.startAt));let c=null;return n.endAt&&(c=function(e){const t=!e.before,n=e.values||[];return new tt(n,t)}(n.endAt)),$t(t,s,o,i,a,"F",u,c)}function Or(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Kr(e.unaryFilter.field);return it.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Kr(e.unaryFilter.field);return it.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Kr(e.unaryFilter.field);return it.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const s=Kr(e.unaryFilter.field);return it.create(s,"!=",{nullValue:"NULL_VALUE"});default:return v()}}(e):void 0!==e.fieldFilter?function(e){return it.create(Kr(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return v()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return ot.create(e.compositeFilter.filters.map((e=>Or(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return v()}}(e.compositeFilter.op))}(e):v()}function qr(e){return mr[e]}function Pr(e){return gr[e]}function Ur(e){return pr[e]}function Br(e){return{fieldPath:e.canonicalString()}}function Kr(e){return $.fromServerFormat(e.fieldPath)}function Gr(e){return e instanceof it?function(e){if("=="===e.op){if(je(e.value))return{unaryFilter:{field:Br(e.field),op:"IS_NAN"}};if(ze(e.value))return{unaryFilter:{field:Br(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(je(e.value))return{unaryFilter:{field:Br(e.field),op:"IS_NOT_NAN"}};if(ze(e.value))return{unaryFilter:{field:Br(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Br(e.field),op:Pr(e.op),value:e.value}}}(e):e instanceof ot?function(e){const t=e.getFilters().map((e=>Gr(e)));return 1===t.length?t[0]:{compositeFilter:{op:Ur(e.op),filters:t}}}(e):v()}function $r(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function Qr(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function zr(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t=Wr(t)),t=jr(e.get(n),t);return Wr(t)}function jr(e,t){let n=t;const r=e.length;for(let s=0;s<r;s++){const t=e.charAt(s);switch(t){case"\0":n+="\x01\x10";break;case"\x01":n+="\x01\x11";break;default:n+=t}}return n}function Wr(e){return e+"\x01\x01"}function Hr(e){const t=e.length;if(I(t>=2),2===t)return I("\x01"===e.charAt(0)&&"\x01"===e.charAt(1)),K.emptyPath();const n=t-2,r=[];let s="";for(let i=0;i<t;){const t=e.indexOf("\x01",i);switch((t<0||t>n)&&v(),e.charAt(t+1)){case"\x01":const n=e.substring(i,t);let o;0===s.length?o=n:(s+=n,o=s,s=""),r.push(o);break;case"\x10":s+=e.substring(i,t),s+="\0";break;case"\x11":s+=e.substring(i,t+1);break;default:v()}i=t+2}return new K(r)}const Yr=["userId","batchId"];function Xr(e,t){return[e,zr(t)]}function Zr(e,t,n){return[e,zr(t),n]}const Jr={},es=["prefixPath","collectionGroup","readTime","documentId"],ts=["prefixPath","collectionGroup","documentId"],ns=["collectionGroup","readTime","prefixPath","documentId"],rs=["canonicalId","targetId"],ss=["targetId","path"],is=["path","targetId"],os=["collectionId","parent"],as=["indexId","uid"],us=["uid","sequenceNumber"],cs=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],ls=["indexId","uid","orderedDocumentKey"],hs=["userId","collectionPath","documentId"],ds=["userId","collectionPath","largestBatchId"],fs=["userId","collectionGroup","largestBatchId"],ms=["mutation
1Queues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],gs=[...ms,"documentOverlays"],ps=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ys=ps,ws=[...ys,"indexConfiguration","indexState","indexEntries"];class vs extends ne{constructor(e,t){super(),this.se=e,this.currentSequenceNumber=t}}function Is(e,t){const n=T(e);return oe.M(n.se,t)}class bs{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const t=this.mutations[r];t.key.isEqual(e.key)&&Cn(t,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=An(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=An(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=Zn();return this.mutations.forEach((r=>{const s=e.get(r.key),i=s.overlayedDocument;let o=this.applyToLocalView(i,s.mutatedFields);o=t.has(r.key)?null:o;const a=Nn(i,o);null!==a&&n.set(r.key,a),i.isValidDocument()||i.convertToNoDocument(U.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),nr())}isEqual(e){return this.batchId===e.batchId&&O(this.mutations,e.mutations,((e,t)=>Rn(e,t)))&&O(this.baseMutations,e.baseMutations,((e,t)=>Rn(e,t)))}}class Ts{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){I(e.mutations.length===n.length);let r=er;const s=e.mutations;for(let i=0;i<s.length;i++)r=r.insert(s[i].key,n[i].version);return new Ts(e,t,n,r)}}class Es{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Ss{constructor(e,t,n,r,s=U.min(),i=U.min(),o=_e.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=o}withSequenceNumber(e){return new Ss(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new Ss(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new Ss(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class xs{constructor(e){this.ie=e}}function _s(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Ds(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:Sr(e,t.key),fields:t.data.value.mapValue.fields,updateTime:wr(e,t.version.toTimestamp()),createTime:wr(e,t.createTime.toTimestamp())}}(e.ie,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Ns(t.version)};else{if(!t.isUnknownDocument())return v();r.unknownDocument={path:n.path.toArray(),version:Ns(t.version)}}return r}function Ds(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Ns(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Cs(e){const t=new P(e.seconds,e.nanoseconds);return U.fromTimestamp(t)}function As(e,t){const n=(t.baseMutations||[]).map((t=>Vr(e.ie,t)));for(let i=0;i<t.mutations.length-1;++i){const e=t.mutations[i];if(i+1<t.mutations.length&&void 0!==t.mutations[i+1].transform){const n=t.mutations[i+1];e.updateTransforms=n.transform.fieldTransforms,t.mutations.splice(i+1,1),++i}}const r=t.mutations.map((t=>Vr(e.ie,t))),s=P.fromMillis(t.localWriteTimeMs);return new bs(t.batchId,s,n,r)}function ks(e){const t=Cs(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?Cs(e.lastLimboFreeSnapshotVersion):U.min();let r;var s;return void 0!==e.query.documents?(I(1===(s=e.query).documents.length),r=Xt(Qt(Dr(s.documents[0])))):r=function(e){return Xt(Lr(e))}(e.query),new Ss(r,e.targetId,0,e.lastListenSequenceNumber,t,n,_e.fromBase64String(e.resumeToken))}function Rs(e,t){const n=Ns(t.snapshotVersion),r=Ns(t.lastLimboFreeSnapshotVersion);let s;s=Pt(t.target)?Fr(e.ie,t.target):Mr(e.ie,t.target);const i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Ot(t.target),readTime:n,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:s}}function Vs(e){const t=Lr({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Jt(t,t.limit,"L"):t}function Fs(e,t){return new Es(t.largestBatchId,Vr(e.ie,t.overlayMutation))}function Ms(e,t){const n=t.path.lastSegment();return[e,zr(t.path.popLast()),n]}function Ls(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:Ns(r.readTime),documentKey:zr(r.documentKey.path),largestBatchId:r.largestBatchId}}class Os{getBundleMetadata(e,t){return qs(e).get(t).next((e=>{if(e)return{id:(t=e).bundleId,createTime:Cs(t.createTime),version:t.version};var t}))}saveBundleMetadata(e,t){return qs(e).put({bundleId:(n=t).id,createTime:Ns(br(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return Ps(e).get(t).next((e=>{if(e)return{name:(t=e).name,query:Vs(t.bundledQuery),readTime:Cs(t.readTime)};var t}))}saveNamedQuery(e,t){return Ps(e).put(function(e){return{name:e.name,readTime:Ns(br(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function qs(e){return Is(e,"bundles")}
1function Ps(e){return Is(e,"namedQueries")}class Us{constructor(e,t){this.yt=e,this.userId=t}static re(e,t){const n=t.uid||"";return new Us(e,n)}getOverlay(e,t){return Bs(e).get(Ms(this.userId,t)).next((e=>e?Fs(this.yt,e):null))}getOverlays(e,t){const n=Xn();return se.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){const r=[];return n.forEach(((n,s)=>{const i=new Es(t,s);r.push(this.oe(e,i))})),se.waitFor(r)}removeOverlaysForBatchId(e,t,n){const r=new Set;t.forEach((e=>r.add(zr(e.getCollectionPath()))));const s=[];return r.forEach((t=>{const r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);s.push(Bs(e).Y("collectionPathOverlayIndex",r))})),se.waitFor(s)}getOverlaysForCollection(e,t,n){const r=Xn(),s=zr(t),i=IDBKeyRange.bound([this.userId,s,n],[this.userId,s,Number.POSITIVE_INFINITY],!0);return Bs(e).W("collectionPathOverlayIndex",i).next((e=>{for(const t of e){const e=Fs(this.yt,t);r.set(e.getKey(),e)}return r}))}getOverlaysForCollectionGroup(e,t,n,r){const s=Xn();let i;const o=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Bs(e).Z({index:"collectionGroupOverlayIndex",range:o},((e,t,n)=>{const o=Fs(this.yt,t);s.size()<r||o.largestBatchId===i?(s.set(o.getKey(),o),i=o.largestBatchId):n.done()})).next((()=>s))}oe(e,t){return Bs(e).put(function(e,t,n){const[r,s,i]=Ms(t,n.mutation.key);return{userId:t,collectionPath:s,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Rr(e.ie,n.mutation)}}(this.yt,this.userId,t))}}function Bs(e){return Is(e,"documentOverlays")}class Ks{constructor(){}ue(e,t){this.ce(e,t),t.ae()}ce(e,t){if("nullValue"in e)this.he(t,5);else if("booleanValue"in e)this.he(t,10),t.le(e.booleanValue?1:0);else if("integerValue"in e)this.he(t,15),t.le(Ce(e.integerValue));else if("doubleValue"in e){const n=Ce(e.doubleValue);isNaN(n)?this.he(t,13):(this.he(t,15),Ee(n)?t.le(0):t.le(n))}else if("timestampValue"in e){const n=e.timestampValue;this.he(t,20),"string"==typeof n?t.fe(n):(t.fe(`${n.seconds||""}`),t.le(n.nanos||0))}else if("stringValue"in e)this.de(e.stringValue,t),this._e(t);else if("bytesValue"in e)this.he(t,30),t.we(Ae(e.bytesValue)),this._e(t);else if("referenceValue"in e)this.me(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.he(t,45),t.le(n.latitude||0),t.le(n.longitude||0)}else"mapValue"in e?Ye(e)?this.he(t,Number.MAX_SAFE_INTEGER):(this.ge(e.mapValue,t),this._e(t)):"arrayValue"in e?(this.ye(e.arrayValue,t),this._e(t)):v()}de(e,t){this.he(t,25),this.pe(e,t)}pe(e,t){t.fe(e)}ge(e,t){const n=e.fields||{};this.he(t,55);for(const r of Object.keys(n))this.de(r,t),this.ce(n[r],t)}ye(e,t){const n=e.values||[];this.he(t,50);for(const r of n)this.ce(r,t)}me(e,t){this.he(t,37),Q.fromName(e).path.forEach((e=>{this.he(t,60),this.pe(e,t)}))}he(e,t){e.le(t)}_e(e){e.le(2)}}function Gs(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}function $s(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=Gs(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}Ks.Ie=new Ks;class Qs{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Te(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ee(n.value),n=t.next();this.Ae()}Re(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.be(n.value),n=t.next();this.Pe()}ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ee(e);else if(e<2048)this.Ee(960|e>>>6),this.Ee(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ee(480|e>>>12),this.Ee(128|63&e>>>6),this.Ee(128|63&e);else{const e=t.codePointAt(0);this.Ee(240|e>>>18),this.Ee(128|63&e>>>12),this.Ee(128|63&e>>>6),this.Ee(128|63&e)}}this.Ae()}Ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.be(e);else if(e<2048)this.be(960|e>>>6),this.be(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.be(480|e>>>12),this.be(128|63&e>>>6),this.be(128|63&e);else{const e=t.codePointAt(0);this.be(240|e>>>18),this.be(128|63&e>>>12),this.be(128|63&e>>>6),this.be(128|63&e)}}this.Pe()}Se(e){const t=this.De(e),n=$s(t);this.Ce(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}xe(e){const t=this.De(e),n=$s(t);this.Ce(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}Ne(){this.ke(255),this.ke(255)}Oe(){this.Me(255),this.Me(255)}reset(){this.position=0}seed(e){this.Ce(e.length),this.buffer.set(e,this.position),this.position+=e.length}Fe(){return this.buffer.slice(0,this.position)}De(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ee(e){const t=255&e;0===t?(this.ke(0),this.ke(255)):255===t?(this.ke(255),this.ke(0)):this.ke(t)}be(e){const t=255&e;0===t?(this.Me(0),this.Me(255)):255===t?(this.Me(255),this.Me(0)):this.Me(e)}Ae(){this.ke(0),this.ke(1)}Pe(){this.Me(0),this.Me(1)}ke(e){this.Ce(1),this.buffer[this.position++]=e}Me(e){this.Ce(1),this.buffer[this.position++]=~e}Ce(e){const t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);
1const r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class zs{constructor(e){this.$e=e}we(e){this.$e.Te(e)}fe(e){this.$e.ve(e)}le(e){this.$e.Se(e)}ae(){this.$e.Ne()}}class js{constructor(e){this.$e=e}we(e){this.$e.Re(e)}fe(e){this.$e.Ve(e)}le(e){this.$e.xe(e)}ae(){this.$e.Oe()}}class Ws{constructor(){this.$e=new Qs,this.Be=new zs(this.$e),this.Le=new js(this.$e)}seed(e){this.$e.seed(e)}qe(e){return 0===e?this.Be:this.Le}Fe(){return this.$e.Fe()}reset(){this.$e.reset()}}class Hs{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Ue(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new Hs(this.indexId,this.documentKey,this.arrayValue,n)}}function Ys(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Xs(e.arrayValue,t.arrayValue),0!==n?n:(n=Xs(e.directionalValue,t.directionalValue),0!==n?n:Q.comparator(e.documentKey,t.documentKey)))}function Xs(e,t){for(let n=0;n<e.length&&n<t.length;++n){const r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}class Zs{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ke=e.orderBy,this.Ge=[];for(const t of e.filters){const e=t;e.isInequality()?this.Qe=e:this.Ge.push(e)}}je(e){I(e.collectionGroup===this.collectionId);const t=j(e);if(void 0!==t&&!this.We(t))return!1;const n=W(e);let r=0,s=0;for(;r<n.length&&this.We(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.Qe){const e=n[r];if(!this.ze(this.Qe,e)||!this.He(this.Ke[s++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(s>=this.Ke.length||!this.He(this.Ke[s++],e))return!1}return!0}We(e){for(const t of this.Ge)if(this.ze(t,e))return!0;return!1}ze(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;const n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}He(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function Js(e){var t,n;if(I(e instanceof it||e instanceof ot),e instanceof it){if(e instanceof It){const r=(null===(n=null===(t=e.value.arrayValue)||void 0===t?void 0:t.values)||void 0===n?void 0:n.map((t=>it.create(e.field,"==",t))))||[];return ot.create(r,"or")}return e}const r=e.filters.map((e=>Js(e)));return ot.create(r,e.op)}function ei(e){if(0===e.getFilters().length)return[];const t=si(Js(e));return I(ri(t)),ti(t)||ni(t)?[t]:t.getFilters()}function ti(e){return e instanceof it}function ni(e){return e instanceof ot&&ct(e)}function ri(e){return ti(e)||ni(e)||function(e){if(e instanceof ot&&ut(e)){for(const t of e.getFilters())if(!ti(t)&&!ni(t))return!1;return!0}return!1}(e)}function si(e){if(I(e instanceof it||e instanceof ot),e instanceof it)return e;if(1===e.filters.length)return si(e.filters[0]);const t=e.filters.map((e=>si(e)));let n=ot.create(t,e.op);return n=ai(n),ri(n)?n:(I(n instanceof ot),I(at(n)),I(n.filters.length>1),n.filters.reduce(((e,t)=>ii(e,t))))}function ii(e,t){let n;return I(e instanceof it||e instanceof ot),I(t instanceof it||t instanceof ot),n=e instanceof it?t instanceof it?function(e,t){return ot.create([e,t],"and")}(e,t):oi(e,t):t instanceof it?oi(t,e):function(e,t){if(I(e.filters.length>0&&t.filters.length>0),at(e)&&at(t))return ft(e,t.getFilters());const n=ut(e)?e:t,r=ut(e)?t:e,s=n.filters.map((e=>ii(e,r)));return ot.create(s,"or")}(e,t),ai(n)}function oi(e,t){if(at(t))return ft(t,e.getFilters());{const n=t.filters.map((t=>ii(e,t)));return ot.create(n,"or")}}function ai(e){if(I(e instanceof it||e instanceof ot),e instanceof it)return e;const t=e.getFilters();if(1===t.length)return ai(t[0]);if(lt(e))return e;const n=t.map((e=>ai(e))),r=[];return n.forEach((t=>{t instanceof it?r.push(t):t instanceof ot&&(t.op===e.op?r.push(...t.filters):r.push(t))})),1===r.length?r[0]:ot.create(r,e.op)}class ui{constructor(){this.Je=new ci}addToCollectionParentIndex(e,t){return this.Je.add(t),se.resolve()}getCollectionParents(e,t){return se.resolve(this.Je.getEntries(t))}addFieldIndex(e,t){return se.resolve()}deleteFieldIndex(e,t){return se.resolve()}getDocumentsMatchingTarget(e,t){return se.resolve(null)}getIndexType(e,t){return se.resolve(0)}getFieldIndexes(e,t){return se.resolve([])}getNextCollectionGroupToUpdate(e){return se.resolve(null)}getMinOffset(e,t){return se.resolve(J.min())}getMinOffsetFromCollectionGroup(e,t){return se.resolve(J.min())}updateCollectionGroup(e,t,n){return se.resolve()}updateIndexEntries(e,t){return se.resolve()}}class ci{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Nt(K.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new Nt(K.comparator)).toArray()}}const li=new Uint8Array(0);class hi{constructor(e,t){this.user=e,this.databaseId=t,this.Ye=new ci,this.Xe=new Qn((e=>Ot(e)),((e,t)=>qt(e,t))),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.Ye.has(t)){const n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener((()=>{this.Ye.add(t)}));const s={collectionId:n,parent:zr(r)};return di(e).put(s)}return se.resolve()}getCollectionParents(e,t){const n=[],r=IDBKeyRange.bound([t,""],[q(t),""],!1,!0);return di(e).W(r).next((e=>{for(const r of e){if(r.collectionId!==t)break;n.push(Hr(r.parent))}return n}))}addFieldIndex(e,t){const n=mi(e),r=function(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map((e=>[e.fieldPath.canonicalString(),e.kind]))}}(t);delete r.indexId;const s=n.add(r);if(t.indexState){const n=gi(e);return s.next((e=>{n.put(Ls(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))}))}return s.next()}deleteFieldIndex(e,t){const n=mi(e),r=gi(e),s=fi(e);return n.delete(t.indexId).next((()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))).next((()=>s.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))))}getDocumentsMatchingTarget(e,t){const n=fi(e);let r=!0;const s=new Map;return se.forEach(this.Ze(t),(t=>this.tn(e,t).next((e=>{r&&(r=!!e),s.set(t,e)})))).next((()=>
vendor: 4,831 bytes, line 1
1{if(r){let e=nr();const r=[];return se.forEach(s,((s,i)=>{var o;g("IndexedDbIndexManager",`Using index ${o=s,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((e=>`${e.fieldPath}:${e.kind}`)).join(",")}`} to execute ${Ot(t)}`);const a=function(e,t){const n=j(t);if(void 0===n)return null;for(const r of Ut(e,n.fieldPath))switch(r.op){case"array-contains-any":return r.value.arrayValue.values||[];case"array-contains":return[r.value]}return null}(i,s),u=function(e,t){const n=new Map;for(const r of W(t))for(const t of Ut(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(i,s),c=function(e,t){const n=[];let r=!0;for(const s of W(t)){const t=0===s.kind?Bt(e,s.fieldPath,e.startAt):Kt(e,s.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new tt(n,r)}(i,s),l=function(e,t){const n=[];let r=!0;for(const s of W(t)){const t=0===s.kind?Kt(e,s.fieldPath,e.endAt):Bt(e,s.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new tt(n,r)}(i,s),h=this.en(s,i,c),d=this.en(s,i,l),f=this.nn(s,i,u),m=this.sn(s.indexId,a,h,c.inclusive,d,l.inclusive,f);return se.forEach(m,(s=>n.J(s,t.limit).next((t=>{t.forEach((t=>{const n=Q.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))}))}))))})).next((()=>r))}return se.resolve(null)}))}Ze(e){let t=this.Xe.get(e);return t||(t=0===e.filters.length?[e]:ei(ot.create(e.filters,"and")).map((t=>Lt(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt))),this.Xe.set(e,t),t)}sn(e,t,n,r,s,i,o){const a=(null!=t?t.length:1)*Math.max(n.length,s.length),u=a/(null!=t?t.length:1),c=[];for(let l=0;l<a;++l){const a=t?this.rn(t[l/u]):li,h=this.on(e,a,n[l%u],r),d=this.un(e,a,s[l%u],i),f=o.map((t=>this.on(e,a,t,!0)));c.push(...this.createRange(h,d,f))}return c}on(e,t,n,r){const s=new Hs(e,Q.empty(),t,n);return r?s:s.Ue()}un(e,t,n,r){const s=new Hs(e,Q.empty(),t,n);return r?s.Ue():s}tn(e,t){const n=new Zs(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next((e=>{let t=null;for(const r of e)n.je(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t}))}getIndexType(e,t){let n=2;const r=this.Ze(t);return se.forEach(r,(t=>this.tn(e,t).next((e=>{e?0!==n&&e.fields.length<function(e){let t=new Nt($.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const r of e.orderBy)r.field.isKeyField()||(t=t.add(r.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})))).next((()=>function(e){return null!==e.limit}(t)&&r.length>1&&2===n?1:n))}cn(e,t){const n=new Ws;for(const r of W(e)){const e=t.data.field(r.fieldPath);if(null==e)return null;const s=n.qe(r.kind);Ks.Ie.ue(e,s)}return n.Fe()}rn(e){const t=new Ws;return Ks.Ie.ue(e,t.qe(0)),t.Fe()}an(e,t){const n=new Ws;return Ks.Ie.ue(Ge(this.databaseId,t),n.qe(function(e){const t=W(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Fe()}nn(e,t,n){if(null===n)return[];let r=[];r.push(new Ws);let s=0;for(const i of W(e)){const e=n[s++];for(const n of r)if(this.hn(t,i.fieldPath)&&Qe(e))r=this.ln(r,i,e);else{const t=n.qe(i.kind);Ks.Ie.ue(e,t)}}return this.fn(r)}en(e,t,n){return this.nn(e,t,n.position)}fn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Fe();return t}ln(e,t,n){const r=[...e],s=[];for(const i of n.arrayValue.values||[])for(const e of r){const n=new Ws;n.seed(e.Fe()),Ks.Ie.ue(i,n.qe(t.kind)),s.push(n)}return s}hn(e,t){return!!e.filters.find((e=>e instanceof it&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op)))}getFieldIndexes(e,t){const n=mi(e),r=gi(e);return(t?n.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.W()).next((e=>{const t=[];return se.forEach(e,(e=>r.get([e.indexId,this.uid]).next((n=>{t.push(function(e,t){const n=t?new Y(t.sequenceNumber,new J(Cs(t.readTime),new Q(Hr(t.documentKey)),t.largestBatchId)):Y.empty(),r=e.fields.map((([e,t])=>new H($.fromServerFormat(e),t)));return new z(e.indexId,e.collectionGroup,r,n)}(e,n))})))).next((()=>t))}))}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next((e=>0===e.length?null:(e.sort(((e,t)=>{const n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:L(e.collectionGroup,t.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(e,t,n){const r=mi(e),s=gi(e);return this.dn(e).next((e=>r.W("collectionGroupIndex",IDBKeyRange.bound(t,t)).next((t=>se.forEach(t,(t=>s.put(Ls(t.indexId,this.user,e,n))))))))}updateIndexEntries(e,t){const n=new Map;return se.forEach(t,((t,r)=>{const s=n.get(t.collectionGroup);return(s?se.resolve(s):this.getFieldIndexes(e,t.collectionGroup)).next((s=>(n.set(t.collectionGroup,s),se.forEach(s,(n=>
1this._n(e,t,n).next((t=>{const s=this.wn(r,n);return t.isEqual(s)?se.resolve():this.mn(e,r,n,t,s)})))))))}))}gn(e,t,n,r){return fi(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.an(n,t.key),documentKey:t.key.path.toArray()})}yn(e,t,n,r){return fi(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.an(n,t.key),t.key.path.toArray()])}_n(e,t,n){const r=fi(e);let s=new Nt(Ys);return r.Z({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.an(n,t)])},((e,r)=>{s=s.add(new Hs(n.indexId,t,r.arrayValue,r.directionalValue))})).next((()=>s))}wn(e,t){let n=new Nt(Ys);const r=this.cn(t,e);if(null==r)return n;const s=j(t);if(null!=s){const i=e.data.field(s.fieldPath);if(Qe(i))for(const s of i.arrayValue.values||[])n=n.add(new Hs(t.indexId,e.key,this.rn(s),r))}else n=n.add(new Hs(t.indexId,e.key,li,r));return n}mn(e,t,n,r,s){g("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);const i=[];return function(e,t,n,r,s){const i=e.getIterator(),o=t.getIterator();let a=At(i),u=At(o);for(;a||u;){let e=!1,t=!1;if(a&&u){const r=n(a,u);r<0?t=!0:r>0&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(u),u=At(o)):t?(s(a),a=At(i)):(a=At(i),u=At(o))}}(r,s,Ys,(r=>{i.push(this.gn(e,t,n,r))}),(r=>{i.push(this.yn(e,t,n,r))})),se.waitFor(i)}dn(e){let t=1;return gi(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},((e,n,r)=>{r.done(),t=n.sequenceNumber+1})).next((()=>t))}createRange(e,t,n){n=n.sort(((e,t)=>Ys(e,t))).filter(((e,t,n)=>!t||0!==Ys(e,n[t-1])));const r=[];r.push(e);for(const i of n){const n=Ys(i,e),s=Ys(i,t);if(0===n)r[0]=e.Ue();else if(n>0&&s<0)r.push(i),r.push(i.Ue());else if(s>0)break}r.push(t);const s=[];for(let i=0;i<r.length;i+=2){if(this.pn(r[i],r[i+1]))return[];const e=[r[i].indexId,this.uid,r[i].arrayValue,r[i].directionalValue,li,[]],t=[r[i+1].indexId,this.uid,r[i+1].arrayValue,r[i+1].directionalValue,li,[]];s.push(IDBKeyRange.bound(e,t))}return s}pn(e,t){return Ys(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(pi)}getMinOffset(e,t){return se.mapArray(this.Ze(t),(t=>this.tn(e,t).next((e=>e||v())))).next(pi)}}function di(e){return Is(e,"collectionParents")}function fi(e){return Is(e,"indexEntries")}function mi(e){return Is(e,"indexConfiguration")}function gi(e){return Is(e,"indexState")}function pi(e){I(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){const s=e[r].indexState.offset;ee(s,t)<0&&(t=s),n<s.largestBatchId&&(n=s.largestBatchId)}return new J(t.readTime,t.documentKey,n)}const yi={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class wi{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new wi(e,wi.DEFAULT_COLLECTION_PERCENTILE,wi.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function vi(e,t,n){const r=e.store("mutations"),s=e.store("documentMutations"),i=[],o=IDBKeyRange.only(n.batchId);let a=0;const u=r.Z({range:o},((e,t,n)=>(a++,n.delete())));i.push(u.next((()=>{I(1===a)})));const c=[];for(const l of n.mutations){const e=Zr(t,l.key.path,n.batchId);i.push(s.delete(e)),c.push(l.key)}return se.waitFor(i).next((()=>c))}function Ii(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw v();t=e.noDocument}return JSON.stringify(t).length}wi.DEFAULT_COLLECTION_PERCENTILE=10,wi.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,wi.DEFAULT=new wi(41943040,wi.DEFAULT_COLLECTION_PERCENTILE,wi.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),wi.DISABLED=new wi(-1,0,0);class bi{constructor(e,t,n,r){this.userId=e,this.yt=t,this.indexManager=n,this.referenceDelegate=r,this.In={}}static re(e,t,n,r){I(""!==e.uid);const s=e.isAuthenticated()?e.uid:"";return new bi(s,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Ei(e).Z({index:"userMutationsIndex",range:n},((e,n,r)=>{t=!1,r.done()})).next((()=>t))}addMutationBatch(e,t,n,r){const s=Si(e),i=Ei(e);return i.add({}).next((o=>{I("number"==typeof o);const a=new bs(o,t,n,r),u=function(e,t,n){const r=n.baseMutations.map((t=>Rr(e.ie,t))),s=n.mutations.map((t=>Rr(e.ie,t)));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:s}}(this.yt,this.userId,a),c=[];let l=new Nt(((e,t)=>L(e.canonicalString(),t.canonicalString())));for(const e of r){const t=Zr(this.userId,e.key.path,o);l=l.add(e.key.path.popLast()),c.push(i.put(u)),c.push(s.put(t,Jr))}return l.forEach((t=>{c.push(this.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((()=>{this.In[o]=a.keys()})),se.waitFor(c).next((()=>a))}
vendor: 7,348 bytes, line 1
1))}lookupMutationBatch(e,t){return Ei(e).get(t).next((e=>e?(I(e.userId===this.userId),As(this.yt,e)):null))}Tn(e,t){return this.In[t]?se.resolve(this.In[t]):this.lookupMutationBatch(e,t).next((e=>{if(e){const n=e.keys();return this.In[t]=n,n}return null}))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]);let s=null;return Ei(e).Z({index:"userMutationsIndex",range:r},((e,t,r)=>{t.userId===this.userId&&(I(t.batchId>=n),s=As(this.yt,t)),r.done()})).next((()=>s))}getHighestUnacknowledgedBatchId(e){const t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=-1;return Ei(e).Z({index:"userMutationsIndex",range:t,reverse:!0},((e,t,r)=>{n=t.batchId,r.done()})).next((()=>n))}getAllMutationBatches(e){const t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Ei(e).W("userMutationsIndex",t).next((e=>e.map((e=>As(this.yt,e)))))}getAllMutationBatchesAffectingDocumentKey(e,t){const n=Xr(this.userId,t.path),r=IDBKeyRange.lowerBound(n),s=[];return Si(e).Z({range:r},((n,r,i)=>{const[o,a,u]=n,c=Hr(a);if(o===this.userId&&t.path.isEqual(c))return Ei(e).get(u).next((e=>{if(!e)throw v();I(e.userId===this.userId),s.push(As(this.yt,e))}));i.done()})).next((()=>s))}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new Nt(L);const r=[];return t.forEach((t=>{const s=Xr(this.userId,t.path),i=IDBKeyRange.lowerBound(s),o=Si(e).Z({range:i},((e,r,s)=>{const[i,o,a]=e,u=Hr(o);i===this.userId&&t.path.isEqual(u)?n=n.add(a):s.done()}));r.push(o)})),se.waitFor(r).next((()=>this.En(e,n)))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1,s=Xr(this.userId,n),i=IDBKeyRange.lowerBound(s);let o=new Nt(L);return Si(e).Z({range:i},((e,t,s)=>{const[i,a,u]=e,c=Hr(a);i===this.userId&&n.isPrefixOf(c)?c.length===r&&(o=o.add(u)):s.done()})).next((()=>this.En(e,o)))}En(e,t){const n=[],r=[];return t.forEach((t=>{r.push(Ei(e).get(t).next((e=>{if(null===e)throw v();I(e.userId===this.userId),n.push(As(this.yt,e))})))})),se.waitFor(r).next((()=>n))}removeMutationBatch(e,t){return vi(e.se,this.userId,t).next((n=>(e.addOnCommittedListener((()=>{this.An(t.batchId)})),se.forEach(n,(t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))))}An(e){delete this.In[e]}performConsistencyCheck(e){return this.checkEmpty(e).next((t=>{if(!t)return se.resolve();const n=IDBKeyRange.lowerBound([this.userId]),r=[];return Si(e).Z({range:n},((e,t,n)=>{if(e[0]===this.userId){const t=Hr(e[1]);r.push(t)}else n.done()})).next((()=>{I(0===r.length)}))}))}containsKey(e,t){return Ti(e,this.userId,t)}Rn(e){return xi(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function Ti(e,t,n){const r=Xr(t,n.path),s=r[1],i=IDBKeyRange.lowerBound(r);let o=!1;return Si(e).Z({range:i,X:!0},((e,n,r)=>{const[i,a,u]=e;i===t&&a===s&&(o=!0),r.done()})).next((()=>o))}function Ei(e){return Is(e,"mutations")}function Si(e){return Is(e,"documentMutations")}function xi(e){return Is(e,"mutationQueues")}class _i{constructor(e){this.bn=e}next(){return this.bn+=2,this.bn}static Pn(){return new _i(0)}static vn(){return new _i(-1)}}class Di{constructor(e,t){this.referenceDelegate=e,this.yt=t}allocateTargetId(e){return this.Vn(e).next((t=>{const n=new _i(t.highestTargetId);return t.highestTargetId=n.next(),this.Sn(e,t).next((()=>t.highestTargetId))}))}getLastRemoteSnapshotVersion(e){return this.Vn(e).next((e=>U.fromTimestamp(new P(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))))}getHighestSequenceNumber(e){return this.Vn(e).next((e=>e.highestListenSequenceNumber))}setTargetsMetadata(e,t,n){return this.Vn(e).next((r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.Sn(e,r))))}addTargetData(e,t){return this.Dn(e,t).next((()=>this.Vn(e).next((n=>(n.targetCount+=1,this.Cn(t,n),this.Sn(e,n))))))}updateTargetData(e,t){return this.Dn(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next((()=>Ni(e).delete(t.targetId))).next((()=>this.Vn(e))).next((t=>(I(t.targetCount>0),t.targetCount-=1,this.Sn(e,t))))}removeTargets(e,t,n){let r=0;const s=[];return Ni(e).Z(((i,o)=>{const a=ks(o);a.sequenceNumber<=t&&null===n.get(a.targetId)&&(r++,s.push(this.removeTargetData(e,a)))})).next((()=>se.waitFor(s))).next((()=>r))}forEachTarget(e,t){return Ni(e).Z(((e,n)=>{const r=ks(n);t(r)}))}Vn(e){return Ci(e).get("targetGlobalKey").next((e=>(I(null!==e),e)))}Sn(e,t){return Ci(e).put("targetGlobalKey",t)}Dn(e,t){return Ni(e).put(Rs(this.yt,t))}Cn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Vn(e).next((e=>e.targetCount))}getTargetData(e,t){const n=Ot(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]);let s=null;return Ni(e).Z({range:r,index:"queryTargetsIndex"},((e,n,r)=>{const i=ks(n);qt(t,i.target)&&(s=i,r.done())})).next((()=>s))}addMatchingKeys(e,t,n){const r=[],s=Ai(e);return t.forEach((t=>{const i=zr(t.path);r.push(s.put({targetId:n,path:i})),r.push(this.referenceDelegate.addReference(e,n,t))})),se.waitFor(r)}removeMatchingKeys(e,t,n){const r=Ai(e);return se.forEach(t,(t=>{const s=zr(t.path);return se.waitFor([r.delete([n,s]),this.referenceDelegate.removeReference(e,n,t)])}))}removeMatchingKeysForTargetId(e,t){const n=Ai(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=Ai(e);let s=nr();return r.Z({range:n,X:!0},((e,t,n)=>{const r=Hr(e[1]),i=new Q(r);s=s.add(i)})).next((()=>s))}containsKey(e,t){const n=zr(t.path),r=IDBKeyRange.bound([n],[q(n)],!1,!0);let s=0;return Ai(e).Z({index:"documentTargetsIndex",X:!0,range:r},(([e,t],n,r)=>{0!==e&&(s++,r.done())})).next((()=>s>0))}ne(e,t){return Ni(e).get(t).next((e=>e?ks(e):null))}}function Ni(e){return Is(e,"targets")}function Ci(e){return Is(e,"targetGlobal")}function Ai(e){return Is(e,"targetDocuments")}function ki([e,t],[n,r]){const s=L(e,n);return 0===s?L(t,r):s}class Ri{constructor(e){this.xn=e,this.buffer=new Nt(ki),this.Nn=0}kn(){return++this.Nn}On(e){const t=[e,this.kn()];if(this.buffer.size<this.xn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();ki(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Vi{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Mn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Fn(6e4)}stop(){this.Mn&&(this.Mn.cancel(),this.Mn=null)}get started(){return null!==this.Mn}Fn(e){g("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Mn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,(async()=>{this.Mn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){ce(e)?g("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await re(e)}await this.Fn(3e5)}))}}class Fi{constructor(e,t){this.$n=e,this.params=t}calculateTargetCount(e,t){return this.$n.Bn(e).next((e=>Math.floor(t/100*e)))}nthSequenceNumber(e,t){if(0===t)return se.resolve(pe.at);const n=new Ri(t);
1return this.$n.forEachTarget(e,(e=>n.On(e.sequenceNumber))).next((()=>this.$n.Ln(e,(e=>n.On(e))))).next((()=>n.maxValue))}removeTargets(e,t,n){return this.$n.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.$n.removeOrphanedDocuments(e,t)}collect(e,t){return-1===this.params.cacheSizeCollectionThreshold?(g("LruGarbageCollector","Garbage collection skipped; disabled"),se.resolve(yi)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(g("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),yi):this.qn(e,t)))}getCacheSize(e){return this.$n.getCacheSize(e)}qn(e,t){let n,r,s,o,a,u,c;const l=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((t=>(t>this.params.maximumSequenceNumbersToCollect?(g("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,o=Date.now(),this.nthSequenceNumber(e,r)))).next((r=>(n=r,a=Date.now(),this.removeTargets(e,n,t)))).next((t=>(s=t,u=Date.now(),this.removeOrphanedDocuments(e,n)))).next((e=>(c=Date.now(),f()<=i.in.DEBUG&&g("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-l}ms\n\tDetermined least recently used ${r} in `+(a-o)+"ms\n"+`\tRemoved ${s} targets in `+(u-a)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-l}ms`),se.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:s,documentsRemoved:e}))))}}class Mi{constructor(e,t){this.db=e,this.garbageCollector=function(e,t){return new Fi(e,t)}(this,t)}Bn(e){const t=this.Un(e);return this.db.getTargetCache().getTargetCount(e).next((e=>t.next((t=>e+t))))}Un(e){let t=0;return this.Ln(e,(e=>{t++})).next((()=>t))}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Ln(e,t){return this.Kn(e,((e,n)=>t(n)))}addReference(e,t,n){return Li(e,n)}removeReference(e,t,n){return Li(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Li(e,t)}Gn(e,t){return function(e,t){let n=!1;return xi(e).tt((r=>Ti(e,r,t).next((e=>(e&&(n=!0),se.resolve(!e)))))).next((()=>n))}(e,t)}removeOrphanedDocuments(e,t){const n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[];let s=0;return this.Kn(e,((i,o)=>
1{if(o<=t){const t=this.Gn(e,i).next((t=>{if(!t)return s++,n.getEntry(e,i).next((()=>(n.removeEntry(i,U.min()),Ai(e).delete([0,zr(i.path)]))))}));r.push(t)}})).next((()=>se.waitFor(r))).next((()=>n.apply(e))).next((()=>s))}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Li(e,t)}Kn(e,t){const n=Ai(e);let r,s=pe.at;return n.Z({index:"documentTargetsIndex"},(([e,n],{path:i,sequenceNumber:o})=>{0===e?(s!==pe.at&&t(new Q(Hr(r)),s),s=o,r=i):s=pe.at})).next((()=>{s!==pe.at&&t(new Q(Hr(r)),s)}))}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Li(e,t){return Ai(e).put(function(e,t){return{targetId:0,path:zr(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}class Oi{constructor(){this.changes=new Qn((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,Ft.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?se.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class qi{constructor(e){this.yt=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return Ki(e).put(n)}removeEntry(e,t,n){return Ki(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Ds(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next((n=>(n.byteSize+=t,this.Qn(e,n))))}getEntry(e,t){let n=Ft.newInvalidDocument(t);return Ki(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Gi(t))},((e,r)=>{n=this.jn(t,r)})).next((()=>n))}Wn(e,t){let n={size:0,document:Ft.newInvalidDocument(t)};return Ki(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Gi(t))},((e,r)=>{n={document:this.jn(t,r),size:Ii(r)}})).next((()=>n))}getEntries(e,t){let n=jn();return this.zn(e,t,((e,t)=>{const r=this.jn(e,t);n=n.insert(e,r)})).next((()=>n))}Hn(e,t){let n=jn(),r=new xt(Q.comparator);return this.zn(e,t,((e,t)=>{const s=this.jn(e,t);n=n.insert(e,s),r=r.insert(e,Ii(t))})).next((()=>({documents:n,Jn:r})))}zn(e,t,n){if(t.isEmpty())return se.resolve();let r=new Nt(Qi);t.forEach((e=>r=r.add(e)));const s=IDBKeyRange.bound(Gi(r.first()),Gi(r.last())),i=r.getIterator();let o=i.getNext();return Ki(e).Z({index:"documentKeyIndex",range:s},((e,t,r)=>{const s=Q.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;o&&Qi(o,s)<0;)n(o,null),o=i.getNext();o&&o.isEqual(s)&&(n(o,t),o=i.hasNext()?i.getNext():null),o?r.j(Gi(o)):r.done()})).next((()=>{for(;o;)n(o,null),o=i.hasNext()?i.getNext():null}))}getAllFromCollection(e,t,n){const r=[t.popLast().toArray(),t.lastSegment(),Ds(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],s=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Ki(e).W(IDBKeyRange.bound(r,s,!0)).next((e=>{let t=jn();for(const n of e){const e=this.jn(Q.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t}))}getAllFromCollectionGroup(e,t,n,r){let s=jn();const i=$i(t,n),o=$i(t,J.max());return Ki(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(i,o,!0)},((e,t,n)=>{const i=this.jn(Q.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(i.key,i),s.size===r&&n.done()})).next((()=>s))}newChangeBuffer(e){return new Ui(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next((e=>e.byteSize))}getMetadata(e){return Bi(e).get("remoteDocumentGlobalKey").next((e=>(I(!!e),e)))}Qn(e,t){return Bi(e).put("remoteDocumentGlobalKey",t)}jn(e,t){if(t){const e=function(e,t){let n;if(t.document)n=kr(e.ie,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=Q.fromSegments(t.noDocument.path),r=Cs(t.noD
vendor: 5,279 bytes, line 1
1ocument.readTime);n=Ft.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return v();{const e=Q.fromSegments(t.unknownDocument.path),r=Cs(t.unknownDocument.version);n=Ft.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){const t=new P(e[0],e[1]);return U.fromTimestamp(t)}(t.readTime)),n}(this.yt,t);if(!e.isNoDocument()||!e.version.isEqual(U.min()))return e}return Ft.newInvalidDocument(e)}}function Pi(e){return new qi(e)}class Ui extends Oi{constructor(e,t){super(),this.Yn=e,this.trackRemovals=t,this.Xn=new Qn((e=>e.toString()),((e,t)=>e.isEqual(t)))}applyChanges(e){const t=[];let n=0,r=new Nt(((e,t)=>L(e.canonicalString(),t.canonicalString())));return this.changes.forEach(((s,i)=>{const o=this.Xn.get(s);if(t.push(this.Yn.removeEntry(e,s,o.readTime)),i.isValidDocument()){const a=_s(this.Yn.yt,i);r=r.add(s.path.popLast());const u=Ii(a);n+=u-o.size,t.push(this.Yn.addEntry(e,s,a))}else if(n-=o.size,this.trackRemovals){const n=_s(this.Yn.yt,i.convertToNoDocument(U.min()));t.push(this.Yn.addEntry(e,s,n))}})),r.forEach((n=>{t.push(this.Yn.indexManager.addToCollectionParentIndex(e,n))})),t.push(this.Yn.updateMetadata(e,n)),se.waitFor(t)}getFromCache(e,t){return this.Yn.Wn(e,t).next((e=>(this.Xn.set(t,{size:e.size,readTime:e.document.readTime}),e.document)))}getAllFromCache(e,t){return this.Yn.Hn(e,t).next((({documents:e,Jn:t})=>(t.forEach(((t,n)=>{this.Xn.set(t,{size:n,readTime:e.get(t).readTime})})),e)))}}function Bi(e){return Is(e,"remoteDocumentGlobal")}function Ki(e){return Is(e,"remoteDocumentsV14")}function Gi(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function $i(e,t){const n=t.documentKey.path.toArray();return[e,Ds(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function Qi(e,t){const n=e.path.toArray(),r=t.path.toArray();let s=0;for(let i=0;i<n.length-2&&i<r.length-2;++i)if(s=L(n[i],r[i]),s)return s;return s=L(n.length,r.length),s||(s=L(n[n.length-2],r[r.length-2]),s||L(n[n.length-1],r[r.length-1]))}class zi{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class ji{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((r=>(n=r,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&An(n.mutation,e,kt.empty(),P.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,nr()).next((()=>t))))}getLocalViewOfDocuments(e,t,n=nr()){const r=Xn();return this.populateOverlays(e,r,t).next((()=>this.computeViews(e,t,r,n).next((e=>{let t=Hn();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=Xn();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,nr())))}populateOverlays(e,t,n){const r=[];return n.forEach((e=>{t.has(e)||r.push(e)})),this.documentOverlayCache.getOverlays(e,r).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,r){let s=jn();const i=Jn(),o=Jn();return t.forEach(((e,t)=>{const o=n.get(t.key);r.has(t.key)&&(void 0===o||o.mutation instanceof Fn)?s=s.insert(t.key,t):void 0!==o&&(i.set(t.key,o.mutation.getFieldMask()),An(o.mutation,t,o.mutation.getFieldMask(),P.now()))})),this.recalculateAndSaveOverlays(e,s).next((e=>(e.forEach(((e,t)=>i.set(e,t))),t.forEach(((e,t)=>{var n;return o.set(e,new zi(t,null!==(n=i.get(e))&&void 0!==n?n:null))})),o)))}recalculateAndSaveOverlays(e,t){const n=Jn();let r=new xt(((e,t)=>e-t)),s=nr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const s of e)s.keys().forEach((e=>{const i=t.get(e);if(null===i)return;let o=n.get(e)||kt.empty();o=s.applyToLocalView(i,o),n.set(e,o);const a=(r.get(s.batchId)||nr()).add(e);r=r.insert(s.batchId,a)}))})).next((()=>{const i=[],o=r.getReverseIterator();for(;o.hasNext();){const r=o.getNext(),a=r.key,u=r.value,c=Zn();u.forEach((e=>{if(!s.has(e)){const r=Nn(t.get(e),n.get(e));null!==r&&c.set(e,r),s=s.add(e)}})),i.push(this.documentOverlayCache.saveOverlays(e,a,c))}return se.waitFor(i)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n){return function(e){return Q.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Ht(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next((s=>{const i=r-s.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-s.size):se.resolve(Xn());let o=-1,a=s;return i.next((t=>se.forEach(t,((t,n)=>(o<n.largestBatchId&&(o=n.largestBatchId),s.get(t)?se.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{a=a.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,s))).next((()=>this.computeViews(e,a,t,nr()))).next((e=>({batchId:o,changes:Yn(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new Q(t)).next((e=>{let t=Hn();
vendor: 12,043 bytes, line 1
1return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n){const r=t.collectionGroup;let s=Hn();return this.indexManager.getCollectionParents(e,r).next((i=>se.forEach(i,(i=>{const o=function(e,t){return new Gt(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,i.child(r));return this.getDocumentsMatchingCollectionQuery(e,o,n).next((e=>{e.forEach(((e,t)=>{s=s.insert(e,t)}))}))})).next((()=>s))))}getDocumentsMatchingCollectionQuery(e,t,n){let r;return this.remoteDocumentCache.getAllFromCollection(e,t.path,n).next((s=>(r=s,this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId)))).next((e=>{e.forEach(((e,t)=>{const n=t.getKey();null===r.get(n)&&(r=r.insert(n,Ft.newInvalidDocument(n)))}));let n=Hn();return r.forEach(((r,s)=>{const i=e.get(r);void 0!==i&&An(i.mutation,s,kt.empty(),P.now()),rn(t,s)&&(n=n.insert(r,s))})),n}))}}class Wi{constructor(e){this.yt=e,this.Zn=new Map,this.ts=new Map}getBundleMetadata(e,t){return se.resolve(this.Zn.get(t))}saveBundleMetadata(e,t){var n;return this.Zn.set(t.id,{id:(n=t).id,version:n.version,createTime:br(n.createTime)}),se.resolve()}getNamedQuery(e,t){return se.resolve(this.ts.get(t))}saveNamedQuery(e,t){return this.ts.set(t.name,function(e){return{name:e.name,query:Vs(e.bundledQuery),readTime:br(e.readTime)}}(t)),se.resolve()}}class Hi{constructor(){this.overlays=new xt(Q.comparator),this.es=new Map}getOverlay(e,t){return se.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Xn();return se.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){return n.forEach(((n,r)=>{this.oe(e,t,r)})),se.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.es.get(n);return void 0!==r&&(r.forEach((e=>this.overlays=this.overlays.remove(e))),this.es.delete(n)),se.resolve()}getOverlaysForCollection(e,t,n){const r=Xn(),s=t.length+1,i=new Q(t.child("")),o=this.overlays.getIteratorFrom(i);for(;o.hasNext();){const e=o.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return se.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let s=new xt(((e,t)=>e-t));const i=this.overlays.getIterator();for(;i.hasNext();){const e=i.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=s.get(e.largestBatchId);null===t&&(t=Xn(),s=s.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=Xn(),a=s.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach(((e,t)=>o.set(e,t))),!(o.size()>=r)););return se.resolve(o)}oe(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.es.get(r.largestBatchId).delete(n.key);this.es.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new Es(t,n));let s=this.es.get(t);void 0===s&&(s=nr(),this.es.set(t,s)),this.es.set(t,s.add(n.key))}}class Yi{constructor(){this.ns=new Nt(Xi.ss),this.rs=new Nt(Xi.os)}isEmpty(){return this.ns.isEmpty()}addReference(e,t){const n=new Xi(e,t);this.ns=this.ns.add(n),this.rs=this.rs.add(n)}us(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.cs(new Xi(e,t))}hs(e,t){e.forEach((e=>this.removeReference(e,t)))}ls(e){const t=new Q(new K([])),n=new Xi(t,e),r=new Xi(t,e+1),s=[];return this.rs.forEachInRange([n,r],(e=>{this.cs(e),s.push(e.key)})),s}fs(){this.ns.forEach((e=>this.cs(e)))}cs(e){this.ns=this.ns.delete(e),this.rs=this.rs.delete(e)}ds(e){const t=new Q(new K([])),n=new Xi(t,e),r=new Xi(t,e+1);let s=nr();return this.rs.forEachInRange([n,r],(e=>{s=s.add(e.key)})),s}containsKey(e){const t=new Xi(e,0),n=this.ns.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class Xi{constructor(e,t){this.key=e,this._s=t}static ss(e,t){return Q.comparator(e.key,t.key)||L(e._s,t._s)}static os(e,t){return L(e._s,t._s)||Q.comparator(e.key,t.key)}}class Zi{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.ws=1,this.gs=new Nt(Xi.ss)}checkEmpty(e){return se.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const s=this.ws;this.ws++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const i=new bs(s,t,n,r);this.mutationQueue.push(i);for(const o of r)this.gs=this.gs.add(new Xi(o.key,s)),this.indexManager.addToCollectionParentIndex(e,o.key.path.popLast());return se.resolve(i)}lookupMutationBatch(e,t){return se.resolve(this.ys(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.ps(n),s=r<0?0:r;return se.resolve(this.mutationQueue.length>s?this.mutationQueue[s]:null)}getHighestUnacknowledgedBatchId(){return se.resolve(0===this.mutationQueue.length?-1:this.ws-1)}getAllMutationBatches(e){return se.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Xi(t,0),r=new Xi(t,Number.POSITIVE_INFINITY),s=[];return this.gs.forEachInRange([n,r],(e=>{const t=this.ys(e._s);s.push(t)})),se.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new Nt(L);return t.forEach((e=>{const t=new Xi(e,0),r=new Xi(e,Number.POSITIVE_INFINITY);this.gs.forEachInRange([t,r],(e=>{n=n.add(e._s)}))})),se.resolve(this.Is(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;Q.isDocumentKey(s)||(s=s.child(""));const i=new Xi(new Q(s),0);let o=new Nt(L);return this.gs.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e._s)),!0)}),i),se.resolve(this.Is(o))}Is(e){const t=[];return e.forEach((e=>{const n=this.ys(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){I(0===this.Ts(t.batchId,"removed")),this.mutationQueue.shift();let n=this.gs;return se.forEach(t.mutations,(r=>{const s=new Xi(r.key,t.batchId);return n=n.delete(s),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.gs=n}))}An(e){}containsKey(e,t){const n=new Xi(t,0),r=this.gs.firstAfterOrEqual(n);return se.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,se.resolve()}Ts(e,t){return this.ps(e)}ps(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}ys(e){const t=this.ps(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Ji{constructor(e){this.Es=e,this.docs=new xt(Q.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),s=r?r.size:0,i=this.Es(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return se.resolve(n?n.document.mutableCopy():Ft.newInvalidDocument(t))}getEntries(e,t){let n=jn();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ft.newInvalidDocument(e))})),se.resolve(n)}getAllFromCollection(e,t,n){let r=jn();const s=new Q(t.child("")),i=this.docs.getIteratorFrom(s);for(;i.hasNext();){const{key:e,value:{document:s}}=i.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||ee(Z(s),n)<=0||(r=r.insert(s.key,s.mutableCopy()))}return se.resolve(r)}getAllFromCollectionGroup(e,t,n,r){v()}As(e,t){return se.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new eo(this)}getSize(e){return se.resolve(this.size)}}class eo extends Oi{constructor(e){super(),this.Yn=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.isValidDocument()?t.push(this.Yn.addEntry(e,r)):this.Yn.removeEntry(n)})),se.waitFor(t)}getFromCache(e,t){return this.Yn.getEntry(e,t)}getAllFromCache(e,t){return this.Yn.getEntries(e,t)}}class to{constructor(e){this.persistence=e,this.Rs=new Qn((e=>Ot(e)),qt),this.lastRemoteSnapshotVersion=U.min(),this.highestTargetId=0,this.bs=0,this.Ps=new Yi,this.targetCount=0,this.vs=_i.Pn()}forEachTarget(e,t){return this.Rs.forEach(((e,n)=>t(n))),se.resolve()}getLastRemoteSnapshotVersion(e){return se.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return se.resolve(this.bs)}allocateTargetId(e){return this.highestTargetId=this.vs.next(),se.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),se.resolve()}Dn(e){this.Rs.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.vs=new _i(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}addTargetData(e,t){return this.Dn(t),this.targetCount+=1,se.resolve()}updateTargetData(e,t){return this.Dn(t),se.resolve()}removeTargetData(e,t){return this.Rs.delete(t.target),this.Ps.ls(t.targetId),this.targetCount-=1,se.resolve()}removeTargets(e,t,n){let r=0;const s=[];return this.Rs.forEach(((i,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Rs.delete(i),s.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)})),se.waitFor(s).next((()=>r))}getTargetCount(e){return se.resolve(this.targetCount)}getTargetData(e,t){const n=this.Rs.get(t)||null;return se.resolve(n)}addMatchingKeys(e,t,n){return this.Ps.us(t,n),se.resolve()}removeMatchingKeys(e,t,n){this.Ps.hs(t,n);const r=this.persistence.referenceDelegate,s=[];return r&&t.forEach((t=>{s.push(r.markPotentiallyOrphaned(e,t))})),se.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.Ps.ls(t),se.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Ps.ds(t);return se.resolve(n)}containsKey(e,t){return se.resolve(this.Ps.containsKey(t))}}class no{constructor(e,t){this.Vs={},this.overlays={},this.Ss=new pe(0),this.Ds=!1,this.Ds=!0,this.referenceDelegate=e(this),this.Cs=new to(this),this.indexManager=new ui,this.remoteDocumentCache=function(e){return new Ji(e)}((e=>this.referenceDelegate.xs(e))),this.yt=new xs(t),this.Ns=new Wi(this.yt)}start(){return Promise.resolve()}shutdown(){return this.Ds=!1,Promise.resolve()}get started(){return this.Ds}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Hi,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Vs[e.toKey()];return n||(n=new Zi(t,this.referenceDelegate),this.Vs[e.toKey()]=n),n}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ns}runTransaction(e,t,n){g("MemoryPersistence","Starting transaction:",e);const r=new ro(this.Ss.next());return this.referenceDelegate.ks(),n(r).next((e=>this.referenceDelegate.Os(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Ms(e,t){return se.or(Object.values(this.Vs).map((n=>()=>n.containsKey(e,t))))}}class ro extends ne{constructor(e){super(),this.currentSequenceNumber=e}}class so{constructor(e){this.persistence=e,this.Fs=new Yi,this.$s=null}static Bs(e){return new so(e)}get Ls(){if(this.$s)return this.$s;throw v()}addReference(e,t,n){return this.Fs.addReference(n,t),this.Ls.delete(n.toString()),se.resolve()}removeReference(e,t,n){return this.Fs.removeReference(n,t),this.Ls.add(n.toString()),se.resolve()}markPotentiallyOrphaned(e,t){return this.Ls.add(t.toString()),se.resolve()}removeTarget(e,t){this.Fs.ls(t.targetId).forEach((e=>this.Ls.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.Ls.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}ks(){this.$s=new Set}Os(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return se.forEach(this.Ls,(n=>{const r=Q.fromPath(n);return this.qs(e,r).next((e=>{e||t.removeEntry(r,U.min())}))})).next((()=>(this.$s=null,t.apply(e))))}updateLimboDocument(e,t){return this.qs(e,t).next((e=>{e?this.Ls.delete(t.toString()):this.Ls.add(t.toString())}))}xs(e){return 0}qs(e,t){return se.or([()=>se.resolve(this.Fs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ms(e,t)])}}class io{constructor(e){this.yt=e}$(e,t,n,r){const s=new ie("createOrUpgrade",t);n<1&&r>=1&&(function(e){e.createObjectStore("owner")}
1(e),function(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Yr,{unique:!0}),e.createObjectStore("documentMutations")}(e),oo(e),function(e){e.createObjectStore("remoteDocuments")}(e));let i=se.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),oo(e)),i=i.next((()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:U.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(s)))),n<4&&r>=4&&(0!==n&&(i=i.next((()=>function(e,t){return t.store("mutations").W().next((n=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Yr,{unique:!0});const r=t.store("mutations"),s=n.map((e=>r.put(e)));return se.waitFor(s)}))}(e,s)))),i=i.next((()=>{!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)}))),n<5&&r>=5&&(i=i.next((()=>this.Us(s)))),n<6&&r>=6&&(i=i.next((()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(e),this.Ks(s))))),n<7&&r>=7&&(i=i.next((()=>this.Gs(s)))),n<8&&r>=8&&(i=i.next((()=>this.Qs(e,s)))),n<9&&r>=9&&(i=i.next((()=>{!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)}))),n<10&&r>=10&&(i=i.next((()=>this.js(s)))),n<11&&r>=11&&(i=i.next((()=>{!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)}))),n<12&&r>=12&&(i=i.next((()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:hs});t.createIndex("collectionPathOverlayIndex",ds,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",fs,{unique:!1})}(e)}))),n<13&&r>=13&&(i=i.next((()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:es});t.createIndex("documentKeyIndex",ts),t.createIndex("collectionGroupIndex",ns)}(e))).next((()=>this.Ws(e,s))).next((()=>e.deleteObjectStore("remoteDocuments")))),n<14&&r>=14&&(i=i.next((()=>this.zs(e,s)))),n<15&&r>=15&&(i=i.next((()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:as}).createIndex("sequenceNumberIndex",us,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:cs}).createIndex("documentKeyIndex",ls,{unique:!1})}(e)))),i}Ks(e){let t=0;return e.store("remoteDocuments").Z(((e,n)=>{t+=Ii(n)})).next((()=>{const n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)}))}Us(e){const t=e.store("mutationQueues"),n=e.store("mutations");return t.W().next((t=>se.forEach(t,(t=>{const r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.W("userMutationsIndex",r).next((n=>se.forEach(n,(n=>{I(n.userId===t.userId);const r=As(this.yt,n);return vi(e,t.userId,r).next((()=>{}))}))))}))))}Gs(e){const t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next((e=>{const r=[];return n.Z(((n,s)=>{const i=new K(n),o=function(e){return[0,zr(e)]}(i);r.push(t.get(o).next((n=>n?se.resolve():(n=>t.put({targetId:0,path:zr(n),sequenceNumber:e.highestListenSequenceNumber}))(i))))})).next((()=>se.waitFor(r)))}))}Qs(e,t){e.createObjectStore("collectionParents",{keyPath:os});const n=t.store("collectionParents"),r=new ci,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:zr(r)})}};return t.store("remoteDocuments").Z({X:!0},((e,t)=>{const n=new K(e);return s(n.popLast())})).next((()=>t.store("documentMutations").Z({X:!0},(([e,t,n],r)=>{const i=Hr(t);return s(i.popLast())}))))}js(e){const t=e.store("targets");return t.Z(((e,n)=>{const r=ks(n),s=Rs(this.yt,r);return t.put(s)}))}Ws(e,t){const n=t.store("remoteDocuments"),r=[];return n.Z(((e,n)=>{const s=t.store("remoteDocumentsV14"),i=(o=n,o.document?new Q(K.fromString(o.document.name).popFirst(5)):o.noDocument?Q.fromSegments(o.noDocument.path):o.unknownDocument?Q.fromSegments(o.unknownDocument.path):v()).path.toArray();var o;const a={prefixPath:i.slice(0,i.length-2),collectionGroup:i[i.length-2],documentId:i[i.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(s.put(a))})).next((()=>se.waitFor(r)))}zs(e,t){const n=t.store("mutations"),r=Pi(this.yt),s=new no(so.Bs,this.yt.ie);return n.W().next((e=>{const n=new Map;return e.forEach((e=>{var t;
1let r=null!==(t=n.get(e.userId))&&void 0!==t?t:nr();As(this.yt,e).keys().forEach((e=>r=r.add(e))),n.set(e.userId,r)})),se.forEach(n,((e,n)=>{const i=new l(n),o=Us.re(this.yt,i),a=s.getIndexManager(i),u=bi.re(i,this.yt,a,s.referenceDelegate);return new ji(r,u,o,a).recalculateAndSaveOverlaysForDocumentKeys(new vs(t,pe.at),e).next()}))}))}}function oo(e){e.createObjectStore("targetDocuments",{keyPath:ss}).createIndex("documentTargetsIndex",is,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",rs,{unique:!0}),e.createObjectStore("targetGlobal")}const ao="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class uo{constructor(e,t,n,r,s,i,o,a,u,c,l=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Hs=s,this.window=i,this.document=o,this.Js=u,this.Ys=c,this.Xs=l,this.Ss=null,this.Ds=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Zs=null,this.inForeground=!1,this.ti=null,this.ei=null,this.ni=Number.NEGATIVE_INFINITY,this.si=e=>Promise.resolve(),!uo.C())throw new S(E.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new Mi(this,r),this.ii=t+"main",this.yt=new xs(a),this.ri=new oe(this.ii,this.Xs,new io(this.yt)),this.Cs=new Di(this.referenceDelegate,this.yt),this.remoteDocumentCache=Pi(this.yt),this.Ns=new Os,this.window&&this.window.localStorage?this.oi=this.window.localStorage:(this.oi=null,!1===c&&p("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.ui().then((()=>
1{if(!this.isPrimary&&!this.allowTabSynchronization)throw new S(E.FAILED_PRECONDITION,ao);return this.ci(),this.ai(),this.hi(),this.runTransaction("getHighestListenSequenceNumber","readonly",(e=>this.Cs.getHighestSequenceNumber(e)))})).then((e=>{this.Ss=new pe(e,this.Js)})).then((()=>{this.Ds=!0})).catch((e=>(this.ri&&this.ri.close(),Promise.reject(e))))}li(e){return this.si=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.ri.L((async t=>{null===t.newVersion&&await e()}))}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Hs.enqueueAndForget((async()=>{this.started&&await this.ui()})))}ui(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",(e=>lo(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next((()=>{if(this.isPrimary)return this.fi(e).next((e=>{e||(this.isPrimary=!1,this.Hs.enqueueRetryable((()=>this.si(!1))))}))})).next((()=>this.di(e))).next((t=>this.isPrimary&&!t?this._i(e).next((()=>!1)):!!t&&this.wi(e).next((()=>!0)))))).catch((e=>{if(ce(e))return g("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return g("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1})).then((e=>{this.isPrimary!==e&&this.Hs.enqueueRetryable((()=>this.si(e))),this.isPrimary=e}))}fi(e){return co(e).get("owner").next((e=>se.resolve(this.mi(e))))}gi(e){return lo(e).delete(this.clientId)}async yi(){if(this.isPrimary&&!this.pi(this.ni,18e5)){this.ni=Date.now();const e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",(e=>{const t=Is(e,"clientMetadata");return t.W().next((e=>{const n=this.Ii(e,18e5),r=e.filter((e=>-1===n.indexOf(e)));return se.forEach(r,(e=>t.delete(e.clientId))).next((()=>r))}))})).catch((()=>[]));if(this.oi)for(const t of e)this.oi.removeItem(this.Ti(t.clientId))}}hi(){this.ei=this.Hs.enqueueAfterDelay("client_metadata_refresh",4e3,(()=>this.ui().then((()=>this.yi())).then((()=>this.hi()))))}mi(e){return!!e&&e.ownerId===this.clientId}di(e){return this.Ys?se.resolve(!0):co(e).get("owner").next((t=>{if(null!==t&&this.pi(t.leaseTimestampMs,5e3)&&!this.Ei(t.ownerId)){if(this.mi(t)&&this.networkEnabled)return!0;if(!this.mi(t)){if(!t.allowTabSynchronization)throw new S(E.FAILED_PRECONDITION,ao);return!1}}return!(!this.networkEnabled||!this.inForeground)||lo(e).W().next((e=>void 0===this.Ii(e,5e3).find((e=>{if(this.clientId!==e.clientId){const t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))))})).next((e=>(this.isPrimary!==e&&g("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e)))}async shutdown(){this.Ds=!1,this.Ai(),this.ei&&(this.ei.cancel(),this.ei=null),this.Ri(),this.bi(),await this.ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],(e=>{const t=new vs(e,pe.at);return this._i(t).next((()=>this.gi(t)))})),this.ri.close(),this.Pi()}Ii(e,t){return e.filter((e=>this.pi(e.updateTimeMs,t)&&!this.Ei(e.clientId)))}vi(){return this.runTransaction("getActiveClients","readonly",(e=>lo(e).W().next((e=>this.Ii(e,18e5).map((e=>e.clientId))))))}get started(){return this.Ds}getMutationQueue(e,t){return bi.re(e,this.yt,t,this.referenceDelegate)}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new hi(e,this.yt.ie.databaseId)}getDocumentOverlayCache(e){return Us.re(this.yt,e)}getBundleCache(){return this.Ns}runTransaction(e,t,n){g("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",s=15===(i=this.Xs)?ws:14===i?ys:13===i?ps:12===i?gs:11===i?ms:void v();var i;let o;return this.ri.runTransaction(e,r,s,(r=>(o=new vs(r,this.Ss?this.Ss.next():pe.at),"readwrite-primary"===t?this.fi(o).next((e=>!!e||this.di(o))).next((t=>{if(!t)throw p(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.Hs.enqueueRetryable((()=>this.si(!1))),new S(E.FAILED_PRECONDITION,te);return n(o)})).next((e=>this.wi(o).next((()=>e)))):this.Vi(o).next((()=>n(o)))))).then((e=>(o.raiseOnCommittedEvent(),e)))}Vi(e){return co(e).get("owner").next((e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)&&!this.mi(e)&&!(this.Ys||this.allowTabSynchronization&&e.allowTabSynchronization))throw new S(E.FAILED_PRECONDITION,ao)}))}wi(e){const t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return co(e).put("owner",t)}static C(){return oe.C()}_i(e){const t=co(e);return t.get("owner").next((e=>this.mi(e)?(g("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):se.resolve()))}pi(e,t){const n=Date.now();return!(e<n-t)&&(!(e>n)||(p(`Detected an update time that is in the future: ${e} > ${n}`),!1))}ci(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ti=()=>{this.Hs.enqueueAndForget((()=>(this.inForeground="visible"===this.document.visibilityState,this.ui())))},this.document.addEventListener("visibilitychange",this.ti),this.inForeground="visible"===this.document.visibilityState)}Ri(){this.ti&&(this.document.removeEventListener("visibilitychange",this.ti),this.ti=null)}ai(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Zs=()=>{this.Ai(),(0,o.G6)()&&navigator.appVersion.match(/Version\/1[45]/)&&this.Hs.enterRestrictedMode(!0),this.Hs.enqueueAndForget((()=>this.shutdown()))},this.window.addEventListener("pagehide",this.Zs))}bi(){this.Zs&&(this.window.removeEventListener("pagehide",this.Zs),this.Zs=null)}Ei(e){var t;try{const n=null!==(null===(t=this.oi)||void 0===t?void 0:t.getItem(this.Ti(e)));return g("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return p("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ai(){if(this.oi)try{this.oi.setItem(this.Ti(this.clientId),String(Date.now()))}catch(e){p("Failed to set zombie client id.",e)}}Pi(){if(this.oi)try{this.oi.removeItem(this.Ti(this.clientId))}catch(e){}}Ti(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function co(e){return Is(e,"owner")}function lo(e){return Is(e,"clientMetadata")}function ho(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class fo{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Si=n,this.Di=r}static Ci(e,t){let n=nr(),r=nr();for(const s of t.docChanges)switch(s.type){case 0:n=n.add(s.doc.key);break;case 1:r=r.add(s.doc.key)}return new fo(e,t.fromCache,n,r)}}class mo{constructor(){this.xi=!1}initialize(e,t){this.Ni=e,this.indexManager=t,this.xi=!0}getDocumentsMatchingQuery(e,t,n,r){return this.ki(e,t).next((s=>s||this.Oi(e,t,r,n))).next((n=>n||this.Mi(e,t)))}ki(e,t){if(zt(t))return se.resolve(null);let n=Xt(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=Jt(t,null,"F"),n=Xt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const s=nr(...r);return this.Ni.getDocuments(e,s).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const i=this.Fi(t,r);return this.$i(t,i,s,n.readTime)?this.ki(e,Jt(t,null,"F")):this.Bi(e,i,t,n)}))))}
1)))))}Oi(e,t,n,r){return zt(t)||r.isEqual(U.min())?this.Mi(e,t):this.Ni.getDocuments(e,n).next((s=>{const o=this.Fi(t,s);return this.$i(t,o,n,r)?this.Mi(e,t):(f()<=i.in.DEBUG&&g("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),nn(t)),this.Bi(e,o,t,X(r,-1)))}))}Fi(e,t){let n=new Nt(on(e));return t.forEach(((t,r)=>{rn(e,r)&&(n=n.add(r))})),n}$i(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||s.version.compareTo(r)>0)}Mi(e,t){return f()<=i.in.DEBUG&&g("QueryEngine","Using full collection scan to execute query:",nn(t)),this.Ni.getDocumentsMatchingQuery(e,t,J.min())}Bi(e,t,n,r){return this.Ni.getDocumentsMatchingQuery(e,n,r).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}class go{constructor(e,t,n,r){this.persistence=e,this.Li=t,this.yt=r,this.qi=new xt(L),this.Ui=new Qn((e=>Ot(e)),qt),this.Ki=new Map,this.Gi=e.getRemoteDocumentCache(),this.Cs=e.getTargetCache(),this.Ns=e.getBundleCache(),this.Qi(n)}Qi(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new ji(this.Gi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Gi.setIndexManager(this.indexManager),this.Li.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.qi)))}}function po(e,t,n,r){return new go(e,t,n,r)}async function yo(e,t){const n=T(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;
1return n.mutationQueue.getAllMutationBatches(e).next((s=>(r=s,n.Qi(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const s=[],i=[];let o=nr();for(const e of r){s.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){i.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return n.localDocuments.getDocuments(e,o).next((e=>({ji:e,removedBatchIds:s,addedBatchIds:i})))}))}))}function wo(e){const t=T(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Cs.getLastRemoteSnapshotVersion(e)))}function vo(e,t,n){let r=nr(),s=nr();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=jn();return n.forEach(((n,i)=>{const o=e.get(n);i.isFoundDocument()!==o.isFoundDocument()&&(s=s.add(n)),i.isNoDocument()&&i.version.isEqual(U.min())?(t.removeEntry(n,i.readTime),r=r.insert(n,i)):!o.isValidDocument()||i.version.compareTo(o.version)>0||0===i.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(i),r=r.insert(n,i)):g("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",i.version)})),{Wi:r,zi:s}}))}function Io(e,t){const n=T(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t))))}function bo(e,t){const n=T(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.Cs.getTargetData(e,t).next((s=>s?(r=s,se.resolve(r)):n.Cs.allocateTargetId(e).next((s=>(r=new Ss(t,s,0,e.currentSequenceNumber),n.Cs.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.qi.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.qi=n.qi.insert(e.targetId,e),n.Ui.set(t,e.targetId)),e}))}async function To(e,t,n){const r=T(e),s=r.qi.get(t),i=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",i,(e=>r.persistence.referenceDelegate.removeTarget(e,s)))}catch(e){if(!ce(e))throw e;g("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.qi=r.qi.remove(t),r.Ui.delete(s.target)}function Eo(e,t,n){const r=T(e);let s=U.min(),i=nr();return r.persistence.runTransaction("Execute query","readonly",(e=>function(e,t,n){const r=T(e),s=r.Ui.get(n);return void 0!==s?se.resolve(r.qi.get(s)):r.Cs.getTargetData(t,n)}(r,e,Xt(t)).next((t=>{if(t)return s=t.lastLimboFreeSnapshotVersion,r.Cs.getMatchingKeysForTargetId(e,t.targetId).next((e=>{i=e}))})).next((()=>r.Li.getDocumentsMatchingQuery(e,t,n?s:U.min(),n?i:nr()))).next((e=>(_o(r,sn(t),e),{documents:e,Hi:i})))))}function So(e,t){const n=T(e),r=T(n.Cs),s=n.qi.get(t);return s?Promise.resolve(s.target):n.persistence.runTransaction("Get target data","readonly",(e=>r.ne(e,t).next((e=>e?e.target:null))))}function xo(e,t){const n=T(e),r=n.Ki.get(t)||U.min();return n.persistence.runTransaction("Get new document changes","readonly",(e=>n.Gi.getAllFromCollectionGroup(e,t,X(r,-1),Number.MAX_SAFE_INTEGER))).then((e=>(_o(n,t,e),e)))}function _o(e,t,n){let r=e.Ki.get(t)||U.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.Ki.set(t,r)}async function Do(e,t,n=nr()){const r=await bo(e,Xt(Vs(t.bundledQuery))),s=T(e);return s.persistence.runTransaction("Save named query","readwrite",(e=>{const i=br(t.readTime);if(r.snapshotVersion.compareTo(i)>=0)return s.Ns.saveNamedQuery(e,t);const o=r.withResumeToken(_e.EMPTY_BYTE_STRING,i);return s.qi=s.qi.insert(o.targetId,o),s.Cs.updateTargetData(e,o).next((()=>s.Cs.removeMatchingKeysForTargetId(e,r.targetId))).next((()=>s.Cs.addMatchingKeys(e,n,r.targetId))).next((()=>s.Ns.saveNamedQuery(e,t)))}))}function No(e,t){return`firestore_clients_${e}_${t}`}function Co(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Ao(e,t){return`firestore_targets_${e}_${t}`}class ko{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Zi(e,t,n){const r=JSON.parse(n);let s,i="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code,i&&(s=new S(r.error.code,r.error.message))),i?new ko(e,t,r.state,s):(p("SharedCl
1ientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class Ro{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Zi(e,t){const n=JSON.parse(t);let r,s="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code,s&&(r=new S(n.error.code,n.error.message))),s?new Ro(e,n.state,r):(p("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class Vo{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Zi(e,t){const n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,s=sr();for(let i=0;r&&i<n.activeTargetIds.length;++i)r=Se(n.activeTargetIds[i]),s=s.add(n.activeTargetIds[i]);return r?new Vo(e,s):(p("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class Fo{constructor(e,t){this.clientId=e,this.onlineState=t}static Zi(e){const t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Fo(t.clientId,t.onlineState):(p("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Mo{constructor(){this.activeTargetIds=sr()}er(e){this.activeTargetIds=this.activeTargetIds.add(e)}nr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}tr(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Lo{constructor(e,t,n,r,s){this.window=e,this.Hs=t,this.persistenceKey=n,this.sr=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ir=this.rr.bind(this),this.ur=new xt(L),this.started=!1,this.cr=[];const i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=s,this.ar=No(this.persistenceKey,this.sr),this.hr=function(e){return`firestore_sequence_number_${e}`}(this.persistenceKey),this.ur=this.ur.insert(this.sr,new Mo),this.lr=new RegExp(`^firestore_clients_${i}_([^_]*)$`),this.dr=new RegExp(`^firestore_mutations_${i}_(\\d+)(?:_(.*))?$`),this._r=new RegExp(`^firestore_targets_${i}_(\\d+)$`),this.wr=function(e){return`firestore_online_state_${e}`}(this.persistenceKey),this.mr=function(e){return`firestore_bundle_loaded_v2_${e}`}(this.persistenceKey),this.window.addEventListener("storage",this.ir)}static C(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.vi();for(const n of e){if(n===this.sr)continue;const e=this.getItem(No(this.persistenceKey,n));if(e){const t=Vo.Zi(n,e);t&&(this.ur=this.ur.insert(t.clientId,t))}}this.gr();const t=this.storage.getItem(this.wr);if(t){const e=this.yr(t);e&&this.pr(e)}for(const n of this.cr)this.rr(n);this.cr=[],this.window.addEventListener("pagehide",(()=>this.shutdown())),this.started=!0}writeSequenceNumber(e){this.setItem(this.hr,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ir(this.ur)}isActiveQueryTarget(e){let t=!1;return this.ur.forEach(((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)})),t}addPendingMutation(e){this.Tr(e,"pending")}updateMutationState(e,t,n){this.Tr(e,t,n),this.Er(e)}addLocalQueryTarget(e){let t="not-current";if(this.isActiveQueryTarget(e)){const n=this.storage.getItem(Ao(this.persistenceKey,e));if(n){const r=Ro.Zi(e,n);r&&(t=r.state)}}return this.Ar.er(e),this.gr(),t}removeLocalQueryTarget(e){this.Ar.nr(e),this.gr()}isLocalQueryTarget(e){return this.Ar.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Ao(this.persistenceKey,e))}updateQueryState(e,t,n){this.Rr(e,t,n)}handleUserChange(e,t,n){t.forEach((e=>{this.Er(e)})),this.currentUser=e,n.forEach((e=>{this.addPendingMutation(e)}))}setOnlineState(e){this.br(e)}notifyBundleLoaded(e){this.Pr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ir),this.removeItem(this.ar),this.started=!1)}getItem(e){const t=this.storage.getItem(e);
1return g("SharedClientState","READ",e,t),t}setItem(e,t){g("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){g("SharedClientState","REMOVE",e),this.storage.removeItem(e)}rr(e){const t=e;if(t.storageArea===this.storage){if(g("SharedClientState","EVENT",t.key,t.newValue),t.key===this.ar)return void p("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.Hs.enqueueRetryable((async()=>{if(this.started){if(null!==t.key)if(this.lr.test(t.key)){if(null==t.newValue){const e=this.vr(t.key);return this.Vr(e,null)}{const e=this.Sr(t.key,t.newValue);if(e)return this.Vr(e.clientId,e)}}else if(this.dr.test(t.key)){if(null!==t.newValue){const e=this.Dr(t.key,t.newValue);if(e)return this.Cr(e)}}else if(this._r.test(t.key)){if(null!==t.newValue){const e=this.Nr(t.key,t.newValue);if(e)return this.kr(e)}}else if(t.key===this.wr){if(null!==t.newValue){const e=this.yr(t.newValue);if(e)return this.pr(e)}}else if(t.key===this.hr){const e=function(e){let t=pe.at;if(null!=e)try{const n=JSON.parse(e);I("number"==typeof n),t=n}catch(e){p("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(t.newValue);e!==pe.at&&this.sequenceNumberHandler(e)}else if(t.key===this.mr){const e=this.Or(t.newValue);await Promise.all(e.map((e=>this.syncEngine.Mr(e))))}}else this.cr.push(t)}))}}get Ar(){return this.ur.get(this.sr)}gr(){this.setItem(this.ar,this.Ar.tr())}Tr(e,t,n){const r=new ko(this.currentUser,e,t,n),s=Co(this.persistenceKey,this.currentUser,e);this.setItem(s,r.tr())}Er(e){const t=Co(this.persistenceKey,this.currentUser,e);this.removeItem(t)}br(e){const t={clientId:this.sr,onlineState:e};this.storage.setItem(this.wr,JSON.stringify(t))}Rr(e,t,n){const r=Ao(this.persistenceKey,e),s=new Ro(e,t,n);this.setItem(r,s.tr())}Pr(e){const t=JSON.stringify(Array.from(e));this.setItem(this.mr,t)}vr(e){const t=this.lr.exec(e);return t?t[1]:null}Sr(e,t){const n=this.vr(e);return Vo.Zi(n,t)}Dr(e,t){const n=this.dr.exec(e),r=Number(n[1]),s=void 0!==n[2]?n[2]:null;return ko.Zi(new l(s),r,t)}Nr(e,t){const n=this._r.exec(e),r=Number(n[1]);return Ro.Zi(r,t)}yr(e){return Fo.Zi(e)}Or(e){return JSON.parse(e)}async Cr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Fr(e.batchId,e.state,e.error);g("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}kr(e){return this.syncEngine.$r(e.targetId,e.state,e.error)}Vr(e,t){const n=t?this.ur.insert(e,t):this.ur.remove(e),r=this.Ir(this.ur),s=this.Ir(n),i=[],o=[];return s.forEach((e=>{r.has(e)||i.push(e)})),r.forEach((e=>{s.has(e)||o.push(e)})),this.syncEngine.Br(i,o).then((()=>{this.ur=n}))}pr(e){this.ur.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ir(e){let t=sr();return e.forEach(((e,n)=>{t=t.unionWith(n.activeTargetIds)})),t}}class Oo{constructor(){this.Lr=new Mo,this.qr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Lr.er(e),this.qr[e]||"not-current"}updateQueryState(e,t,n){this.qr[e]=t}removeLocalQueryTarget(e){this.Lr.nr(e)}isLocalQueryTarget(e){return this.Lr.activeTargetIds.has(e)}clearQueryState(e){delete this.qr[e]}getAllActiveQueryTargets(){return this.Lr.activeTargetIds}isActiveQueryTarget(e){return this.Lr.activeTargetIds.has(e)}start(){return this.Lr=new Mo,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class qo{Ur(e){}shutdown(){}}class Po{constructor(){this.Kr=()=>this.Gr(),this.Qr=()=>this.jr(),this.Wr=[],this.zr()}Ur(e){this.Wr.push(e)}shutdown(){window.removeEventListener("online",this.Kr),window.removeEventListener("offline",this.Qr)}zr(){window.addEventListener("online",this.Kr),window.addEventListener("offline",this.Qr)}Gr(){g("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Wr)e(0)}jr(){g("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Wr)e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const Uo={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
1Query:"runAggregationQuery"};class Bo{constructor(e){this.Hr=e.Hr,this.Jr=e.Jr}Yr(e){this.Xr=e}Zr(e){this.eo=e}onMessage(e){this.no=e}close(){this.Jr()}send(e){this.Hr(e)}so(){this.Xr()}io(e){this.eo(e)}ro(e){this.no(e)}}class Ko extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http";this.oo=t+"://"+e.host,this.uo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get co(){return!1}ao(e,t,n,r,s){const i=this.ho(e,t);g("RestConnection","Sending: ",i,n);const o={};return this.lo(o,r,s),this.fo(e,i,o,n).then((e=>(g("RestConnection","Received: ",e),e)),(t=>{throw y("RestConnection",`${e} failed with error: `,t,"url: ",i,"request:",n),t}))}_o(e,t,n,r,s,i){return this.ao(e,t,n,r,s)}lo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+h,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}ho(e,t){const n=Uo[e];return`${this.oo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}fo(e,t,n,r){return new Promise(((s,i)=>{const o=new a.JJ;o.setWithCredentials(!0),o.listenOnce(a.tw.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case a.jK.NO_ERROR:const t=o.getResponseJson();g("Connection","XHR received:",JSON.stringify(t)),s(t);break;case a.jK.TIMEOUT:g("Connection",'RPC "'+e+'" timed out'),i(new S(E.DEADLINE_EXCEEDED,"Request time out"));break;case a.jK.HTTP_ERROR:const n=o.getStatus();if(g("Connection",'RPC "'+e+'" failed with status:',n,"response text:",o.getResponseText()),n>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(E).indexOf(t)>=0?t:E.UNKNOWN}(t.status);i(new S(e,t.message))}else i(new S(E.UNKNOWN,"Server responded with status "+o.getStatus()))}else i(new S(E.UNAVAILABLE,"Connection failed."));break;default:v()}}finally{g("Connection",'RPC "'+e+'" completed.')}}));const u=JSON.stringify(r);o.send(t,"POST",u,n,15)}))}
1wo(e,t,n){const r=[this.oo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=(0,a.UE)(),i=(0,a.FJ)(),o={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};this.useFetchStreams&&(o.xmlHttpFactory=new a.zI({})),this.lo(o.initMessageHeaders,t,n),o.encodeInitMessageHeaders=!0;const u=r.join("");g("Connection","Creating WebChannel: "+u,o);const c=s.createWebChannel(u,o);let l=!1,h=!1;const d=new Bo({Hr:e=>{h?g("Connection","Not sending because WebChannel is closed:",e):(l||(g("Connection","Opening WebChannel transport."),c.open(),l=!0),g("Connection","WebChannel sending:",e),c.send(e))},Jr:()=>c.close()}),f=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return f(c,a.ii.EventType.OPEN,(()=>{h||g("Connection","WebChannel transport opened.")})),f(c,a.ii.EventType.CLOSE,(()=>{h||(h=!0,g("Connection","WebChannel transport closed"),d.io())})),f(c,a.ii.EventType.ERROR,(e=>{h||(h=!0,y("Connection","WebChannel transport errored:",e),d.io(new S(E.UNAVAILABLE,"The operation could not be completed")))})),f(c,a.ii.EventType.MESSAGE,(e=>{var t;if(!h){const n=e.data[0];I(!!n);const r=n,s=r.error||(null===(t=r[0])||void 0===t?void 0:t.error);if(s){g("Connection","WebChannel received error:",s);const e=s.status;let t=function(e){const t=Bn[e];if(void 0!==t)return $n(t)}(e),n=s.message;void 0===t&&(t=E.INTERNAL,n="Unknown error status: "+e+" with message "+s.message),h=!0,d.io(new S(t,n)),c.close()}else g("Connection","WebChannel received:",n),d.ro(n)}})),f(i,a.ju.STAT_EVENT,(e=>{e.stat===a.kN.PROXY?g("Connection","Detected buffering proxy"):e.stat===a.kN.NOPROXY&&g("Connection","Detected no buffering proxy")})),setTimeout((()=>{d.so()}),0),d}}function Go(){return"undefined"!=typeof window?window:null}function $o(){return"undefined"!=typeof document?document:null}function Qo(e){return new yr(e,!0)}class zo{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Hs=e,this.timerId=t,this.mo=n,this.yo=r,this.po=s,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}reset(){this.Io=0}Ao(){this.Io=this.po}Ro(e){this.cancel();const t=Math.floor(this.Io+this.bo()),n=Math.max(0,Date.now()-this.Eo),r=Math.max(0,t-n);r>0&&g("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Io} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.To=this.Hs.enqueueAfterDelay(this.timerId,r,(()=>(this.Eo=Date.now(),e()))),this.Io*=this.yo,this.Io<this.mo&&(this.Io=this.mo),this.Io>this.po&&(this.Io=this.po)}Po(){null!==this.To&&(this.To.skipDelay(),this.To=null)}cancel(){null!==this.To&&(this.To.cancel(),this.To=null)}bo(){return(Math.random()-.5)*this.Io}}class jo{constructor(e,t,n,r,s,i,o,a){this.Hs=e,this.vo=n,this.Vo=r,this.connection=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.So=0,this.Do=null,this.Co=null,this.stream=null,this.xo=new zo(e,t)}No(){return 1===this.state||5===this.state||this.ko()}ko(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Oo()}async stop(){this.No()&&await this.close(0)}Mo(){this.state=0,this.xo.reset()}Fo(){this.ko()&&null===this.Do&&(this.Do=this.Hs.enqueueAfterDelay(this.vo,6e4,(()=>this.$o())))}Bo(e){this.Lo(),this.stream.send(e)}async $o(){if(this.ko())return this.close(0)}Lo(){this.Do&&(this.Do.cancel(),this.Do=null)}qo(){this.Co&&(this.Co.cancel(),this.Co=null)}async close(e,t){this.Lo(),this.qo(),this.xo.cancel(),this.So++,4!==e?this.xo.reset():t&&t.code===E.RESOURCE_EXHAUSTED?(p(t.toString()),p("Using maximum backoff delay to prevent overloading the backend."),this.xo.Ao()):t&&t.code===E.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Uo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Zr(t)}Uo(){}auth(){this.state=1;const e=this.Ko(this.So),t=this.So;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.So===t&&this.Go(e,n)}),(t=>{e((()=>{const e=new S(E.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Qo(e)}))}))}Go(e,t){const n=this.Ko(this.So);this.stream=this.jo(e,t),this.stream.Yr((()=>{n((()=>(this.state=2,this.Co=this.Hs.enqueueAfterDelay(this.Vo,1e4,(()=>(this.ko()&&(this.state=3),Promise.resolve()))),this.listener.Yr())))}
1)),this.stream.Zr((e=>{n((()=>this.Qo(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}Oo(){this.state=5,this.xo.Ro((async()=>{this.state=0,this.start()}))}Qo(e){return g("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Ko(e){return t=>{this.Hs.enqueueAndForget((()=>this.So===e?t():(g("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class Wo extends jo{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.yt=s}jo(e,t){return this.connection.wo("Listen",e,t)}onMessage(e){this.xo.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:v()}(t.targetChange.targetChangeType||"NO_CHANGE"),s=t.targetChange.targetIds||[],i=function(e,t){return e.wt?(I(void 0===t||"string"==typeof t),_e.fromBase64String(t||"")):(I(void 0===t||t instanceof Uint8Array),_e.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?E.UNKNOWN:$n(e.code);return new S(t,e.message||"")}(o);n=new cr(r,s,i,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const s=xr(e,r.document.name),i=br(r.document.updateTime),o=r.document.createTime?br(r.document.createTime):U.min(),a=new Rt({mapValue:{fields:r.document.fields}}),u=Ft.newFoundDocument(s,i,o,a),c=r.targetIds||[],l=r.removedTargetIds||[];n=new ar(c,l,u.key,u)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const s=xr(e,r.document),i=r.readTime?br(r.readTime):U.min(),o=Ft.newNoDocument(s,i),a=r.removedTargetIds||[];n=new ar([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const s=xr(e,r.document),i=r.removedTargetIds||[];n=new ar([],i,s,null)}else{if(!("filter"in t))return v();{t.filter;const e=t.filter;e.targetId;const r=e.count||0,s=new Un(r),i=e.targetId;n=new ur(i,s)}}return n}(this.yt,e),n=function(e){if(!("targetChange"in e))return U.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?U.min():t.readTime?br(t.readTime):U.min()}(e);return this.listener.Wo(t,n)}zo(e){const t={};t.database=Nr(this.yt),t.addTarget=function(e,t){let n;const r=t.target;return n=Pt(r)?{documents:Fr(e,r)}:{query:Mr(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0?n.resumeToken=vr(e,t.resumeToken):t.snapshotVersion.compareTo(U.min())>0&&(n.readTime=wr(e,t.snapshotVersion.toTimestamp())),n}(this.yt,e);const n=function(e,t){const n=function(e,t){switch(t){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return v()}}(0,t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.yt,e);n&&(t.labels=n),this.Bo(t)}Ho(e){const t={};t.database=Nr(this.yt),t.removeTarget=e,this.Bo(t)}}class Ho extends jo{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.yt=s,this.Jo=!1}get Yo(){return this.Jo}start(){this.Jo=!1,this.lastStreamToken=void 0,super.start()}Uo(){this.Jo&&this.Xo([])}jo(e,t){return this.connection.wo("Write",e,t)}onMessage(e){if(I(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Jo){this.xo.reset();const t=function(e,t){return e&&e.length>0?(I(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?br(e.updateTime):br(t);return n.isEqual(U.min())&&(n=br(t)),new Sn(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=br(e.commitTime);return this.listener.Zo(n,t)}return I(!e.writeResults||0===e.writeResults.length),this.Jo=!0,this.listener.tu()}eu(){const e={};e.database=Nr(this.yt),this.Bo(e)}Xo(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>Rr(this.yt,e)))};this.Bo(t)}}class Yo extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.yt=r,this.nu=!1}su(){if(this.nu)throw new S(E.FAILED_PRECONDITION,"The client has already been terminated.")}ao(e,t,n){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,s])=>
1this.connection.ao(e,t,n,r,s))).catch((e=>{throw"FirebaseError"===e.name?(e.code===E.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new S(E.UNKNOWN,e.toString())}))}_o(e,t,n,r){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,i])=>this.connection._o(e,t,n,s,i,r))).catch((e=>{throw"FirebaseError"===e.name?(e.code===E.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new S(E.UNKNOWN,e.toString())}))}terminate(){this.nu=!0}}class Xo{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.iu=0,this.ru=null,this.ou=!0}uu(){0===this.iu&&(this.cu("Unknown"),this.ru=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.ru=null,this.au("Backend didn't respond within 10 seconds."),this.cu("Offline"),Promise.resolve()))))}hu(e){"Online"===this.state?this.cu("Unknown"):(this.iu++,this.iu>=1&&(this.lu(),this.au(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.cu("Offline")))}set(e){this.lu(),this.iu=0,"Online"===e&&(this.ou=!1),this.cu(e)}cu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}au(e){const t=`Could not reach Cloud Firestore backend. ${e}\nThis 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.ou?(p(t),this.ou=!1):g("OnlineStateTracker",t)}lu(){null!==this.ru&&(this.ru.cancel(),this.ru=null)}}class Zo{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.fu=[],this.du=new Map,this._u=new Set,this.wu=[],this.mu=s,this.mu.Ur((e=>{n.enqueueAndForget((async()=>{aa(this)&&(g("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=T(e);t._u.add(4),await ea(t),t.gu.set("Unknown"),t._u.delete(4),await Jo(t)}(this))}))})),this.gu=new Xo(n,r)}}async function Jo(e){if(aa(e))for(const t of e.wu)await t(!0)}async function ea(e){for(const t of e.wu)await t(!1)}function ta(e,t){const n=T(e);n.du.has(t.targetId)||(n.du.set(t.targetId,t),oa(n)?ia(n):xa(n).ko()&&ra(n,t))}function na(e,t){const n=T(e),r=xa(n);n.du.delete(t),r.ko()&&sa(n,t),0===n.du.size&&(r.ko()?r.Fo():aa(n)&&n.gu.set("Unknown"))}function ra(e,t){e.yu.Ot(t.targetId),xa(e).zo(t)}function sa(e,t){e.yu.Ot(t),xa(e).Ho(t)}function ia(e){e.yu=new hr({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),ne:t=>e.du.get(t)||null}),xa(e).start(),e.gu.uu()}function oa(e){return aa(e)&&!xa(e).No()&&e.du.size>0}function aa(e){return 0===T(e)._u.size}function ua(e){e.yu=void 0}async function ca(e){e.du.forEach(((t,n)=>{ra(e,t)}))}async function la(e,t){ua(e),oa(e)?(e.gu.hu(t),ia(e)):e.gu.set("Unknown")}async function ha(e,t,n){if(e.gu.set("Online"),t instanceof cr&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.du.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.du.delete(r),e.yu.removeTarget(r))}(e,t)}catch(n){g("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await da(e,n)}else if(t instanceof ar?e.yu.Kt(t):t instanceof ur?e.yu.Jt(t):e.
vendor: 6,055 bytes, line 1
1yu.jt(t),!n.isEqual(U.min()))try{const t=await wo(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.yu.Zt(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const s=e.du.get(r);s&&e.du.set(r,s.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach((t=>{const n=e.du.get(t);if(!n)return;e.du.set(t,n.withResumeToken(_e.EMPTY_BYTE_STRING,n.snapshotVersion)),sa(e,t);const r=new Ss(n.target,t,1,n.sequenceNumber);ra(e,r)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){g("RemoteStore","Failed to raise snapshot:",t),await da(e,t)}}async function da(e,t,n){if(!ce(t))throw t;e._u.add(1),await ea(e),e.gu.set("Offline"),n||(n=()=>wo(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{g("RemoteStore","Retrying IndexedDB access"),await n(),e._u.delete(1),await Jo(e)}))}function fa(e,t){return t().catch((n=>da(e,n,t)))}async function ma(e){const t=T(e),n=_a(t);let r=t.fu.length>0?t.fu[t.fu.length-1].batchId:-1;for(;ga(t);)try{const e=await Io(t.localStore,r);if(null===e){0===t.fu.length&&n.Fo();break}r=e.batchId,pa(t,e)}catch(e){await da(t,e)}ya(t)&&wa(t)}function ga(e){return aa(e)&&e.fu.length<10}function pa(e,t){e.fu.push(t);const n=_a(e);n.ko()&&n.Yo&&n.Xo(t.mutations)}function ya(e){return aa(e)&&!_a(e).No()&&e.fu.length>0}function wa(e){_a(e).start()}async function va(e){_a(e).eu()}async function Ia(e){const t=_a(e);for(const n of e.fu)t.Xo(n.mutations)}async function ba(e,t,n){const r=e.fu.shift(),s=Ts.from(r,t,n);await fa(e,(()=>e.remoteSyncer.applySuccessfulWrite(s))),await ma(e)}async function Ta(e,t){t&&_a(e).Yo&&await async function(e,t){if(Gn(n=t.code)&&n!==E.ABORTED){const n=e.fu.shift();_a(e).Mo(),await fa(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await ma(e)}var n}(e,t),ya(e)&&wa(e)}async function Ea(e,t){const n=T(e);n.asyncQueue.verifyOperationInProgress(),g("RemoteStore","RemoteStore received new credentials");const r=aa(n);n._u.add(3),await ea(n),r&&n.gu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n._u.delete(3),await Jo(n)}async function Sa(e,t){const n=T(e);t?(n._u.delete(2),await Jo(n)):t||(n._u.add(2),await ea(n),n.gu.set("Unknown"))}function xa(e){return e.pu||(e.pu=function(e,t,n){const r=T(e);return r.su(),new Wo(t,r.connection,r.authCredentials,r.appCheckCredentials,r.yt,n)}(e.datastore,e.asyncQueue,{Yr:ca.bind(null,e),Zr:la.bind(null,e),Wo:ha.bind(null,e)}),e.wu.push((async t=>{t?(e.pu.Mo(),oa(e)?ia(e):e.gu.set("Unknown")):(await e.pu.stop(),ua(e))}))),e.pu}function _a(e){return e.Iu||(e.Iu=function(e,t,n){const r=T(e);return r.su(),new Ho(t,r.connection,r.authCredentials,r.appCheckCredentials,r.yt,n)}(e.datastore,e.asyncQueue,{Yr:va.bind(null,e),Zr:Ta.bind(null,e),tu:Ia.bind(null,e),Zo:ba.bind(null,e)}),e.wu.push((async t=>{t?(e.Iu.Mo(),await ma(e)):(await e.Iu.stop(),e.fu.length>0&&(g("RemoteStore",`Stopping write stream with ${e.fu.length} pending writes`),e.fu=[]))}))),e.Iu}class Da{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,this.deferred=new x,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}static createAndSchedule(e,t,n,r,s){const i=Date.now()+n,o=new Da(e,t,i,r,s);return o.start(n),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new S(E.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Na(e,t){if(p("AsyncQueue",`${t}: ${e}`),ce(e))return new S(E.UNAVAILABLE,`${t}: ${e}`);throw e}class Ca{constructor(e){this.comparator=e?(t,n)=>e(t,n)||Q.comparator(t.key,n.key):(e,t)=>Q.comparator(e.key,t.key),this.keyedMap=Hn(),this.sortedSet=new xt(this.comparator)}static emptySet(e){return new Ca(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof Ca))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new Ca;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Aa{constructor(){this.Tu=new xt(Q.comparator)}track(e){const t=e.doc.key,n=this.Tu.get(t);n?0!==e.type&&3===n.type?this.Tu=this.Tu.insert(t,e):3===e.type&&1!==n.type?this.Tu=this.Tu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Tu=this.Tu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Tu=this.Tu.remove(t):1===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):v():this.Tu=this.Tu.insert(t,e)}Eu(){const e=[];return this.Tu.inorderTraversal(((t,n)=>{e.push(n)})),e}}class ka{constructor(e,t,n,r,s,i,o,a,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=u}
1static fromInitialDocuments(e,t,n,r,s){const i=[];return t.forEach((e=>{i.push({type:0,doc:e})})),new ka(e,t,Ca.emptySet(t),i,n,r,!0,!1,s)}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)&&en(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class Ra{constructor(){this.Au=void 0,this.listeners=[]}}class Va{constructor(){this.queries=new Qn((e=>tn(e)),en),this.onlineState="Unknown",this.Ru=new Set}}async function Fa(e,t){const n=T(e),r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new Ra),s)try{i.Au=await n.onListen(r)}catch(e){const n=Na(e,`Initialization of query '${nn(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.bu(n.onlineState),i.Au&&t.Pu(i.Au)&&qa(n)}async function Ma(e,t){const n=T(e),r=t.query;let s=!1;const i=n.queries.get(r);if(i){const e=i.listeners.indexOf(t);e>=0&&(i.listeners.splice(e,1),s=0===i.listeners.length)}if(s)return n.queries.delete(r),n.onUnlisten(r)}function La(e,t){const n=T(e);let r=!1;for(const s of t){const e=s.query,t=n.queries.get(e);if(t){for(const e of t.listeners)e.Pu(s)&&(r=!0);t.Au=s}}r&&qa(n)}function Oa(e,t,n){const r=T(e),s=r.queries.get(t);if(s)for(const i of s.listeners)i.onError(n);r.queries.delete(t)}function qa(e){e.Ru.forEach((e=>{e.next()}))}class Pa{constructor(e,t,n){this.query=e,this.vu=t,this.Vu=!1,this.Su=null,this.onlineState="Unknown",this.options=n||{}}Pu(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new ka(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Vu?this.Du(e)&&(this.vu.next(e),t=!0):this.Cu(e,this.onlineState)&&(this.xu(e),t=!0),this.Su=e,t}onError(e){this.vu.error(e)}bu(e){this.onlineState=e;let t=!1;return this.Su&&!this.Vu&&this.Cu(this.Su,e)&&(this.xu(this.Su),t=!0),t}Cu(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return(!this.options.Nu||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Du(e){if(e.docChanges.length>0)return!0;const t=this.Su&&this.Su.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}xu(e){e=ka.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Vu=!0,this.vu.next(e)}}class Ua{constructor(e,t){this.ku=e,this.byteLength=t}Ou(){return"metadata"in this.ku}}class Ba{constructor(e){this.yt=e}Ji(e){return xr(this.yt,e)}Yi(e){return e.metadata.exists?kr(this.yt,e.document,!1):Ft.newNoDocument(this.Ji(e.metadata.name),this.Xi(e.metadata.readTime))}Xi(e){return br(e)}}class Ka{constructor(e,t,n){this.Mu=e,this.localStore=t,this.yt=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Ga(e)}Fu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.ku.namedQuery)this.queries.push(e.ku.namedQuery);else if(e.ku.documentMetadata){this.documents.push({metadata:e.ku.documentMetadata}),e.ku.documentMetadata.exists||++t;const n=K.fromString(e.ku.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ku.document&&(this.documents[this.documents.length-1].document=e.ku.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}$u(e){const t=new Map,n=new Ba(this.yt);for(const r of e)if(r.metadata.queries){const e=n.Ji(r.metadata.name);for(const n of r.metadata.queries){const r=(t.get(n)||nr()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const s=T(e);let i=nr(),o=jn();for(const c of n){const e=t.Ji(c.metadata.name);c.document&&(i=i.add(e));const n=t.Yi(c);n.setReadTime(t.Xi(c.metadata.readTime)),o=o.insert(e,n)}const a=s.Gi.newChangeBuffer({trackRemovals:!0}),u=await bo(s,function(e){return Xt(Qt(K.fromString(`__bundle__/docs/${e}`)))}(r));return s.persistence.runTransaction("Apply bundle documents","readwrite",(e=>vo(e,a,o).next((t=>(a.apply(e),t))).next((t=>s.Cs.removeMatchingKeysForTargetId(e,u.targetId).next((()=>s.Cs.addMatchingKeys(e,i,u.targetId))).next((()=>s.localDocuments.getLocalViewOfDocuments(e,t.Wi,t.zi))).next((()=>t.Wi))))))}(this.localStore,new Ba(this.yt),this.documents,this.Mu.id),t=this.$u(this.documents);for(const n of this.queries)await Do(this.localStore,n,t.get(n.name));return this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}}}function Ga(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class $a{constructor(e){this.key=e}}class Qa{constructor(e){this.key=e}}class za{constructor(e,t){this.query=e,this.qu=t,this.Uu=null,this.hasCachedResults=!1,this.current=!1,this.Ku=nr(),this.mutatedKeys=nr(),this.Gu=on(e),this.Qu=new Ca(this.Gu)}get ju(){return this.qu}Wu(e,t){const n=t?t.zu:new Aa,r=t?t.Qu:this.Qu;let s=t?t.mutatedKeys:this.mutatedKeys,i=r,o=!1;const a="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,u="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const c=r.get(e),l=rn(this.query,t)?t:null,h=!!c&&this.mutatedKeys.has(c.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;c&&l?c.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.Hu(c,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.Gu(l,a)>0||u&&this.Gu(l,u)<0)&&(o=!0)):!c&&l?(n.track({type:0,doc:l}),f=!0):c&&!l&&(n.track({type:1,doc:c}),f=!0,(a||u)&&(o=!0)),f&&(l?(i=i.add(l),s=d?s.add(e):s.delete(e)):(i=i.delete(e),s=s.delete(e)))})),null!==this.query.limit)for(;i.size>this.query.limit;
1){const e="F"===this.query.limitType?i.last():i.first();i=i.delete(e.key),s=s.delete(e.key),n.track({type:1,doc:e})}return{Qu:i,zu:n,$i:o,mutatedKeys:s}}Hu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;const s=e.zu.Eu();s.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return v()}};return n(e)-n(t)}(e.type,t.type)||this.Gu(e.doc,t.doc))),this.Ju(n);const i=t?this.Yu():[],o=0===this.Ku.size&&this.current?1:0,a=o!==this.Uu;return this.Uu=o,0!==s.length||a?{snapshot:new ka(this.query,e.Qu,r,s,e.mutatedKeys,0===o,a,!1,!!n&&n.resumeToken.approximateByteSize()>0),Xu:i}:{Xu:i}}bu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Qu:this.Qu,zu:new Aa,mutatedKeys:this.mutatedKeys,$i:!1},!1)):{Xu:[]}}Zu(e){return!this.qu.has(e)&&!!this.Qu.has(e)&&!this.Qu.get(e).hasLocalMutations}Ju(e){e&&(e.addedDocuments.forEach((e=>this.qu=this.qu.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.qu=this.qu.delete(e))),this.current=e.current)}Yu(){if(!this.current)return[];const e=this.Ku;this.Ku=nr(),this.Qu.forEach((e=>{this.Zu(e.key)&&(this.Ku=this.Ku.add(e.key))}));const t=[];return e.forEach((e=>{this.Ku.has(e)||t.push(new Qa(e))})),this.Ku.forEach((n=>{e.has(n)||t.push(new $a(n))})),t}tc(e){this.qu=e.Hi,this.Ku=nr();const t=this.Wu(e.documents);return this.applyChanges(t,!0)}ec(){return ka.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.Uu,this.hasCachedResults)}}class ja{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Wa{constructor(e){this.key=e,this.nc=!1}}class Ha{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.sc={},this.ic=new Qn((e=>tn(e)),en),this.rc=new Map,this.oc=new Set,this.uc=new xt(Q.comparator),this.cc=new Map,this.ac=new Yi,this.hc={},this.lc=new Map,this.fc=_i.vn(),this.onlineState="Unknown",this.dc=void 0}get isPrimaryClient(){return!0===this.dc}}async function Ya(e,t){const n=Tu(e);let r,s;const i=n.ic.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.ec();else{const e=await bo(n.localStore,Xt(t));n.isPrimaryClient&&ta(n.remoteStore,e);const i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await Xa(n,t,r,"current"===i,e.resumeToken)}return s}async function Xa(e,t,n,r,s){e._c=(t,n,r)=>async function(e,t,n,r){let s=t.view.Wu(n);s.$i&&(s=await Eo(e.localStore,t.query,!1).then((({documents:e})=>t.view.Wu(e,s))));const i=r&&r.targetChanges.get(t.targetId),o=t.view.applyChanges(s,e.isPrimaryClient,i);return uu(e,t.targetId,o.Xu),o.snapshot}(e,t,n,r);const i=await Eo(e.localStore,t,!0),o=new za(t,i.Hi),a=o.Wu(i.documents),u=or.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,s),c=o.applyChanges(a,e.isPrimaryClient,u);uu(e,n,c.Xu);const l=new ja(t,n,o);return e.ic.set(t,l),e.rc.has(n)?e.rc.get(n).push(t):e.rc.set(n,[t]),c.snapshot}async function Za(e,t){const n=T(e),r=n.ic.get(t),s=n.rc.get(r.targetId);if(s.length>1)return n.rc.set(r.targetId,s.filter((e=>!en(e,t)))),void n.ic.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await To(n.localStore,r.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(r.targetId),na(n.remoteStore,r.targetId),ou(n,r.targetId)})).catch(re)):(ou(n,r.targetId),await To(n.localStore,r.targetId,!0))}async function Ja(e,t){const n=T(e);try{const e=await function(e,t){const n=T(e),r=t.snapshotVersion;let s=n.qi;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const i=n.Gi.newChangeBuffer({trackRemovals:!0});s=n.qi;const o=[];
1t.targetChanges.forEach(((i,a)=>{const u=s.get(a);if(!u)return;o.push(n.Cs.removeMatchingKeys(e,i.removedDocuments,a).next((()=>n.Cs.addMatchingKeys(e,i.addedDocuments,a))));let c=u.withSequenceNumber(e.currentSequenceNumber);t.targetMismatches.has(a)?c=c.withResumeToken(_e.EMPTY_BYTE_STRING,U.min()).withLastLimboFreeSnapshotVersion(U.min()):i.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(i.resumeToken,r)),s=s.insert(a,c),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(u,c,i)&&o.push(n.Cs.updateTargetData(e,c))}));let a=jn(),u=nr();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push(vo(e,i,t.documentUpdates).next((e=>{a=e.Wi,u=e.zi}))),!r.isEqual(U.min())){const t=n.Cs.getLastRemoteSnapshotVersion(e).next((t=>n.Cs.setTargetsMetadata(e,e.currentSequenceNumber,r)));o.push(t)}return se.waitFor(o).next((()=>i.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,a,u))).next((()=>a))})).then((e=>(n.qi=s,e)))}(n.localStore,t);
1t.targetChanges.forEach(((e,t)=>{const r=n.cc.get(t);r&&(I(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.nc=!0:e.modifiedDocuments.size>0?I(r.nc):e.removedDocuments.size>0&&(I(r.nc),r.nc=!1))})),await hu(n,e,t)}catch(e){await re(e)}}function eu(e,t,n){const r=T(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.ic.forEach(((n,r)=>{const s=r.view.bu(t);s.snapshot&&e.push(s.snapshot)})),function(e,t){const n=T(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const s of n.listeners)s.bu(t)&&(r=!0)})),r&&qa(n)}(r.eventManager,t),e.length&&r.sc.Wo(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function tu(e,t,n){const r=T(e);r.sharedClientState.updateQueryState(t,"rejected",n);const s=r.cc.get(t),i=s&&s.key;if(i){let e=new xt(Q.comparator);e=e.insert(i,Ft.newNoDocument(i,U.min()));const n=nr().add(i),s=new ir(U.min(),new Map,new Nt(L),e,n);await Ja(r,s),r.uc=r.uc.remove(i),r.cc.delete(t),lu(r)}else await To(r.localStore,t,!1).then((()=>ou(r,t,n))).catch(re)}async function nu(e,t){const n=T(e),r=t.batch.batchId;try{const e=await function(e,t){const n=T(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),s=n.Gi.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const s=n.batch,i=s.keys();let o=se.resolve();return i.forEach((e=>{o=o.next((()=>r.getEntry(t,e))).next((t=>{const i=n.docVersions.get(e);I(null!==i),t.version.compareTo(i)<0&&(s.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))}))})),o.next((()=>e.mutationQueue.removeMutationBatch(t,s)))}(n,e,t,s).next((()=>s.apply(e))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=nr();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t)))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(n.localStore,t);iu(n,r,null),su(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await hu(n,e)}catch(e){await re(e)}}async function ru(e,t,n){const r=T(e);try{const e=await function(e,t){const n=T(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;
1return n.mutationQueue.lookupMutationBatch(e,t).next((t=>(I(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(r.localStore,t);iu(r,t,n),su(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await hu(r,e)}catch(n){await re(n)}}function su(e,t){(e.lc.get(t)||[]).forEach((e=>{e.resolve()})),e.lc.delete(t)}function iu(e,t,n){const r=T(e);let s=r.hc[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.hc[r.currentUser.toKey()]=s}}function ou(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.rc.get(t))e.ic.delete(r),n&&e.sc.wc(r,n);e.rc.delete(t),e.isPrimaryClient&&e.ac.ls(t).forEach((t=>{e.ac.containsKey(t)||au(e,t)}))}function au(e,t){e.oc.delete(t.path.canonicalString());const n=e.uc.get(t);null!==n&&(na(e.remoteStore,n),e.uc=e.uc.remove(t),e.cc.delete(n),lu(e))}function uu(e,t,n){for(const r of n)r instanceof $a?(e.ac.addReference(r.key,t),cu(e,r)):r instanceof Qa?(g("SyncEngine","Document no longer in limbo: "+r.key),e.ac.removeReference(r.key,t),e.ac.containsKey(r.key)||au(e,r.key)):v()}function cu(e,t){const n=t.key,r=n.path.canonicalString();e.uc.get(n)||e.oc.has(r)||(g("SyncEngine","New document in limbo: "+n),e.oc.add(r),lu(e))}function lu(e){for(;e.oc.size>0&&e.uc.size<e.maxConcurrentLimboResolutions;){const t=e.oc.values().next().value;e.oc.delete(t);const n=new Q(K.fromString(t)),r=e.fc.next();e.cc.set(r,new Wa(n)),e.uc=e.uc.insert(n,r),ta(e.remoteStore,new Ss(Xt(Qt(n.path)),r,2,pe.at))}}async function hu(e,t,n){const r=T(e),s=[],i=[],o=[];r.ic.isEmpty()||(r.ic.forEach(((e,a)=>{o.push(r._c(a,t,n).then((e=>
1{if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(a.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){s.push(e);const t=fo.Ci(a.targetId,e);i.push(t)}})))})),await Promise.all(o),r.sc.Wo(s),await async function(e,t){const n=T(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>se.forEach(t,(t=>se.forEach(t.Si,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>se.forEach(t.Di,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!ce(e))throw e;g("LocalStore","Failed to update sequence numbers: "+e)}for(const r of t){const e=r.targetId;if(!r.fromCache){const t=n.qi.get(e),r=t.snapshotVersion,s=t.withLastLimboFreeSnapshotVersion(r);n.qi=n.qi.insert(e,s)}}}(r.localStore,i))}async function du(e,t){const n=T(e);if(!n.currentUser.isEqual(t)){g("SyncEngine","User change. New user:",t.toKey());const e=await yo(n.localStore,t);n.currentUser=t,function(e,t){e.lc.forEach((e=>{e.forEach((e=>{e.reject(new S(E.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),e.lc.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await hu(n,e.ji)}}function fu(e,t){const n=T(e),r=n.cc.get(t);if(r&&r.nc)return nr().add(r.key);{let e=nr();const r=n.rc.get(t);if(!r)return e;for(const t of r){const r=n.ic.get(t);e=e.unionWith(r.view.ju)}return e}}async function mu(e,t){const n=T(e),r=await Eo(n.localStore,t.query,!0),s=t.view.tc(r);return n.isPrimaryClient&&uu(n,t.targetId,s.Xu),s}async function gu(e,t){const n=T(e);return xo(n.localStore,t).then((e=>hu(n,e)))}async function pu(e,t,n,r){const s=T(e),i=await function(e,t){const n=T(e),r=T(n.mutationQueue);return n.persistence.runTransaction("Lookup mutation documents","readonly",(e=>r.Tn(e,t).next((t=>t?n.localDocuments.getDocuments(e,t):se.resolve(null)))))}(s.localStore,t);null!==i?("pending"===n?await ma(s.remoteStore):"acknowledged"===n||"rejected"===n?(iu(s,t,r||null),su(s,t),function(e,t){T(T(e).mutationQueue).An(t)}(s.localStore,t)):v(),await hu(s,i)):g("SyncEngine","Cannot apply mutation batch with id: "+t)}async function yu(e,t,n){const r=T(e),s=[],i=[];for(const o of t){let e;const t=r.rc.get(o);if(t&&0!==t.length){e=await bo(r.localStore,Xt(t[0]));for(const e of t){const t=r.ic.get(e),n=await mu(r,t);n.snapshot&&i.push(n.snapshot)}}else{const t=await So(r.localStore,o);e=await bo(r.localStore,t),await Xa(r,wu(t),o,!1,e.resumeToken)}s.push(e)}return r.sc.Wo(i),s}function wu(e){return $t(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function vu(e){const t=T(e);return T(T(t.localStore).persistence).vi()}async function Iu(e,t,n,r){const s=T(e);if(s.dc)return void g("SyncEngine","Ignoring unexpected query state notification.");const i=s.rc.get(t);if(i&&i.length>0)switch(n){case"current":case"not-current":{const e=await xo(s.localStore,sn(i[0])),r=ir.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,_e.EMPTY_BYTE_STRING);await hu(s,e,r);break}case"rejected":await To(s.localStore,t,!0),ou(s,t,r);break;default:v()}}async function bu(e,t,n){const r=Tu(e);if(r.dc){for(const e of t){if(r.rc.has(e)){g("SyncEngine","Adding an already active target "+e);continue}const t=await So(r.localStore,e),n=await bo(r.localStore,t);await Xa(r,wu(t),n.targetId,!1,n.resumeToken),ta(r.remoteStore,n)}for(const e of n)r.rc.has(e)&&await To(r.localStore,e,!1).then((()=>{na(r.remoteStore,e),ou(r,e)})).catch(re)}}function Tu(e){const t=T(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Ja.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=fu.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=tu.bind(null,t),t.sc.Wo=La.bind(null,t.eventManager),t.sc.wc=Oa.bind(null,t.eventManager),t}function Eu(e){const t=T(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=nu.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=ru.bind(null,t),t}class Su{constructor(){this.synchronizeTabs=!1}async initialize(e){this.yt=Qo(e.databaseInfo.databaseId),this.sharedClientState=this.gc(e),this.persistence=this.yc(e),await this.persistence.start(),this.localStore=this.Ic(e),this.gcScheduler
1=this.Tc(e,this.localStore),this.indexBackfillerScheduler=this.Ec(e,this.localStore)}Tc(e,t){return null}Ec(e,t){return null}Ic(e){return po(this.persistence,new mo,e.initialUser,this.yt)}yc(e){return new no(so.Bs,this.yt)}gc(e){return new Oo}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class xu extends Su{constructor(e,t,n){super(),this.Ac=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ac.initialize(this,e),await Eu(this.Ac.syncEngine),await ma(this.Ac.remoteStore),await this.persistence.li((()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve())))}Ic(e){return po(this.persistence,new mo,e.initialUser,this.yt)}Tc(e,t){const n=this.persistence.referenceDelegate.garbageCollector;return new Vi(n,e.asyncQueue,t)}Ec(e,t){const n=new ge(t,this.persistence);return new me(e.asyncQueue,n)}yc(e){const t=ho(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?wi.withCacheSize(this.cacheSizeBytes):wi.DEFAULT;return new uo(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,Go(),$o(),this.yt,this.sharedClientState,!!this.forceOwnership)}gc(e){return new Oo}}class _u extends xu{constructor(e,t){super(e,t,!1),this.Ac=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);const t=this.Ac.syncEngine;this.sharedClientState instanceof Lo&&(this.sharedClientState.syncEngine={Fr:pu.bind(null,t),$r:Iu.bind(null,t),Br:bu.bind(null,t),vi:vu.bind(null,t),Mr:gu.bind(null,t)},await this.sharedClientState.start()),await this.persistence.li((async e=>{await async function(e,t){const n=T(e);if(Tu(n),Eu(n),!0===t&&!0!==n.dc){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await yu(n,e.toArray());n.dc=!0,await Sa(n.remoteStore,!0);for(const r of t)ta(n.remoteStore,r)}else if(!1===t&&!1!==n.dc){const e=[];let t=Promise.resolve();n.rc.forEach(((r,s)=>{n.sharedClientState.isLocalQueryTarget(s)?e.push(s):t=t.then((()=>(ou(n,s),To(n.localStore,s,!0)))),na(n.remoteStore,s)})),await t,await yu(n,e),function(e){const t=T(e);t.cc.forEach(((e,n)=>{na(t.remoteStore,n)})),t.ac.fs(),t.cc=new Map,t.uc=new xt(Q.comparator)}(n),n.dc=!1,await Sa(n.remoteStore,!1)}}(this.Ac.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())}))}gc(e){const t=Go();if(!Lo.C(t))throw new S(E.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const n=ho(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Lo(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class Du{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>eu(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=du.bind(null,this.syncEngine),await Sa(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Va}createDatastore(e){const t=Qo(e.databaseInfo.databaseId),n=(r=e.databaseInfo,new Ko(r));var r;return function(e,t,n,r){return new Yo(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,s=e=>eu(this.syncEngine,e,0),i=Po.C()?new Po:new qo,new Zo(t,n,r,s,i);var t,n,r,s,i}createSyncEngine(e,t){return function(e,t,n,r,s,i,o){const a=new Ha(e,t,n,r,s,i);return o&&(a.dc=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=T(e);g("RemoteStore","RemoteStore shutting down."),t._u.add(5),await ea(t),t.mu.shutdown(),t.gu.set("Unknown")}(this.remoteStore)}}function Nu(e,t,n){if(!n)throw new S(E.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Cu(e,t,n,r){if(!0===t&&!0===r)throw new S(E.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Au(e){if(!Q.isDocumentKey(e))throw new S(E.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function ku(e){if(Q.isDocumentKey(e))throw new S(E.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ru(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":v()}function Vu(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new S(E.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Ru(e);throw new S(E.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function Fu(e,t){if(t<=0)throw new S(E.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}const Mu=new Map;class Lu{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new S(E.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new S(E.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,Cu("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}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&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Ou{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Lu({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new S(E.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 void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new S(E.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 Lu(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new D;switch(e.type){case"gapi":const t=e.client;return new k(t,e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new S(E.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
1d credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Mu.get(e);t&&(g("ComponentProvider","Removing Datastore"),Mu.delete(e),t.terminate())}(this),Promise.resolve()}}function qu(e,t,n,r={}){var s;const i=(e=Vu(e,Ou))._getSettings();if("firestore.googleapis.com"!==i.host&&i.host!==t&&y("Host has been set in both settings() and useEmulator(), emulator host will be used"),e._setSettings(Object.assign(Object.assign({},i),{host:`${t}:${n}`,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=l.MOCK_USER;else{t=(0,o.Sg)(r.mockUserToken,null===(s=e._app)||void 0===s?void 0:s.options.projectId);const i=r.mockUserToken.sub||r.mockUserToken.user_id;if(!i)throw new S(E.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new l(i)}e._authCredentials=new N(new _(t,n))}}class Pu{constructor(e,t,n){this.converter=t,this._key=n,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 Bu(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Pu(this.firestore,e,this._key)}}class Uu{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Uu(this.firestore,e,this._query)}}class Bu extends Uu{constructor(e,t,n){super(e,t,Qt(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Pu(this.firestore,null,new Q(e))}withConverter(e){return new Bu(this.firestore,e,this._path)}}function Ku(e,t,...n){if(e=(0,o.m9)(e),Nu("collection","path",t),e instanceof Ou){const r=K.fromString(t,...n);return ku(r),new Bu(e,null,r)}{if(!(e instanceof Pu||e instanceof Bu))throw new S(E.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(K.fromString(t,...n));return ku(r),new Bu(e.firestore,null,r)}}function Gu(e,t){if(e=Vu(e,Ou),Nu("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new S(E.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Uu(e,null,function(e){return new Gt(K.emptyPath(),e)}(t))}function $u(e,t,...n){if(e=(0,o.m9)(e),1===arguments.length&&(t=M.R()),Nu("doc","path",t),e instanceof Ou){const r=K.fromString(t,...n);return Au(r),new Pu(e,null,new Q(r))}{if(!(e instanceof Pu||e instanceof Bu))throw new S(E.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(K.fromString(t,...n));return Au(r),new Pu(e.firestore,e instanceof Bu?e.converter:null,new Q(r))}}function Qu(e,t){return e=(0,o.m9)(e),t=(0,o.m9)(t),(e instanceof Pu||e instanceof Bu)&&(t instanceof Pu||t instanceof Bu)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function zu(e,t){return e=(0,o.m9)(e),t=(0,o.m9)(t),e instanceof Uu&&t instanceof Uu&&e.firestore===t.firestore&&en(e._query,t._query)&&e.converter===t.converter}function ju(e,t=10240){let n=0;return{async read(){if(n<e.byteLength){const r={value:e.slice(n,n+t),done:!1};return n+=t,r}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class Wu{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Rc(this.observer.next,e)}error(e){this.observer.error?this.Rc(this.observer.error,e):p("Uncaught Error in snapshot listener:",e.toString())}bc(){this.muted=!0}Rc(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}class Hu{constructor(e,t){this.Pc=e,this.yt=t,this.metadata=new x,this.buffer=new Uint8Array,this.vc=new TextDecoder("utf-8"),this.Vc().then((e=>{e&&e.Ou()?this.metadata.resolve(e.ku.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ku)}`))}),(e=>this.metadata.reject(e)))}close(){return this.Pc.cancel()}async getMetadata(){return this.metadata.promise}async mc(){return await this.getMetadata(),this.Vc()}async Vc(){const e=await this.Sc();if(null===e)return null;const t=this.vc.decode(e),n=Number(t);isNaN(n)&&this.Dc(`length string (${t}
1) is not valid number`);const r=await this.Cc(n);return new Ua(JSON.parse(r),e.length+n)}xc(){return this.buffer.findIndex((e=>e==="{".charCodeAt(0)))}async Sc(){for(;this.xc()<0&&!(await this.Nc()););if(0===this.buffer.length)return null;const e=this.xc();e<0&&this.Dc("Reached the end of bundle when a length string is expected.");const t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Cc(e){for(;this.buffer.length<e;)await this.Nc()&&this.Dc("Reached the end of bundle when more is expected.");const t=this.vc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Dc(e){throw this.Pc.cancel(),new Error(`Invalid bundle format: ${e}`)}async Nc(){const e=await this.Pc.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class Yu{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw new S(E.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const n=T(e),r=Nr(n.yt)+"/documents",s={documents:t.map((e=>Sr(n.yt,e)))},i=await n._o("BatchGetDocuments",r,s,t.length),o=new Map;i.forEach((e=>{const t=function(e,t){return"found"in t?function(e,t){I(!!t.found),t.found.name,t.found.updateTime;const n=xr(e,t.found.name),r=br(t.found.updateTime),s=t.found.createTime?br(t.found.createTime):U.min(),i=new Rt({mapValue:{fields:t.found.fields}});return Ft.newFoundDocument(n,r,s,i)}(e,t):"missing"in t?function(e,t){I(!!t.missing),I(!!t.readTime);const n=xr(e,t.missing),r=br(t.readTime);return Ft.newNoDocument(n,r)}(e,t):v()}(n.yt,e);o.set(t.key.toString(),t)}));const a=[];return t.forEach((e=>{const t=o.get(e.toString());I(!!t),a.push(t)})),a}(this.datastore,e);return t.forEach((e=>this.recordVersion(e))),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(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new qn(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const e=this.readVersions;this.mutations.forEach((t=>{e.delete(t.key.toString())})),e.forEach(((e,t)=>{const n=Q.fromPath(t);this.mutations.push(new Pn(n,this.precondition(n)))})),await async function(e,t){const n=T(e),r=Nr(n.yt)+"/documents",s={writes:t.map((e=>Rr(n.yt,e)))};await n.ao("Commit",r,s)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw v();t=U.min()}const n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new S(E.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(U.min())?xn.exists(!1):xn.updateTime(t):xn.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(U.min()))throw new S(E.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return xn.updateTime(t)}return xn.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class Xu{constructor(e,t,n,r,s){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=s,this.kc=n.maxAttempts,this.xo=new zo(this.asyncQueue,"transaction_retry")}run(){this.kc-=1,this.Oc()}Oc(){this.xo.Ro((async()=>{const e=new Yu(this.datastore),t=this.Mc(e);t&&t.then((t=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(t)})).catch((e=>{this.Fc(e)}))))})).catch((e=>{this.Fc(e)}))}))}Mc(e){try{const t=this.updateFunction(e);return!Te(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Fc(e){this.kc>0&&this.$c(e)?(this.kc-=1,this.asyncQueue.enqueueAndForget((()=>(this.Oc(),Promise.resolve())))):this.deferred.reject(e)}$c(e){if("FirebaseError"===e.name){const t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!Gn(t)}return!1}}class Zu{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=l.UNAUTHENTICATED,this.clientId=M.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{g("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(g("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}async getConfiguration(){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}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new S(E.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new x;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){const n=Na(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function Ju(e,t){e.asyncQueue.verifyOperationInProgress(),g("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await yo(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e.offlineComponents=t}async function ec(e,t){e.asyncQueue.verifyOperationInProgress();const n=await tc(e);g("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener((e=>Ea(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Ea(t.remoteStore,n))),e.onlineComponents=t}async function tc(e){return e.offlineComponents||(g("FirestoreClient","Using default OfflineComponentProvider"),await Ju(e,new Su)),e.offlineComponents}async function nc(e){return e.onlineComponents||(g("FirestoreClient","Using default OnlineComponentProvider"),await ec(e,new Du)),e.onlineComponents}function rc(e){return tc(e).then((e=>e.persistence))}function sc(e){return tc(e).then((e=>e.localStore))}function ic(e){return nc(e).then((e=>e.remoteStore))}function oc(e){return nc(e).then((e=>e.syncEngine))}function ac(e){return nc(e).then((e=>e.datastore))}async function uc(e){const t=await nc(e),n=t.eventManager;return n.onListen=Ya.bind(null,t.syncEngine),n.onUnlisten=Za.bind(null,t.syncEngine),n}function cc(e,t,n={}){const r=new x;return e.asyncQueue.enqueueAndForget((async()=>
1function(e,t,n,r,s){const i=new Wu({next:i=>{t.enqueueAndForget((()=>Ma(e,o)));const a=i.docs.has(n);!a&&i.fromCache?s.reject(new S(E.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&i.fromCache&&r&&"server"===r.source?s.reject(new S(E.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.)')):s.resolve(i)},error:e=>s.reject(e)}),o=new Pa(Qt(n.path),i,{includeMetadataChanges:!0,Nu:!0});return Fa(e,o)}(await uc(e),e.asyncQueue,t,n,r))),r.promise}function lc(e,t,n={}){const r=new x;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,s){const i=new Wu({next:n=>{t.enqueueAndForget((()=>Ma(e,o))),n.fromCache&&"server"===r.source?s.reject(new S(E.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.)')):s.resolve(n)},error:e=>s.reject(e)}),o=new Pa(n,i,{includeMetadataChanges:!0,Nu:!0});return Fa(e,o)}(await uc(e),e.asyncQueue,t,n,r))),r.promise}function hc(e,t,n,r){const s=function(e,t){let n;return n="string"==typeof e?(new TextEncoder).encode(e):e,function(e,t){return new Hu(e,t)}(function(e,t){if(e instanceof Uint8Array)return ju(e,t);if(e instanceof ArrayBuffer)return ju(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(n),t)}(n,Qo(t));e.asyncQueue.enqueueAndForget((async()=>{!function(e,t,n){const r=T(e);(async function(e,t,n){try{const r=await t.getMetadata();if(await function(e,t){const n=T(e),r=br(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",(e=>n.Ns.getBundleMetadata(e,t.id))).then((e=>!!e&&e.createTime.compareTo(r)>=0))}(e.localStore,r))return await t.close(),n._completeWith(function(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(r)),Promise.resolve(new Set);n._updateProgress(Ga(r));const s=new Ka(r,e.localStore,t.yt);let i=await t.mc();for(;i;){const e=await s.Fu(i);e&&n._updateProgress(e),i=await t.mc()}const o=await s.complete();return await hu(e,o.Lu,void 0),await function(e,t){const n=T(e);return n.persistence.runTransaction("Save bundle","readwrite",(e=>n.Ns.saveBundleMetadata(e,t)))}(e.localStore,r),n._completeWith(o.progress),Promise.resolve(o.Bu)}catch(e){return y("SyncEngine",`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(r,t,n).then((e=>{r.sharedClientState.notifyBundleLoaded(e)}))}(await oc(e),s,r)}))}class dc{constructor(){this.Bc=Promise.resolve(),this.Lc=[],this.qc=!1,this.Uc=[],this.Kc=null,this.Gc=!1,this.Qc=!1,this.jc=[],this.xo=new zo(this,"async_queue_retry"),this.Wc=()=>{const e=$o();e&&g("AsyncQueue","Visibility state changed to "+e.visibilityState),this.xo.Po()};const e=$o();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Wc)}get isShuttingDown(){return this.qc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.zc(),this.Hc(e)}enterRestrictedMode(e){if(!this.qc){this.qc=!0,this.Qc=e||!1;const t=$o();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Wc)}}enqueue(e){if(this.zc(),this.qc)return new Promise((()=>{}));const t=new x;return this.Hc((()=>this.qc&&this.Qc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Lc.push(e),this.Jc())))}async Jc(){if(0!==this.Lc.length){try{await this.Lc[0](),this.Lc.shift(),this.xo.reset()}catch(e){if(!ce(e))throw e;g("AsyncQueue","Operation failed with retryable error: "+e)}this.Lc.length>0&&this.xo.Ro((()=>this.Jc()))}}Hc(e){const t=this.Bc.then((()=>(this.Gc=!0,e().catch((e=>{this.Kc=e,this.Gc=!1;throw p("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e})).then((e=>(this.Gc=!1,e))))));return this.Bc=t,t}enqueueAfterDelay(e,t,n){this.zc(),this.jc.indexOf(e)>-1&&(t=0);const r=Da.createAndSchedule(this,e,t,n,(e=>this.Yc(e)));return this.Uc.push(r),r}zc(){this.Kc&&v()}verifyOperationInProgress(){}async Xc(){let e;do{e=this.Bc,await e}while(e!==this.Bc)}Zc(e){for(const t of this.Uc)if(t.timerId===e)return!0;return!1}ta(e){return this.Xc().then((()=>{this.Uc.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.Uc)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Xc()}))}ea(e){this.jc.push(e)}Yc(e){const t=this.Uc.indexOf(e);this.Uc.splice(t,1)}}function fc(e){return function(e,t){if("object"!=typeof e||null===e)return!1;const n=e;for(const r of["next","error","complete"])if(r in n&&"function"==typeof n[r])return!0;return!1}(e)}class mc{constructor(){this._progressObserver={},this._taskCompletionResolver=new x,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}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)}}const gc=-1;class pc extends Ou{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new dc,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||wc(this),this._firestoreClient.terminate()}}function yc(e){return e._firestoreClient||wc(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function wc(e){var t;const n=e._freezeSettings(),r=function(e,t,n,r){return new ye(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,n);e._firestoreClient=new Zu(e._authCredentials,e._appCheckCredentials,e._queue,r)}function vc(e,t){Nc(e=Vu(e,pc));const n=yc(e),r=e._freezeSettings(),s=new Du;return bc(n,s,new xu(s,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}function Ic(e){Nc(e=Vu(e,pc));const t=yc(e),n=e._freezeSettings(),r=new Du;return bc(t,r,new _u(r,n.cacheSizeBytes))}
1function bc(e,t,n){const r=new x;return e.asyncQueue.enqueue((async()=>{try{await Ju(e,n),await ec(e,t),r.resolve()}catch(e){const n=e;if(!function(e){return"FirebaseError"===e.name?e.code===E.FAILED_PRECONDITION||e.code===E.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||(22===e.code||20===e.code||11===e.code)}(n))throw n;y("Error enabling offline persistence. Falling back to persistence disabled: "+n),r.reject(n)}})).then((()=>r.promise))}function Tc(e){if(e._initialized&&!e._terminated)throw new S(E.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new x;return e._queue.enqueueAndForgetEvenWhileRestricted((async()=>{try{await async function(e){if(!oe.C())return Promise.resolve();const t=e+"main";await oe.delete(t)}(ho(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}})),t.promise}function Ec(e){return function(e){const t=new x;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t){const n=T(e);aa(n.remoteStore)||g("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=T(e);return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",(e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e)))}(n.localStore);if(-1===e)return void t.resolve();const r=n.lc.get(e)||[];r.push(t),n.lc.set(e,r)}catch(e){const n=Na(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await oc(e),t))),t.promise}(yc(e=Vu(e,pc)))}function Sc(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await rc(e),n=await ic(e);return t.setNetworkEnabled(!0),function(e){const t=T(e);return t._u.delete(0),Jo(t)}(n)}))}(yc(e=Vu(e,pc)))}function xc(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await rc(e),n=await ic(e);return t.setNetworkEnabled(!1),async function(e){const t=T(e);t._u.add(0),await ea(t),t.gu.set("Offline")}(n)}))}(yc(e=Vu(e,pc)))}function _c(e,t){const n=yc(e=Vu(e,pc)),r=new mc;return hc(n,e._databaseId,t,r),r}function Dc(e,t){return function(e,t){return e.asyncQueue.enqueue((async()=>function(e,t){const n=T(e);return n.persistence.runTransaction("Get named query","readonly",(e=>n.Ns.getNamedQuery(e,t)))}(await sc(e),t)))}(yc(e=Vu(e,pc)),t).then((t=>t?new Uu(e,null,t.query):null))}function Nc(e){if(e._initialized||e._terminated)throw new S(E.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.")}class Cc{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Cc(_e.fromBase64String(e))}catch(e){throw new S(E.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Cc(_e.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)}}class Ac{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new S(E.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new $(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class kc{constructor(e){this._methodName=e}}class Rc{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new S(E.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new S(E.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}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return L(this._lat,e._lat)||L(this._long,e._long)}}const Vc=/^__.*__$/;class Fc{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Fn(e,this.data,this.fieldMask,t,this.fieldTransforms):new Vn(e,this.data,t,this.fieldTransforms)}}class Mc{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Fn(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function Lc(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw v()}}class Oc{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.yt=n,this.ignoreUndefinedProperties=r,void 0===s&&this.na(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get sa(){return this.settings.sa}ia(e){return new Oc(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.yt,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}ra(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.ua(e),r}ca(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.na(),r}aa(e){return this.ia({path:void 0,oa:!0})}ha(e){return rl(e,this.settings.methodName,this.settings.la||!1,this.path,this.settings.fa)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}na(){if(this.path)for(let e=0;e<this.path.length;e++)this.ua(this.path.get(e))}ua(e){if(0===e.length)throw this.ha("Document fields must not be empty");if(Lc(this.sa)&&Vc.test(e))throw this.ha('Document fields cannot begin and end with "__"')}}class qc{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.yt=n||Qo(e)}da(e,t,n,r=!1){return new Oc({sa:e,methodName:t,fa:n,path:$.emptyPath(),oa:!1,la:r},this.databaseId,this.yt,this.ignoreUndefinedProperties)}}function Pc(e){const t=e._freezeSettings(),n=Qo(e._databaseId);return new qc(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Uc(e,t,n,r,s,i={}){const o=e.da(i.merge||i.mergeFields?2:0,t,n,s);Jc("Data must be an object, but it was:",o,r);const a=Xc(r,o);let u,c;if(i.merge)u=new kt(o.fieldMask),c=o.fieldTransforms;else if(i.mergeFields){const e=[];for(const r of i.mergeFields){const s=el(t,r,n);if(!o.contains(s))throw new S(E.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);sl(e,s)||e.push(s)}u=new kt(e),c=o.fieldTransforms.filter((e=>u.covers(e.field)))}else u=null,c=o.fieldTransforms;return new Fc(new Rt(a),u,c)}class Bc extends kc{_toFieldTransform(e){if(2!==e.sa)throw 1===e.sa?e.ha(`${this._methodName}() can only appear at the top level of your update data`):e.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof Bc}}function Kc(e,t,n){return new Oc({sa:3,fa:t.settings.fa,methodName:e._methodName,oa:n},t.databaseId,t.yt,t.ignoreUndefinedProperties)}class Gc extends kc{_toFieldTransform(e){return new En(e.path,new gn)}isEqual(e){return e instanceof Gc}}class $c extends kc{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=Kc(this,e,!0),n=this._a.map((e=>Yc(e,t))),r=new pn(n);return new En(e.path,r)}isEqual(e){return this===e}}class Qc extends kc{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=Kc(this,e,!0),n=this._a.map((e=>Yc(e,t))),r=new wn(n);return new En(e.path,r)}isEqual(e){return this===e}}class zc extends kc{constructor(e,t){super(e),this.wa=t}_toFieldTransform(e){const t=new In(e.yt,ln(e.yt,this.wa));return new En(e.path,t)}isEqual(e){return this===e}}function jc(e,t,n,r){const s=e.da(1,t,n);Jc("Data must be an object, but it was:",s,r);const i=[],a=Rt.empty();Ie(r,((e,r)=>{const u=nl(t,e,n);r=(0,o.m9)(r);const c=s.ca(u);if(r instanceof Bc)i.push(u);else{const e=Yc(r,c);null!=e&&(i.push(u),a.set(u,e))}}));const u=new kt(i);return new Mc(a,u,s.fieldTransforms)}function Wc(e,t,n,r,s,i){const a=e.da(1,t,n),u=[el(t,r,n)],c=[s];if(i.length%2!=0)throw new S(E.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let o=0;o<i.length;o+=2)u.push(el(t,i[o])),c.push(i[o+1]);const l=[],h=Rt.empty();for(let f=u.length-1;f>=0;--f)if(!sl(l,u[f])){const e=u[f];let t=c[f];t=(0,o.m9)(t);const n=a.ca(e);
1if(t instanceof Bc)l.push(e);else{const r=Yc(t,n);null!=r&&(l.push(e),h.set(e,r))}}const d=new kt(l);return new Mc(h,d,a.fieldTransforms)}function Hc(e,t,n,r=!1){return Yc(n,e.da(r?4:3,t))}function Yc(e,t){if(Zc(e=(0,o.m9)(e)))return Jc("Unsupported field value:",t,e),Xc(e,t);if(e instanceof kc)return function(e,t){if(!Lc(t.sa))throw t.ha(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.ha(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.oa&&4!==t.sa)throw t.ha("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const s of e){let e=Yc(s,t.aa(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=(0,o.m9)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ln(t.yt,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=P.fromDate(e);return{timestampValue:wr(t.yt,n)}}if(e instanceof P){const n=new P(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:wr(t.yt,n)}}if(e instanceof Rc)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Cc)return{bytesValue:vr(t.yt,e._byteString)};if(e instanceof Pu){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.ha(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:Tr(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.ha(`Unsupported field value: ${Ru(e)}`)}(e,t)}function Xc(e,t){const n={};return be(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):Ie(e,((e,r)=>{const s=Yc(r,t.ra(e));null!=s&&(n[e]=s)})),{mapValue:{fields:n}}}function Zc(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof P||e instanceof Rc||e instanceof Cc||e instanceof Pu||e instanceof kc)}function Jc(e,t,n){if(!Zc(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=Ru(n);throw"an object"===r?t.ha(e+" a custom object"):t.ha(e+" "+r)}}function el(e,t,n){if((t=(0,o.m9)(t))instanceof Ac)return t._internalPath;if("string"==typeof t)return nl(e,t);throw rl("Field path arguments must be of type string or ",e,!1,void 0,n)}const tl=new RegExp("[~\\*/\\[\\]]");function nl(e,t,n){if(t.search(tl)>=0)throw rl(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new Ac(...t.split("."))._internalPath}catch(r){throw rl(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function rl(e,t,n,r,s){const i=r&&!r.isEmpty(),o=void 0!==s;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let u="";return(i||o)&&(u+=" (found",i&&(u+=` in field ${r}`),o&&(u+=` in document ${s}`),u+=")"),new S(E.INVALID_ARGUMENT,a+e+u)}function sl(e,t){return e.some((e=>e.isEqual(t)))}class il{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new Pu(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new ol(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const t=this._document.data.field(al("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class ol extends il{data(){return super.data()}}function al(e,t){return"string"==typeof t?nl(e,t):t instanceof Ac?t._internalPath:t._delegate._internalPath}function ul(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new S(E.UNIMPLEMENT
1ED,"limitToLast() queries require specifying at least one orderBy() clause")}class cl{}class ll extends cl{}function hl(e,t,...n){let r=[];t instanceof cl&&r.push(t),r=r.concat(n),function(e){const t=e.filter((e=>e instanceof ml)).length,n=e.filter((e=>e instanceof dl)).length;if(t>1||t>0&&n>0)throw new S(E.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(const s of r)e=s._apply(e);return e}class dl extends ll{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new dl(e,t,n)}_apply(e){const t=this._parse(e);return Cl(e._query,t),new Uu(e.firestore,e.converter,Zt(e._query,t))}_parse(e){const t=Pc(e.firestore);return function(e,t,n,r,s,i,o){let a;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new S(E.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){Nl(o,i);const t=[];for(const n of o)t.push(Dl(r,e,n));a={arrayValue:{values:t}}}else a=Dl(r,e,o)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||Nl(o,i),a=Hc(n,"where",o,"in"===i||"not-in"===i);return it.create(s,i,a)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value)}}function fl(e,t,n){const r=t,s=al("where",e);return dl._create(s,r,n)}class ml extends cl{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new ml(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:ot.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const s of r)Cl(n,s),n=Zt(n,s)}(e._query,t),new Uu(e.firestore,e.converter,Zt(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class gl extends ll{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new gl(e,t)}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new S(E.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new S(E.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");const r=new Et(t,n);return function(e,t){if(null===jt(e)){const n=Wt(e);null!==n&&Al(e,n,t.field)}}(e,r),r}(e._query,this._field,this._direction);return new Uu(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new Gt(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}function pl(e,t="asc"){const n=t,r=al("orderBy",e);return gl._create(r,n)}class yl extends ll{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new yl(e,t,n)}_apply(e){return new Uu(e.firestore,e.converter,Jt(e._query,this._limit,this._limitType))}}function wl(e){return Fu("limit",e),yl._create("limit",e,"F")}function vl(e){return Fu("limitToLast",e),yl._create("limitToLast",e,"L")}class Il extends ll{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Il(e,t,n)}_apply(e){const t=_l(e,this.type,this._docOrFields,this._inclusive);return new Uu(e.firestore,e.converter,function(e,t){return new Gt(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}function bl(...e){return Il._create("startAt",e,!0)}function Tl(...e){return Il._create("startAfter",e,!1)}class El extends ll{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new El(e,t,n)}_apply(e){const t=_l(e,this.type,this._docOrFields,this._inclusive);return new Uu(e.firestore,e.converter,function(e,t){return new Gt(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}function Sl(...e){return El._create("endBefore",e,!1)}function xl(...e){return El._create("endAt",e,!0)}function _l(e,t,n,r){if(n[0]=(0,o.m9)(n[0]),n[0]instanceof il)return function(e,t,n,r,s
1){if(!r)throw new S(E.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const o of Yt(e))if(o.field.isKeyField())i.push(Ge(t,r.key));else{const e=r.data.field(o.field);if(ke(e))throw new S(E.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+o.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=o.field.canonicalString();throw new S(E.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}i.push(e)}return new tt(i,s)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const s=Pc(e.firestore);return function(e,t,n,r,s,i){const o=e.explicitOrderBy;if(s.length>o.length)throw new S(E.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let u=0;u<s.length;u++){const i=s[u];if(o[u].field.isKeyField()){if("string"!=typeof i)throw new S(E.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof i}`);if(!Ht(e)&&-1!==i.indexOf("/"))throw new S(E.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${i}' contains a slash.`);const n=e.path.child(K.fromString(i));if(!Q.isDocumentKey(n))throw new S(E.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const s=new Q(n);a.push(Ge(t,s))}else{const e=Hc(n,r,i);a.push(e)}}return new tt(a,i)}(e._query,e.firestore._databaseId,s,t,n,r)}}function Dl(e,t,n){if("string"==typeof(n=(0,o.m9)(n))){if(""===n)throw new S(E.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Ht(t)&&-1!==n.indexOf("/"))throw new S(E.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);const r=t.path.child(K.fromString(n));if(!Q.isDocumentKey(r))throw new S(E.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Ge(e,new Q(r))}if(n instanceof Pu)return Ge(e,n._key);throw new S(E.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Ru(n)}.`)}function Nl(e,t){if(!Array.isArray(e)||0===e.length)throw new S(E.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(e.length>10)throw new S(E.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function Cl(e,t){if(t.isInequality()){const n=Wt(e),r=t.field;if(null!==n&&!n.isEqual(r))throw new S(E.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${r.toString()}'`);const s=jt(e);null!==s&&Al(e,r,s)}const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==n)throw n===t.op?new S(E.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new S(E.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function Al(e,t,n){if(!n.isEqual(t))throw new S(E.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class kl{convertValue(e,t="none"){switch(Le(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Ce(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(Ae(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 10:return this.convertObject(e.mapValue,t);default:throw v()}}convertObject(e,t){const n={};return Ie(e.fields,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertGeoPoint(e){return new Rc(Ce(e.latitude),Ce(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=Re(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ve(e));default:return null}}convertTimestamp(e){const t=Ne(e);return new P(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=K.fromString(e);I(Qr(n));const r=new we(n.get(1),n.get(3)),s=new Q(n.popFirst(5));return r.isEqual(t)||p(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}function Rl(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Vl extends kl{constructor(e){super(),this.firestore=e}convertBytes(e){return new Cc(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);
vendor: 5,196 bytes, line 1
1return new Pu(this.firestore,null,t)}}class Fl{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Ml extends il{constructor(e,t,n,r,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new Ll(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){const n=this._document.data.field(al("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Ll extends Ml{data(e={}){return super.data(e)}}class Ol{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Fl(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Ll(this._firestore,this._userDataWriter,n.key,n,new Fl(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new S(E.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(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>{const r=new Ll(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Fl(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Ll(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Fl(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let s=-1,i=-1;return 0!==t.type&&(s=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),i=n.indexOf(t.doc.key)),{type:ql(t.type),doc:r,oldIndex:s,newIndex:i}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function ql(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return v()}}function Pl(e,t){return e instanceof Ml&&t instanceof Ml?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof Ol&&t instanceof Ol&&e._firestore===t._firestore&&zu(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function Ul(e){e=Vu(e,Pu);const t=Vu(e.firestore,pc);return cc(yc(t),e._key).then((n=>eh(t,e,n)))}class Bl extends kl{constructor(e){super(),this.firestore=e}convertBytes(e){return new Cc(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Pu(this.firestore,null,t)}}function Kl(e){e=Vu(e,Pu);const t=Vu(e.firestore,pc),n=yc(t),r=new Bl(t);return function(e,t){const n=new x;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await function(e,t){const n=T(e);return n.persistence.runTransaction("read document","readonly",(e=>n.localDocuments.getDocument(e,t)))}(e,t);r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new S(E.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(e){const r=Na(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await sc(e),t,n))),n.promise}(n,e._key).then((n=>new Ml(t,r,e._key,n,new Fl(null!==n&&n.hasLocalMutations,!0),e.converter)))}function Gl(e){e=Vu(e,Pu);const t=Vu(e.firestore,pc);return cc(yc(t),e._key,{source:"server"}).then((n=>eh(t,e,n)))}function $l(e){e=Vu(e,Uu);const t=Vu(e.firestore,pc),n=yc(t),r=new Bl(t);return ul(e._query),lc(n,e._query).then((n=>new Ol(t,r,e,n)))}function Ql(e){e=Vu(e,Uu);const t=Vu(e.firestore,pc),n=yc(t),r=new Bl(t);return function(e,t){const n=new x;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await Eo(e,t,!0),s=new za(t,r.Hi),i=s.Wu(r.documents),o=s.applyChanges(i,!1);n.resolve(o.snapshot)}catch(e){const r=Na(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await sc(e),t,n))),n.promise}(n,e._query).then((n=>new Ol(t,r,e,n)))}function zl(e){e=Vu(e,Uu);const t=Vu(e.firestore,pc),n=yc(t),r=new Bl(t);return lc(n,e._query,{source:"server"}).then((n=>new Ol(t,r,e,n)))}function jl(e,t,n){e=Vu(e,Pu);const r=Vu(e.firestore,pc),s=Rl(e.converter,t,n);return Jl(r,[Uc(Pc(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,xn.none())])}function Wl(e,t,n,...r){e=Vu(e,Pu);const s=Vu(e.firestore,pc),i=Pc(s);let a;
1return a="string"==typeof(t=(0,o.m9)(t))||t instanceof Ac?Wc(i,"updateDoc",e._key,t,n,r):jc(i,"updateDoc",e._key,t),Jl(s,[a.toMutation(e._key,xn.exists(!0))])}function Hl(e){return Jl(Vu(e.firestore,pc),[new qn(e._key,xn.none())])}function Yl(e,t){const n=Vu(e.firestore,pc),r=$u(e),s=Rl(e.converter,t);return Jl(n,[Uc(Pc(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,xn.exists(!1))]).then((()=>r))}function Xl(e,...t){var n,r,s;e=(0,o.m9)(e);let i={includeMetadataChanges:!1},a=0;"object"!=typeof t[a]||fc(t[a])||(i=t[a],a++);const u={includeMetadataChanges:i.includeMetadataChanges};if(fc(t[a])){const e=t[a];t[a]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[a+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[a+2]=null===(s=e.complete)||void 0===s?void 0:s.bind(e)}let c,l,h;if(e instanceof Pu)l=Vu(e.firestore,pc),h=Qt(e._key.path),c={next:n=>{t[a]&&t[a](eh(l,e,n))},error:t[a+1],complete:t[a+2]};else{const n=Vu(e,Uu);l=Vu(n.firestore,pc),h=n._query;const r=new Bl(l);c={next:e=>{t[a]&&t[a](new Ol(l,r,n,e))},error:t[a+1],complete:t[a+2]},ul(e._query)}return function(e,t,n,r){const s=new Wu(r),i=new Pa(t,s,n);return e.asyncQueue.enqueueAndForget((async()=>Fa(await uc(e),i))),()=>{s.bc(),e.asyncQueue.enqueueAndForget((async()=>Ma(await uc(e),i)))}}(yc(l),h,u,c)}function Zl(e,t){return function(e,t){const n=new Wu(t);return e.asyncQueue.enqueueAndForget((async()=>function(e,t){T(e).Ru.add(t),t.next()}(await uc(e),n))),()=>{n.bc(),e.asyncQueue.enqueueAndForget((async()=>function(e,t){T(e).Ru.delete(t)}(await uc(e),n)))}}(yc(e=Vu(e,pc)),fc(t)?t:{next:t})}function Jl(e,t){return function(e,t){const n=new x;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=Eu(e);try{const e=await function(e,t){const n=T(e),r=P.now(),s=t.reduce(((e,t)=>e.add(t.key)),nr());let i,o;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let a=jn(),u=nr();return n.Gi.getEntries(e,s).next((e=>{a=e,a.forEach(((e,t)=>{t.isValidDocument()||(u=u.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,a))).next((s=>{i=s;const o=[];for(const e of t){const t=kn(e,i.get(e.key).overlayedDocument);null!=t&&o.push(new Fn(e.key,t,Vt(t.value.mapValue),xn.exists(!0)))}
1return n.mutationQueue.addMutationBatch(e,r,o,t)})).next((t=>{o=t;const r=t.applyToLocalDocumentSet(i,u);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)}))})).then((()=>({batchId:o.batchId,changes:Yn(i)})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.hc[e.currentUser.toKey()];r||(r=new xt(L)),r=r.insert(t,n),e.hc[e.currentUser.toKey()]=r}(r,e.batchId,n),await hu(r,e.changes),await ma(r.remoteStore)}catch(e){const t=Na(e,"Failed to persist write");n.reject(t)}}(await oc(e),t,n))),n.promise}(yc(e),t)}function eh(e,t,n){const r=n.docs.get(t._key),s=new Bl(e);return new Ml(e,s,t._key,r,new Fl(n.hasPendingWrites,n.fromCache),t.converter)}const th={maxAttempts:5};class nh{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=Pc(e)}set(e,t,n){this._verifyNotCommitted();const r=rh(e,this._firestore),s=Rl(r.converter,t,n),i=Uc(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,xn.none())),this}update(e,t,n,...r){this._verifyNotCommitted();const s=rh(e,this._firestore);let i;return i="string"==typeof(t=(0,o.m9)(t))||t instanceof Ac?Wc(this._dataReader,"WriteBatch.update",s._key,t,n,r):jc(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,xn.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=rh(e,this._firestore);return this._mutations=this._mutations.concat(new qn(t._key,xn.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 S(E.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function rh(e,t){if((e=(0,o.m9)(e)).firestore!==t)throw new S(E.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class sh extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=Pc(e)}get(e){const t=rh(e,this._firestore),n=new Vl(this._firestore);return this._transaction.lookup([t._key]).then((e=>{if(!e||1!==e.length)return v();const r=e[0];if(r.isFoundDocument())return new il(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new il(this._firestore,n,t._key,null,t.converter);throw v()}))}set(e,t,n){const r=rh(e,this._firestore),s=Rl(r.converter,t,n),i=Uc(this._dataReader,"Transaction.set",r._key,s,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){const s=rh(e,this._firestore);let i;return i="string"==typeof(t=(0,o.m9)(t))||t instanceof Ac?Wc(this._dataReader,"Transaction.update",s._key,t,n,r):jc(this._dataReader,"Transaction.update",s._key,t),this._transaction.update(s._key,i),this}delete(e){const t=rh(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=rh(e,this._firestore),n=new Bl(this._firestore);return super.get(e).then((e=>new Ml(this._firestore,n,t._key,e._document,new Fl(!1,!1),t.converter)))}}function ih(e,t,n){e=Vu(e,pc);const r=Object.assign(Object.assign({},th),n);return function(e){if(e.maxAttempts<1)throw new S(E.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(e,t,n){const r=new x;return e.asyncQueue.enqueueAndForget((async()=>{const s=await ac(e);new Xu(e.asyncQueue,s,n,t,r).run()})),r.promise}(yc(e),(n=>t(new sh(e,n))),r)}function oh(){return new Bc("deleteField")}function ah(){return new Gc("serverTimestamp")}function uh(...e){return new $c("arrayUnion",e)}function ch(...e){return new Qc("arrayRemove",e)}function lh(e){return new zc("increment",e)}!function(e,t=!0){!function(e){h=e}(r.SDK_VERSION),(0,r._registerComponent)(new s.wA("firestore",((e,{instanceIdentifier:n,options:r})=>{const s=e.getProvider("app").getImmediate(),i=new pc(new C(e.getProvider("auth-internal")),new V(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new S(E.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new we(e.options.projectId,t)}(s,n),s);return r=Object.assign({useFetchStreams:t},r),i._setSettings(r),i}),"PUBLIC").setMultipleInstances(!0)),(0,r.registerVersion)(c,"3.8.0",e),(0,r.registerVersion)(c,"3.8.0","esm2017")}()}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.