PageSourceSearch

https://www.finalroundai.com/_next/static/chunks/14aeac6e-da969d97c1792fce.js

js finalroundai.com collected 2026-09-24 17:58:47 UTC 215,931 bytes, 7 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[19149],{64797:(e,t,n)=>{n.d(t,{K7:()=>oR,O5:()=>oO,_A:()=>oy,vK:()=>oC});var r,i,s,a,o=n(84073),l=n(66945),u=n(52126),h=n(74953),c=n(54225),d=n(16501),m=n(40459),f=n(60996).hp;let g="@firebase/firestore",p="4.7.16";class y{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}}y.UNAUTHENTICATED=new y(null),y.GOOGLE_CREDENTIALS=new y("google-credentials-uid"),y.FIRST_PARTY=new y("first-party-uid"),y.MOCK_USER=new y("mock-user");let w="11.8.1",v=new u.Vy("@firebase/firestore");function I(){return v.logLevel}function T(e,...t){if(v.logLevel<=u.$b.DEBUG){let n=t.map(b);v.debug(`Firestore (${w}): ${e}`,...n)}}function E(e,...t){if(v.logLevel<=u.$b.ERROR){let n=t.map(b);v.error(`Firestore (${w}): ${e}`,...n)}}function x(e,...t){if(v.logLevel<=u.$b.WARN){let n=t.map(b);v.warn(`Firestore (${w}): ${e}`,...n)}}function b(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function S(e,t,n){let r="Unexpected state";"string"==typeof t?r=t:n=t,_(e,r,n)}function _(e,t,n){let r=`FIRESTORE (${w}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==n)try{r+=" CONTEXT: "+JSON.stringify(n)}catch(e){r+=" CONTEXT: "+n}throw E(r),Error(r)}function D(e,t,n,r){let i="Unexpected state";"string"==typeof n?i=n:r=n,e||_(t,i,r)}let k={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 C extends h.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class A{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class N{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class R{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(y.UNAUTHENTICATED))}shutdown(){}}class O{constructor(e){this.t=e,this.currentUser=y.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){D(void 0===this.o,42304);let n=this.i,r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve(),i=new A;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new A,e.enqueueRetryable(()=>r(this.currentUser))};let s=()=>{let t=i;e.enqueueRetryable(async()=>{await t.promise,await r(this.currentUser)})},a=e=>{T("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(T("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new A)}},0),s()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(T("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(D("string"==typeof t.accessToken,31837,{l:t}),new N(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){let e=this.auth&&this.auth.getUid();return D(null===e||"string"==typeof e,2055,{h:e}),new y(e)}}class V{constructor(e,t,n){this.P=e,this.T=t,this.I=n,this.type="FirstParty",this.user=y.FIRST_PARTY,this.A=new Map}R(){return this.I?this.I():null}get headers(){this.A.set("X-Goog-AuthUser",this.P);let e=this.R();return e&&this.A.set("Authorization",e),this.T&&this.A.set("X-Goog-Iam-Authorization-Token",this.T),this.A}}class M{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new V(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(y.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class P{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 F{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,(0,o.xZ)(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){D(void 0===this.o,3512);let n=e=>{null!=e.error&&T("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let n=e.token!==this.m;return this.m=e.token,T("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};let r=e=>{T("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(e=>r(e)),setTimeout(()=>{if(!this.appCheck){let e=this.V.getImmediate({optional:!0});e?r(e):T("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new P(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>
1e?(D("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new P(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function L(){return new TextEncoder}function B(e,t){return e<t?-1:+(e>t)}function z(e,t){let n=0;for(;n<e.length&&n<t.length;){let r=e.codePointAt(n),i=t.codePointAt(n);if(r!==i){if(r<128&&i<128)return B(r,i);{let s=L(),a=function(e,t){for(let n=0;n<e.length&&n<t.length;++n)if(e[n]!==t[n])return B(e[n],t[n]);return B(e.length,t.length)}(s.encode(U(e,n)),s.encode(U(t,n)));return 0!==a?a:B(r,i)}}n+=r>65535?2:1}return B(e.length,t.length)}function U(e,t){return e.codePointAt(t)>65535?e.substring(t,t+2):e.substring(t,t+1)}function q(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}class K{static now(){return K.fromMillis(Date.now())}static fromDate(e){return K.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*1e6);return new K(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new C(k.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new C(k.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?B(this.nanoseconds,e.nanoseconds):B(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(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class ${static fromTimestamp(e){return new $(e)}static min(){return new $(new K(0,0))}static max(){return new $(new K(0x3afff4417f,0x3b9ac9ff))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}let G="__name__";class j{constructor(e,t,n){void 0===t?t=0:t>e.length&&S(637,{offset:t,range:e.length}),void 0===n?n=e.length-t:n>e.length-t&&S(1746,{length:n,range:e.length-t}),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===j.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof j?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){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=j.compareSegments(e.get(r),t.get(r));if(0!==n)return n}return B(e.length,t.length)}static compareSegments(e,t){let n=j.isNumericId(e),r=j.isNumericId(t);return n&&!r?-1:!n&&r?1:n&&r?j.extractNumericId(e).compare(j.extractNumericId(t)):z(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return c.jz.fromString(e.substring(4,e.length-2))}}class Q extends j{construct(e,t,n){return new Q(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}
1toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let n of e){if(n.indexOf("//")>=0)throw new C(k.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>e.length>0))}return new Q(t)}static emptyPath(){return new Q([])}}let H=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class J extends j{construct(e,t,n){return new J(e,t,n)}static isValidIdentifier(e){return H.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),J.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===G}static keyField(){return new J([G])}static fromServerFormat(e){let t=[],n="",r=0,i=()=>{if(0===n.length)throw new C(k.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},s=!1;for(;r<e.length;){let t=e[r];if("\\"===t){if(r+1===e.length)throw new C(k.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new C(k.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new C(k.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new J(t)}static emptyPath(){return new J([])}}class W{constructor(e){this.path=e}static fromPath(e){return new W(Q.fromString(e))}static fromName(e){return new W(Q.fromString(e).popFirst(5))}static empty(){return new W(Q.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===Q.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Q.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new W(new Q(e.slice()))}}class X{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Y(e){return e.fields.find(e=>2===e.kind)}function Z(e){return e.fields.filter(e=>2!==e.kind)}X.UNKNOWN_ID=-1;class ee{constructor(e,t){this.fieldPath=e,this.kind=t}}class et{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new et(0,ei.min())}}function en(e,t){let n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1;return new ei($.fromTimestamp(1e9===r?new K(n+1,0):new K(n,r)),W.empty(),t)}function er(e){return new ei(e.readTime,e.key,-1)}class ei{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new ei($.min(),W.empty(),-1)}static max(){return new ei($.max(),W.empty(),-1)}}function es(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n||0!==(n=W.comparator(e.documentKey,t.documentKey))?n:B(e.largestBatchId,t.largestBatchId)}let ea="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class eo{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function el(e){if(e.code!==k.FAILED_PRECONDITION||e.message!==ea)throw e;T("LocalStore","Unexpectedly lost primary lease")}class eu{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&&S(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new eu((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)=>
1{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof eu?t:eu.resolve(t)}catch(e){return eu.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):eu.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):eu.reject(t)}static resolve(e){return new eu((t,n)=>{t(e)})}static reject(e){return new eu((t,n)=>{n(e)})}static waitFor(e){return new eu((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=eu.resolve(!1);for(let n of e)t=t.next(e=>e?eu.resolve(e):n());return t}static forEach(e,t){let n=[];return e.forEach((e,r)=>{n.push(t.call(this,e,r))}),this.waitFor(n)}static mapArray(e,t){return new eu((n,r)=>{let i=e.length,s=Array(i),a=0;for(let o=0;o<i;o++){let l=o;t(e[l]).next(e=>{s[l]=e,++a===i&&n(s)},e=>r(e))}})}static doWhile(e,t){return new eu((n,r)=>{let i=()=>{!0===e()?t().next(()=>{i()},r):n()};i()})}}let eh="SimpleDb";class ec{static open(e,t,n,r){try{return new ec(t,e.transaction(r,n))}catch(e){throw new eg(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.S=new A,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{t.error?this.S.reject(new eg(e,t.error)):this.S.resolve()},this.transaction.onerror=t=>{let n=eI(t.target.error);this.S.reject(new eg(e,n))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(T(eh,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}v(){let e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){return new ey(this.transaction.objectStore(e))}}class ed{static delete(e){return T(eh,"Removing database:",e),ew((0,h.mS)().indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!(0,h.zW)())return!1;if(ed.F())return!0;let e=(0,h.ZQ)(),t=ed.M(e),n=em(e);return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||0<t&&t<10||0<n&&n<4.5)}static F(){var e;return void 0!==m&&"YES"===(null==(e=m.__PRIVATE_env)?void 0:e.O)}static N(e,t){return e.store(t)}static M(e){let t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i);return Number(t?t[1].split("_").slice(0,2).join("."):"-1")}constructor(e,t,n){this.name=e,this.version=t,this.B=n,this.L=null,12.2===ed.M((0,h.ZQ)())&&E("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async k(e){return this.db||(T(eh,"Opening database:",this.name),this.db=await new Promise((t,n)=>{let r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{t(e.target.result)},r.onblocked=()=>{n(new eg(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=>{let r=t.target.error;"VersionError"===r.name?n(new C(k.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 C(k.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 eg(e,r))},r.onupgradeneeded=e=>{T(eh,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);let t=e.target.result;if(null!==this.L&&this.L!==e.oldVersion)throw Error(`refusing to open IndexedDB database due to potential corruption of the IndexedDB database data; this corruption could be caused by clicking the "clear site data" button in a web browser; try reloading the web page to re-initialize the IndexedDB database: lastClosedDbVersion=${this.L}, event.oldVersion=${e.oldVersion}, event.newVersion=${e.newVersion}, db.version=${t.version}`);this.B.q(t,r.transaction,e.oldVersion,this.version).next(()=>{T(eh,"Database upgrade to version "+this.version+" complete")}
1)}}),this.db.addEventListener("close",e=>{let t=e.target;this.L=t.version},{passive:!0})),this.$&&(this.db.onversionchange=e=>this.$(e)),this.db}U(e){this.$=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){let i="readonly"===t,s=0;for(;;){++s;try{this.db=await this.k(e);let t=ec.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.v(),e)).catch(e=>(t.abort(e),eu.reject(e))).toPromise();return s.catch(()=>{}),await t.D,s}catch(t){let e="FirebaseError"!==t.name&&s<3;if(T(eh,"Transaction failed with error:",t.message,"Retrying:",e),this.close(),!e)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function em(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}class ef{constructor(e){this.K=e,this.W=!1,this.G=null}get isDone(){return this.W}get j(){return this.G}set cursor(e){this.K=e}done(){this.W=!0}H(e){this.G=e}delete(){return ew(this.K.delete())}}class eg extends C{constructor(e,t){super(k.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function ep(e){return"IndexedDbTransactionError"===e.name}class ey{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(T(eh,"PUT",this.store.name,e,t),n=this.store.put(t,e)):(T(eh,"PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),ew(n)}add(e){return T(eh,"ADD",this.store.name,e,e),ew(this.store.add(e))}get(e){return ew(this.store.get(e)).next(t=>(void 0===t&&(t=null),T(eh,"GET",this.store.name,e,t),t))}delete(e){return T(eh,"DELETE",this.store.name,e),ew(this.store.delete(e))}count(){return T(eh,"COUNT",this.store.name),ew(this.store.count())}J(e,t){let n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){let e=r.getAll(n.range);return new eu((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),t=[];return this.Y(e,(e,n)=>{t.push(n)}).next(()=>t)}}Z(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new eu((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}})}X(e,t){T(eh,"DELETE ALL",this.store.name);let n=this.options(e,t);n.ee=!1;let r=this.cursor(n);return this.Y(r,(e,t,n)=>n.delete())}te(e,t){let n;t?n=e:(n={},t=e);let r=this.cursor(n);return this.Y(r,t)}ne(e){let t=this.cursor({});return new eu((n,r)=>{t.onerror=e=>{r(eI(e.target.error))},t.onsuccess=t=>{let r=t.target.result;r?e(r.primaryKey,r.value).next(e=>{e?r.continue():n()}):n()}})}Y(e,t){let n=[];return new eu((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{let i=e.target.result;if(!i)return void r();let s=new ef(i),a=t(i.primaryKey,i.value,s);if(a instanceof eu){let e=a.catch(e=>(s.done(),eu.reject(e)));n.push(e)}s.isDone?r():null===s.j?i.continue():i.continue(s.j)}}).next(()=>eu.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){let n=this.store.index(e.index);return e.ee?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function ew(e){return new eu((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{n(eI(e.target.error))}})}let ev=!1;function eI(e){let t=ed.M((0,h.ZQ)());if(t>=12.2&&t<13){let t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){let e=new C("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 ev||(ev=!0,setTimeout(()=>{throw e},0)),e}}return e}let eT="IndexBackfiller";class eE{constructor(e,t){this.asyncQueue=e,this.re=t,this.task=null}start(){this.ie(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}ie(e){T(eT,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{let e=await this.re.se();T(eT,`Documents written: ${e}`)}catch(e){ep(e)?T(eT,"Ignoring IndexedDB error during index backfill: ",e):await el(e)}await this.ie(6e4)})}}class ex{constructor(e,t){this.localStore=e,this.persistence=t}async se(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.oe(t,e))}oe(e,t){let n=new Set,r=t,i=!0;return eu.doWhile(()=>!0===i&&r>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>
1{if(null!==t&&!n.has(t))return T(eT,`Processing collection: ${t}`),this._e(e,t,r).next(e=>{r-=e,n.add(t)});i=!1})).next(()=>t-r)}_e(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next(n=>{let i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next(()=>this.ae(r,n)).next(n=>(T(eT,`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n))).next(()=>i.size)}))}ae(e,t){let n=e;return t.changes.forEach((e,t)=>{let r=er(t);es(r,n)>0&&(n=r)}),new ei(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class eb{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ue(e),this.ce=e=>t.writeSequenceNumber(e))}ue(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ce&&this.ce(e),e}}eb.le=-1;function eS(e){return 0===e&&1/e==-1/0}function e_(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t+="\x01\x01"),t=function(e,t){let n=t,r=e.length;for(let t=0;t<r;t++){let r=e.charAt(t);switch(r){case"\0":n+="\x01\x10";break;case"\x01":n+="\x01\x11";break;default:n+=r}}return n}(e.get(n),t);return t+"\x01\x01"}function eD(e){let t=e.length;if(D(t>=2,64408,{path:e}),2===t)return D("\x01"===e.charAt(0)&&"\x01"===e.charAt(1),56145,{path:e}),Q.emptyPath();let n=t-2,r=[],i="";for(let s=0;s<t;){let t=e.indexOf("\x01",s);switch((t<0||t>n)&&S(50515,{path:e}),e.charAt(t+1)){case"\x01":let a,o=e.substring(s,t);0===i.length?a=o:(i+=o,a=i,i=""),r.push(a);break;case"\x10":i+=e.substring(s,t),i+="\0";break;case"\x11":i+=e.substring(s,t+1);break;default:S(61167,{path:e})}s=t+2}return new Q(r)}let ek="remoteDocuments",eC="owner",eA="owner",eN="mutationQueues",eR="mutations",eO="batchId",eV="userMutationsIndex",eM=["userId","batchId"],eP={},eF="documentMutations",eL="remoteDocumentsV14",eB=["prefixPath","collectionGroup","readTime","documentId"],ez="documentKeyIndex",eU=["prefixPath","collectionGroup","documentId"],eq="collectionGroupIndex",eK=["collectionGroup","readTime","prefixPath","documentId"],e$="remoteDocumentGlobal",eG="remoteDocumentGlobalKey",ej="targets",eQ="queryTargetsIndex",eH=["canonicalId","targetId"],eJ="targetDocuments",eW=["targetId","path"],eX="documentTargetsIndex",eY=["path","targetId"],eZ="targetGlobalKey",e0="targetGlobal",e1="collectionParents",e2=["collectionId","parent"],e5="clientMetadata",e4="bundles",e6="namedQueries",e3="indexConfiguration",e8="collectionGroupIndex",e9="indexState",e7=["indexId","uid"],te="sequenceNumberIndex",tt=["uid","sequenceNumber"],tn="indexEntries",tr=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],ti="documentKeyIndex",ts=["indexId","uid","orderedDocumentKey"],ta="documentOverlays",to=["userId","collectionPath","documentId"],tl="collectionPathOverlayIndex",tu=["userId","collectionPath","largestBatchId"],th="collectionGroupOverlayIndex",tc=["userId","collectionGroup","largestBatchId"],td="globals",tm=[eN,eR,eF,ek,ej,eC,e0,eJ,e5,e$,e1,e4,e6],tf=[...tm,ta],tg=[eN,eR,eF,eL,ej,eC,e0,eJ,e5,e$,e1,e4,e6,ta],tp=[...tg,e3,e9,tn],ty=[...tp,td];class tw extends eo{constructor(e,t){super(),this.he=e,this.currentSequenceNumber=t}}function tv(e,t){return ed.N(e.he,t)}function tI(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function tT(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}class tE{constructor(e,t){this.comparator=e,this.root=t||tb.EMPTY}insert(e,t){return new tE(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,tb.BLACK,null,null))}remove(e){return new tE(this.comparator,this.root.remove(e,this.comparator).copy(null,null,tb.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let 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();){let 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(){let e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new tx(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new tx(this.root,e,this.comparator,!1)}getReverseIterator(){return new tx(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new tx(this.root,e,this.comparator,!0)}}class tx{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class tb{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:tb.RED,this.left=null!=r?r:tb.EMPTY,this.right=null!=i?i:tb.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new tb(null!=e?e:this.key,null!=t?t:this.value,
1null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this,i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp()}removeMin(){if(this.left.isEmpty())return tb.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)).fixUp()}remove(e,t){let n,r=this;if(0>t(e,r.key))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 tb.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=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}rotateLeft(){let e=this.copy(null,null,tb.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,tb.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){return Math.pow(2,this.check())<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw S(43730,{key:this.key,value:this.value});if(this.right.isRed())throw S(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw S(27949);return e+ +!this.isRed()}}tb.EMPTY=null,tb.RED=!0,tb.BLACK=!1,tb.EMPTY=new class{constructor(){this.size=0}get key(){throw S(57766)}get value(){throw S(16141)}get color(){throw S(16727)}get left(){throw S(29726)}get right(){throw S(36894)}copy(e,t,n,r,i){return this}insert(e,t,n){return new tb(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 tS{constructor(e){this.comparator=e,this.data=new tE(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){let n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){let 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){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new t_(this.data.getIterator())}getIteratorFrom(e){return new t_(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 tS)||this.size!==e.size)return!1;let t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new tS(this.comparator);return t.data=e,t}}
1class t_{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function tD(e){return e.hasNext()?e.getNext():void 0}class tk{constructor(e){this.fields=e,e.sort(J.comparator)}static empty(){return new tk([])}unionWith(e){let t=new tS(J.comparator);for(let e of this.fields)t=t.add(e);for(let n of e)t=t.add(n);return new tk(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return q(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class tC extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class tA{constructor(e){this.binaryString=e}static fromBase64String(e){return new tA(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new tC("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new tA(function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e))}[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 btoa(this.binaryString)}toUint8Array(){var e=this.binaryString;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return B(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}tA.EMPTY_BYTE_STRING=new tA("");let tN=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function tR(e){if(D(!!e,39018),"string"==typeof e){let t=0,n=tN.exec(e);if(D(!!n,46558,{timestamp:e}),n[1]){let e=n[1];t=Number(e=(e+"000000000").substr(0,9))}return{seconds:Math.floor(new Date(e).getTime()/1e3),nanos:t}}return{seconds:tO(e.seconds),nanos:tO(e.nanos)}}function tO(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function tV(e){return"string"==typeof e?tA.fromBase64String(e):tA.fromUint8Array(e)}let tM="server_timestamp",tP="__type__",tF="__previous_value__",tL="__local_write_time__";function tB(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[tP])?void 0:n.stringValue)===tM}function tz(e){let t=tR(e.mapValue.fields[tL].timestampValue);return new K(t.seconds,t.nanos)}let tU="(default)";class tq{constructor(e,t){this.projectId=e,this.database=t||tU}static empty(){return new tq("","")}get isDefaultDatabase(){return this.database===tU}isEqual(e){return e instanceof tq&&e.projectId===this.projectId&&e.database===this.database}}let tK="__type__",t$="__max__",tG={mapValue:{fields:{__type__:{stringValue:t$}}}},tj="__vector__",tQ="value",tH={nullValue:"NULL_VALUE"};function tJ(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?tB(e)?4:ne(e)?0x1fffffffffffff:t9(e)?10:11:S(28295,{value:e})}function tW(e,t){if(e===t)return!0;let n=tJ(e);if(n!==tJ(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return tz(e).isEqual(tz(t));case 3:if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let r=tR(e.timestampValue),i=tR(t.timestampValue);return r.seconds===i.seconds&&r.nanos===i.nanos;case 5:return e.stringValue===t.stringValue;case 6:return tV(e.bytesValue).isEqual(tV(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return tO(e.geoPointValue.latitude)===tO(t.geoPointValue.latitude)&&tO(e.geoPointValue.longitude)===tO(t.geoPointValue.longitude);case 2:if("integerValue"in e&&"integerValue"in t)return tO(e.integerValue)===tO(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let n=tO(e.doubleValue),r=tO(t.doubleValue);return n===r?eS(n)===eS(r):isNaN(n)&&isNaN(r)}return!1;case 9:return q(e.arrayValue.values||[],t.arrayValue.values||[],tW);case 10:case 11:let s=e.mapValue.fields||{},a=t.mapValue.fields||{};if(tI(s)!==tI(a))return!1;for(let e in s)if(s.hasOwnProperty(e)&&(void 0===a[e]||!tW(s[e],a[e])))return!1;return!0;default:return S(52216,{left:e})}}function tX(e,t){return void 0!==(e.values||[]).find(e=>tW(e,t))}function tY(e,t){if(e===t)return 0;let n=tJ(e),r=tJ(t);if(n!==r)return B(n,r);switch(n){case 0:case 0x1fffffffffffff:return 0;case 1:return B(e.booleanValue,t.booleanValue);case 2:let i=tO(e.integerValue||e.doubleValue),s=tO(t.integerValue||t.doubleValue);return i<s?-1:i>s?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return tZ(e.timestampValue,t.timestampValue);case 4:return tZ(tz(e),tz(t));case 5:return z(e.stringValue,t.stringValue);case 6:return function(e,t){let n=tV(e),r=tV(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){let n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){let t=B(n[e],r[e]);if(0!==t)return t}return B(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){let n=B(tO(e.latitude),tO(t.latitude));return 0!==n?n:B(tO(e.longitude),tO(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return t0(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,i,s;let a=e.fields||{},o=t.fields||{},l=null==(n=a[tQ])?void 0:n.arrayValue,u=null==(r=o[tQ])?void 0:r.arrayValue,h=B((null==(i=null==l?void 0:l.values)?void 0:i.length)||0,(null==(s=null==u?void 0:u.values)?void 0:s.length)||0);return 0!==h?h:t0(l,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===tG.mapValue&&t===tG.mapValue)return 0;if(e===tG.mapValue)return 1;if(t===tG.mapValue)return -1;let n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){let t=z(r[e],s[e]);if(0!==t)return t;let a=tY(n[r[e]],i[s[e]]);if(0!==a)return a}return B(r.length,s.length)}(e.mapValue,t.mapValue);default:throw S(23264,{Pe:n})}}function tZ(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return B(e,t);let n=tR(e),r=tR(t),i=B(n.seconds,r.seconds);return 0!==i?i:B(n.nanos,r.nanos)}function t0(e,t){let n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){let t=tY(n[e],r[e]);if(t)return t}return B(n.length,r.length)}function t1(e){var t,n;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){let t=tR(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?tV(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,W.fromName(t).toString()):"geoPointValue"in e?(n=e.geoPointValue,`geo(${n.latitude},${n.longitude})`):"arrayValue"in e?function(e){let t="[",n=!0;for(let r of e.values||[])n?n=!1:t+=",",t+=t1(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),n="{",r=!0;for(let i of t)r?r=!1:n+=",",n+=`${i}:${t1(e.fields[i])}`;return n+"}"}(e.mapValue):S(61005,{value:e})}function t2(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function t5(e){return!!e&&"integerValue"in e}function t4(e){return!!e&&"arrayValue"in e}function t6(e){return!!e&&"nullValue"in e}function t3(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function t8(e){return!!e&&"mapValue"in e}function t9(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[tK])?void 0:n.stringValue)===tj}function t7(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){let t={mapValue:{fields:{}}};return tT(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=t7(n)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=t7(e.arrayValue.values[n]);return t}return Object.assign({},e)}function ne(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===t$}let nt={mapValue:{fields:{[tK]:{stringValue:tj},[tQ]:{arrayValue:{}}}}};function nn(e,t){let n=tY(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function nr(e,t){let n=tY(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class ni{constructor(e){this.value=e}static empty(){return new ni({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(!t8(t=(t.mapValue.fields||{})[e.get(n)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=t7(t)}setAll(e){let t=J.emptyPath(),n={},r=[];e.forEach((e,i)=>{if(!t.isImmediateParentOf(i)){let e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=t7(e):r.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){let t=this.field(e.popLast());t8(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return tW(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)];t8(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}
1applyChanges(e,t,n){for(let r of(tT(t,(t,n)=>e[t]=n),n))delete e[r]}clone(){return new ni(t7(this.value))}}class ns{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new ns(e,0,$.min(),$.min(),$.min(),ni.empty(),0)}static newFoundDocument(e,t,n,r){return new ns(e,1,t,$.min(),n,r,0)}static newNoDocument(e,t){return new ns(e,2,t,$.min(),$.min(),ni.empty(),0)}static newUnknownDocument(e,t){return new ns(e,3,t,$.min(),$.min(),ni.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual($.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=ni.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ni.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=$.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 ns&&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 ns(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 na{constructor(e,t){this.position=e,this.inclusive=t}}function no(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){let s=t[i],a=e.position[i];if(r=s.field.isKeyField()?W.comparator(W.fromName(a.referenceValue),n.key):tY(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function nl(e,t){if(null===e)return null===t;if(null===t||e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!tW(e.position[n],t.position[n]))return!1;return!0}class nu{constructor(e,t="asc"){this.field=e,this.dir=t}}class nh{}class nc extends nh{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 nw(e,t,n):"array-contains"===t?new nE(e,n):"in"===t?new nx(e,n):"not-in"===t?new nb(e,n):"array-contains-any"===t?new nS(e,n):new nc(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new nv(e,n):new nI(e,n)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(tY(t,this.value)):null!==t&&tJ(this.value)===tJ(t)&&this.matchesComparison(tY(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 S(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class nd extends nh{constructor(e,t){super(),this.filters=e,this.op=t,this.Te=null}static create(e,t){return new nd(e,t)}matches(e){return nm(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.Te||(this.Te=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Te}getFilters(){return Object.assign([],this.filters)}}function nm(e){return"and"===e.op}function nf(e){return"or"===e.op}function ng(e){return np(e)&&nm(e)}function np(e){for(let t of e.filters)if(t instanceof nd)return!1;return!0}function ny(e,t){let n=e.filters.concat(t);return nd.create(n,e.op)}class nw extends nc{constructor(e,t,n){super(e,t,n),this.key=W.fromName(n.referenceValue)}matches(e){let t=W.comparator(e.key,this.key);return this.matchesComparison(t)}}class nv extends nc{constructor(e,t){super(e,"in",t),this.keys=nT("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class nI extends nc{constructor(e,t){super(e,"not-in",t),this.keys=nT("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function nT(e,t){var n;return((null==(n=t.arrayValue)?void 0:n.values)||[]).map(e=>W.fromName(e.referenceValue))}class nE extends nc{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return t4(t)&&tX(t.arrayValue,this.value)}}class nx extends nc{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&tX(this.value.arrayValue,t)}}class nb extends nc{constructor(e,t){super(e,"not-in",t)}matches(e){if(tX(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!tX(this.value.arrayValue,t)}}class nS extends nc{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!t4(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>tX(this.value.arrayValue,e))}}class n_{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.Ie=null}}function nD(e,t=null,n=[],r=[],i=null,s=null,a=null){return new n_(e,t,n,r,i,s,a)}function nk(e){if(null===e.Ie){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(e=>(function e(t){if(t instanceof nc)return t.field.canonicalString()+t.op.toString()+t1(t.value);if(ng(t))return t.filters.map(t=>e(t)).join(",");{let n=t.filters.map(t=>e(t)).join(",");return`${t.op}(${n})`}})(e)).join(","),t+="|ob:",t+=e.orderBy.map(e=>e.field.canonicalString()+e.dir).join(","),null==e.limit||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>t1(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>t1(e)).join(",")),e.Ie=t}return e.Ie}function nC(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++){var n,r;if(n=e.orderBy[i],r=t.orderBy[i],!(n.dir===r.dir&&n.field.isEqual(r.field)))return!1}if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!function e(t,n){return t instanceof nc?n instanceof nc&&t.op===n.op&&t.field.isEqual(n.field)&&tW(t.value,n.value):t instanceof nd?n instanceof nd&&t.op===n.op&&t.filters.length===n.filters.length&&t.filters.reduce((t,r,i)=>t&&e(r,n.filters[i]),!0):void S(19439)}(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!nl(e.startAt,t.startAt)&&nl(e.endAt,t.endAt)}function nA(e){return W.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function nN(e,t){return e.filters.filter(e=>e instanceof nc&&e.field.isEqual(t))}function nR(e,t,n){let r=tH,i=!0;for(let n of nN(e,t)){let e=tH,t=!0;switch(n.op){case"<":case"<=":var s;
1e="nullValue"in(s=n.value)?tH:"booleanValue"in s?{booleanValue:!1}:"integerValue"in s||"doubleValue"in s?{doubleValue:NaN}:"timestampValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in s?{stringValue:""}:"bytesValue"in s?{bytesValue:""}:"referenceValue"in s?t2(tq.empty(),W.empty()):"geoPointValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in s?{arrayValue:{}}:"mapValue"in s?t9(s)?nt:{mapValue:{}}:S(35942,{value:s});break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=tH}0>nn({value:r,inclusive:i},{value:e,inclusive:t})&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];0>nn({value:r,inclusive:i},{value:e,inclusive:n.inclusive})&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}function nO(e,t,n){let r=tG,i=!0;for(let n of nN(e,t)){let e=tG,t=!0;switch(n.op){case">=":case">":var s;e="nullValue"in(s=n.value)?{booleanValue:!1}:"booleanValue"in s?{doubleValue:NaN}:"integerValue"in s||"doubleValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in s?{stringValue:""}:"stringValue"in s?{bytesValue:""}:"bytesValue"in s?t2(tq.empty(),W.empty()):"referenceValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in s?{arrayValue:{}}:"arrayValue"in s?nt:"mapValue"in s?t9(s)?{mapValue:{}}:tG:S(61959,{value:s}),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=tG}nr({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];nr({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}class nV{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Ee=null,this.de=null,this.Ae=null,this.startAt,this.endAt}}function nM(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 nP(e){if(null===e.Ee){let t;e.Ee=[];let n=new Set;for(let t of e.explicitOrderBy)e.Ee.push(t),n.add(t.field.canonicalString());let r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(t=new tS(J.comparator),e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t).forEach(t=>{n.has(t.canonicalString())||t.isKeyField()||e.Ee.push(new nu(t,r))}),n.has(J.keyField().canonicalString())||e.Ee.push(new nu(J.keyField(),r))}return e.Ee}function nF(e){return e.de||(e.de=function(e,t){if("F"===e.limitType)return nD(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{let t="desc"===e.dir?"asc":"desc";return new nu(e.field,t)});let n=e.endAt?new na(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new na(e.startAt.position,e.startAt.inclusive):null;return nD(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(e,nP(e))),e.de}function nL(e,t,n){return new nV(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function nB(e,t){return nC(nF(e),nF(t))&&e.limitType===t.limitType}function nz(e){return`${nk(nF(e))}|lt:${e.limitType}`}function nU(e){var t;let n;return`Query(target=${n=(t=nF(e)).path.canonicalString(),null!==t.collectionGroup&&(n+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(n+=`, filters: [${t.filters.map(e=>(function e(t){return t instanceof nc?`${t.field.canonicalString()} ${t.op} ${t1(t.value)}`:t instanceof nd?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),null==t.limit||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(e=>t1(e)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(e=>t1(e)).join(",")),`Target(${n})`}; limitType=${e.limitType})`}function nq(e,t){return t.isFoundDocument()&&function(e,t){let n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):W.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(let n of nP(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(let n of e.filters)if(!n.matches(t))return!1;return!0}
1(e,t)&&(!e.startAt||!!function(e,t,n){let r=no(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,nP(e),t))&&(!e.endAt||!!function(e,t,n){let r=no(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,nP(e),t))}function nK(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function n$(e){return(t,n)=>{let r=!1;for(let i of nP(e)){let e=function(e,t,n){let r=e.field.isKeyField()?W.comparator(t.key,n.key):function(e,t,n){let r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?tY(r,i):S(42886)}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return -1*r;default:return S(19790,{direction:e.dir})}}(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}class nG{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n){for(let[t,r]of n)if(this.equalsFn(t,e))return r}}has(e){return void 0!==this.get(e)}set(e,t){let n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){let 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){tT(this.inner,(t,n)=>{for(let[t,r]of n)e(t,r)})}isEmpty(){var e=this.inner;for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}size(){return this.innerSize}}let nj=new tE(W.comparator),nQ=new tE(W.comparator);function nH(...e){let t=nQ;for(let n of e)t=t.insert(n.key,n);return t}function nJ(){return new nG(e=>e.toString(),(e,t)=>e.isEqual(t))}let nW=new tE(W.comparator),nX=new tS(W.comparator);function nY(...e){let t=nX;for(let n of e)t=t.add(n);return t}let nZ=new tS(B);class n0{constructor(){this._=void 0}}class n1 extends n0{}class n2 extends n0{constructor(e){super(),this.elements=e}}function n5(e,t){let n=n9(t);for(let t of e.elements)n.some(e=>tW(e,t))||n.push(t);return{arrayValue:{values:n}}}class n4 extends n0{constructor(e){super(),this.elements=e}}function n6(e,t){let n=n9(t);for(let t of e.elements)n=n.filter(e=>!tW(e,t));return{arrayValue:{values:n}}}class n3 extends n0{constructor(e,t){super(),this.serializer=e,this.Re=t}}function n8(e){return tO(e.integerValue||e.doubleValue)}function n9(e){return t4(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class n7{constructor(e,t){this.field=e,this.transform=t}}class re{constructor(e,t){this.version=e,this.transformResults=t}}class rt{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new rt}static exists(e){return new rt(void 0,e)}static updateTime(e){return new rt(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 rn(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class rr{}function ri(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new rd(e.key,rt.none()):new ro(e.key,e.data,rt.none());{let n=e.data,r=ni.empty(),i=new tS(J.comparator);for(let e of t.fields)if(!i.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),i=i.add(e)}return new rl(e.key,r,new tk(i.toArray()),rt.none())}}function rs(e,t,n,r){return e instanceof ro?function(e,t,n,r){if(!rn(e.precondition,t))return n;let i=e.value.clone(),s=rc(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof rl?function(e,t,n,r){if(!rn(e.precondition,t))return n;let i=rc(e.fieldTransforms,r,t),s=t.data;return(s.setAll(ru(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n)?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):rn(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}function ra(e,t){var n,r;return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||!(!n||!r)&&q(n,r,(e,t)=>{var n,r;return e.field.isEqual(t.field)&&(n=e.transform,r=t.transform,n instanceof n2&&r instanceof n2||n instanceof n4&&r instanceof n4?q(n.elements,r.elements,tW):n instanceof n3&&r instanceof n3?tW(n.Re,r.Re):n instanceof n1&&r instanceof n1)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class ro extends rr{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.prec
1ondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class rl extends rr{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function ru(e){let t=new Map;return e.fieldMask.fields.forEach(n=>{if(!n.isEmpty()){let r=e.data.field(n);t.set(n,r)}}),t}function rh(e,t,n){let r=new Map;D(e.length===n.length,32656,{Ve:n.length,me:e.length});for(let s=0;s<n.length;s++){var i;let a=e[s],o=a.transform,l=t.data.field(a.field);r.set(a.field,(i=n[s],o instanceof n2?n5(o,l):o instanceof n4?n6(o,l):i))}return r}function rc(e,t,n){let r=new Map;for(let i of e){let e=i.transform,s=n.data.field(i.field);r.set(i.field,e instanceof n1?function(e,t){let n={fields:{[tP]:{stringValue:tM},[tL]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&tB(t)&&(t=function e(t){let n=t.mapValue.fields[tF];return tB(n)?e(n):n}(t)),t&&(n.fields[tF]=t),{mapValue:n}}(t,s):e instanceof n2?n5(e,s):e instanceof n4?n6(e,s):function(e,t){let n=function(e,t){return e instanceof n3?t5(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}(e,t),r=n8(n)+n8(e.Re);return t5(n)&&t5(e.Re)?{integerValue:""+r}:function(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:eS(t)?"-0":t}}(e.serializer,r)}(e,s))}return r}class rd extends rr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class rm extends rr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class rf{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let r=this.mutations[t];r.key.isEqual(e.key)&&function(e,t,n){e instanceof ro?function(e,t,n){let r=e.value.clone(),i=rh(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof rl?function(e,t,n){if(!rn(e.precondition,t))return t.convertToUnknownDocument(n.version);let r=rh(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(ru(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}(r,e,n[t])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=rs(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=rs(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=nJ();return this.mutations.forEach(r=>{let i=e.get(r.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=ri(s,a=t.has(r.key)?null:a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument($.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),nY())}isEqual(e){return this.batchId===e.batchId&&q(this.mutations,e.mutations,(e,t)=>ra(e,t))&&q(this.baseMutations,e.baseMutations,(e,t)=>ra(e,t))}}class rg{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){D(e.mutations.length===n.length,58842,{fe:e.mutations.length,ge:n.length});let r=nW,i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new rg(e,t,n,r)}}class rp{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{
2      largestBatchId: ${this.largestBatchId},
3      mutation: ${this.mutation.toString()}
4    }`}}class ry{constructor(e,t){this.count=e,this.unchangedNames=t}}function rw(e){if(void 0===e)return E("GRPC error has no .code"),k.UNKNOWN;switch(e){case r.OK:return k.OK;case r.CANCELLED:return k.CANCELLED;case r.UNKNOWN:return k.UNKNOWN;case r.DEADLINE_EXCEEDED:return k.DEADLINE_EXCEEDED;case r.RESOURCE_EXHAUSTED:return k.RESOURCE_EXHAUSTED;case r.INTERNAL:return k.INTERNAL;case r.UNAVAILABLE:return k.UNAVAILABLE;case r.UNAUTHENTICATED:return k.UNAUTHENTICATED;case r.INVALID_ARGUMENT:return k.INVALID_ARGUMENT;case r.NOT_FOUND:return k.NOT_FOUND;case r.ALREADY_EXISTS:return k.ALREADY_EXISTS;case r.PERMISSION_DENIED:return k.PERMISSION_DENIED;case r.FAILED_PRECONDITION:return k.FAILED_PRECONDITION;case r.ABORTED:return k.ABORTED;case r.OUT_OF_RANGE:return k.OUT_OF_RANGE;
4case r.UNIMPLEMENTED:return k.UNIMPLEMENTED;case r.DATA_LOSS:return k.DATA_LOSS;default:return S(39323,{code:e})}}(i=r||(r={}))[i.OK=0]="OK",i[i.CANCELLED=1]="CANCELLED",i[i.UNKNOWN=2]="UNKNOWN",i[i.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",i[i.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",i[i.NOT_FOUND=5]="NOT_FOUND",i[i.ALREADY_EXISTS=6]="ALREADY_EXISTS",i[i.PERMISSION_DENIED=7]="PERMISSION_DENIED",i[i.UNAUTHENTICATED=16]="UNAUTHENTICATED",i[i.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",i[i.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",i[i.ABORTED=10]="ABORTED",i[i.OUT_OF_RANGE=11]="OUT_OF_RANGE",i[i.UNIMPLEMENTED=12]="UNIMPLEMENTED",i[i.INTERNAL=13]="INTERNAL",i[i.UNAVAILABLE=14]="UNAVAILABLE",i[i.DATA_LOSS=15]="DATA_LOSS";let rv=new c.jz([0xffffffff,0xffffffff],0);function rI(e){let t=L().encode(e),n=new c.VV;return n.update(t),new Uint8Array(n.digest())}function rT(e){let t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new c.jz([n,r],0),new c.jz([i,s],0)]}class rE{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new rx(`Invalid padding: ${t}`);if(n<0||e.length>0&&0===this.hashCount)throw new rx(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new rx(`Invalid padding when bitmap length is 0: ${t}`);this.pe=8*e.length-t,this.ye=c.jz.fromNumber(this.pe)}we(e,t,n){let r=e.add(t.multiply(c.jz.fromNumber(n)));return 1===r.compare(rv)&&(r=new c.jz([r.getBits(0),r.getBits(1)],0)),r.modulo(this.ye).toNumber()}Se(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.pe)return!1;let[t,n]=rT(rI(e));for(let e=0;e<this.hashCount;e++){let r=this.we(t,n,e);if(!this.Se(r))return!1}return!0}static create(e,t,n){let r=new rE(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);return n.forEach(e=>r.insert(e)),r}insert(e){if(0===this.pe)return;let[t,n]=rT(rI(e));for(let e=0;e<this.hashCount;e++){let r=this.we(t,n,e);this.be(r)}}be(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class rx extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class rb{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){let r=new Map;return r.set(e,rS.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new rb($.min(),r,new tE(B),nj,nY())}}class rS{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new rS(n,t,nY(),nY(),nY())}}class r_{constructor(e,t,n,r){this.De=e,this.removedTargetIds=t,this.key=n,this.ve=r}}class rD{constructor(e,t){this.targetId=e,this.Ce=t}}class rk{constructor(e,t,n=tA.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class rC{constructor(){this.Fe=0,this.Me=rR(),this.xe=tA.EMPTY_BYTE_STRING,this.Oe=!1,this.Ne=!0}get current(){return this.Oe}get resumeToken(){return this.xe}get Be(){return 0!==this.Fe}get Le(){return this.Ne}ke(e){e.approximateByteSize()>0&&(this.Ne=!0,this.xe=e)}qe(){let e=nY(),t=nY(),n=nY();return this.Me.forEach((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:S(38017,{changeType:i})}}),new rS(this.xe,this.Oe,e,t,n)}Qe(){this.Ne=!1,this.Me=rR()}$e(e,t){this.Ne=!0,this.Me=this.Me.insert(e,t)}Ue(e){this.Ne=!0,this.Me=this.Me.remove(e)}Ke(){this.Fe+=1}We(){this.Fe-=1,D(this.Fe>=0,3241,{Fe:this.Fe})}Ge(){this.Ne=!0,this.Oe=!0}}class rA{constructor(e){this.ze=e,this.je=new Map,this.He=nj,this.Je=rN(),this.Ye=rN(),this.Ze=new tE(B)}Xe(e){for(let t of e.De)e.ve&&e.ve.isFoundDocument()?this.et(t,e.ve):this.tt(t,e.key,e.ve);for(let t of e.removedTargetIds)this.tt(t,e.key,e.ve)}nt(e){this.forEachTarget(e,t=>{let n=this.rt(t);switch(e.state){case 0:this.it(t)&&n.ke(e.resumeToken);break;case 1:n.We(),n.Be||n.Qe(),n.ke(e.resumeToken);break;case 2:n.We(),n.Be||this.removeTarget(t);break;case 3:this.it(t)&&(n.Ge(),n.ke(e.resumeToken));break;case 4:this.it(t)&&(this.st(t),n.ke(e.resumeToken));break;default:S(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.je.forEach((e,n)=>{this.it(n)&&t(n)})}ot(e){let t=e.targetId,n=e.Ce.count,r=this._t(t);if(r){let i=r.target;if(nA(i))if(0===n){let e=new W(i.path);this.tt(t,e,ns.newNoDocument(e,$.min()))}else D(1===n,20013,{expectedCount:n});else{let r=this.ut(t);if(r!==n){let n=this.ct(e),i=n?this.lt(n,e,r):1;0!==i&&(this.st(t),this.Ze=this.Ze.insert(t,2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}ct(e){let t,n,r=e.Ce.unchangedNames;if(!r||!r.bits)return null;let{bits:{bitmap:i="",padding:s=0},hashCount:a=0}=r;try{t=tV(i).toUint8Array()}catch(e){if(e instanceof tC)return x("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{n=new rE(t,s,a)}catch(e){return x(e instanceof rx?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===n.pe?null:n}lt(e,t,n){return 2*(t.Ce.count!==n-this.Tt(e,t.targetId))}Tt(e,t){let n=this.ze.getRemoteKeysForTarget(t),r=0;
4return n.forEach(n=>{let i=this.ze.Pt(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;e.mightContain(s)||(this.tt(t,n,null),r++)}),r}It(e){let t=new Map;this.je.forEach((n,r)=>{let i=this._t(r);if(i){if(n.current&&nA(i.target)){let t=new W(i.target.path);this.Et(t).has(r)||this.dt(r,t)||this.tt(r,t,ns.newNoDocument(t,e))}n.Le&&(t.set(r,n.qe()),n.Qe())}});let n=nY();this.Ye.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{let t=this._t(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)}),r&&(n=n.add(e))}),this.He.forEach((t,n)=>n.setReadTime(e));let r=new rb(e,t,this.Ze,this.He,n);return this.He=nj,this.Je=rN(),this.Ye=rN(),this.Ze=new tE(B),r}et(e,t){if(!this.it(e))return;let n=2*!!this.dt(e,t.key);this.rt(e).$e(t.key,n),this.He=this.He.insert(t.key,t),this.Je=this.Je.insert(t.key,this.Et(t.key).add(e)),this.Ye=this.Ye.insert(t.key,this.At(t.key).add(e))}tt(e,t,n){if(!this.it(e))return;let r=this.rt(e);this.dt(e,t)?r.$e(t,1):r.Ue(t),this.Ye=this.Ye.insert(t,this.At(t).delete(e)),this.Ye=this.Ye.insert(t,this.At(t).add(e)),n&&(this.He=this.He.insert(t,n))}removeTarget(e){this.je.delete(e)}ut(e){let t=this.rt(e).qe();return this.ze.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ke(e){this.rt(e).Ke()}rt(e){let t=this.je.get(e);return t||(t=new rC,this.je.set(e,t)),t}At(e){let t=this.Ye.get(e);return t||(t=new tS(B),this.Ye=this.Ye.insert(e,t)),t}Et(e){let t=this.Je.get(e);return t||(t=new tS(B),this.Je=this.Je.insert(e,t)),t}it(e){let t=null!==this._t(e);return t||T("WatchChangeAggregator","Detected inactive target",e),t}_t(e){let t=this.je.get(e);return t&&t.Be?null:this.ze.Rt(e)}st(e){this.je.set(e,new rC),this.ze.getRemoteKeysForTarget(e).forEach(t=>{this.tt(e,t,null)})}dt(e,t){return this.ze.getRemoteKeysForTarget(e).has(t)}}function rN(){return new tE(W.comparator)}function rR(){return new tE(W.comparator)}let rO={asc:"ASCENDING",desc:"DESCENDING"},rV={"<":"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"},rM={and:"AND",or:"OR"};class rP{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function rF(e,t){return e.useProto3Json||null==t?t:{value:t}}function rL(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function rB(e){return D(!!e,49232),$.fromTimestamp(function(e){let t=tR(e);return new K(t.seconds,t.nanos)}(e))}function rz(e,t){return rU(e,t).canonicalString()}function rU(e,t){let n=new Q(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?n:n.child(t)}function rq(e){var t;let n=Q.fromString(e);return D((t=n).length>=4&&"projects"===t.get(0)&&"databases"===t.get(2),10190,{key:n.toString()}),n}function rK(e,t){return rz(e.databaseId,t.path)}function r$(e,t){let n=rq(t);if(n.get(1)!==e.databaseId.projectId)throw new C(k.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 C(k.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new W(rH(n))}function rG(e,t){return rz(e.databaseId,t)}function rj(e){let t=rq(e);return 4===t.length?Q.emptyPath():rH(t)}function rQ(e){return new Q(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function rH(e){return D(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function rJ(e,t,n){return{name:rK(e,t),fields:n.value.mapValue.fields}}function rW(e,t){var n;let r;if(t instanceof ro)r={update:rJ(e,t.key,t.value)};else if(t instanceof rd)r={delete:rK(e,t.key)};else if(t instanceof rl)r={update:rJ(e,t.key,t.data),updateMask:function(e){let t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};
4else{if(!(t instanceof rm))return S(16599,{ft:t.type});r={verify:rK(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let n=t.transform;if(n instanceof n1)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof n2)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof n4)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof n3)return{fieldPath:t.field.canonicalString(),increment:n.Re};throw S(20930,{transform:t.transform})})(0,e))),t.precondition.isNone||(r.currentDocument=void 0!==(n=t.precondition).updateTime?{updateTime:rL(e,n.updateTime.toTimestamp())}:void 0!==n.exists?{exists:n.exists}:S(27497)),r}function rX(e,t){var n;let r=t.currentDocument?void 0!==(n=t.currentDocument).updateTime?rt.updateTime(rB(n.updateTime)):void 0!==n.exists?rt.exists(n.exists):rt.none():rt.none(),i=t.updateTransforms?t.updateTransforms.map(t=>{let n;return n=null,"setToServerValue"in t?(D("REQUEST_TIME"===t.setToServerValue,16630,{proto:t}),n=new n1):"appendMissingElements"in t?n=new n2(t.appendMissingElements.values||[]):"removeAllFromArray"in t?n=new n4(t.removeAllFromArray.values||[]):"increment"in t?n=new n3(e,t.increment):S(16584,{proto:t}),new n7(J.fromServerFormat(t.fieldPath),n)}):[];if(t.update){t.update.name;let n=r$(e,t.update.name),s=new ni({mapValue:{fields:t.update.fields}});return t.updateMask?new rl(n,s,new tk((t.updateMask.fieldPaths||[]).map(e=>J.fromServerFormat(e))),r,i):new ro(n,s,r,i)}return t.delete?new rd(r$(e,t.delete),r):t.verify?new rm(r$(e,t.verify),r):S(1463,{proto:t})}function rY(e,t){return{documents:[rG(e,t.path)]}}function rZ(e,t){var n,r;let i,s={structuredQuery:{}},a=t.path;null!==t.collectionGroup?(i=a,s.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=a.popLast(),s.structuredQuery.from=[{collectionId:a.lastSegment()}]),s.parent=rG(e,i);let o=function(e){if(0!==e.length)return function e(t){return t instanceof nc?function(e){if("=="===e.op){if(t3(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NAN"}};if(t6(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(t3(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NOT_NAN"}};if(t6(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:r1(e.field),op:rV[e.op],value:e.value}}}(t):t instanceof nd?function(t){let n=t.getFilters().map(t=>e(t));return 1===n.length?n[0]:{compositeFilter:{op:rM[t.op],filters:n}}}(t):S(54877,{filter:t})}(nd.create(e,"and"))}(t.filters);o&&(s.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:r1(e.field),direction:rO[e.dir]}))}(t.orderBy);l&&(s.structuredQuery.orderBy=l);let u=rF(e,t.limit);return null!==u&&(s.structuredQuery.limit=u),t.startAt&&(s.structuredQuery.startAt={before:(n=t.startAt).inclusive,values:n.position}),t.endAt&&(s.structuredQuery.endAt={before:!(r=t.endAt).inclusive,values:r.position}),{gt:s,parent:i}}function r0(e){var t;let n,r=rj(e.parent),i=e.structuredQuery,s=i.from?i.from.length:0,a=null;if(s>0){D(1===s,65062);let e=i.from[0];e.allDescendants?a=e.collectionId:r=r.child(e.collectionId)}let o=[];i.where&&(o=function(e){let t=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=r2(e.unaryFilter.field);return nc.create(t,"==",{doubleValue:NaN});case"IS_NULL":let n=r2(e.unaryFilter.field);return nc.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let r=r2(e.unaryFilter.field);return nc.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=r2(e.unaryFilter.field);return nc.create(i,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return S(61313);default:return S(60726)}}(t):void 0!==t.fieldFilter?nc.create(r2(t.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";case"OPERATOR_UNSPECIFIED":return S(58110);default:return S(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?nd.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return S(1026)}}(t.compositeFilter.op)):S(30097,{filter:t})}(e);return t instanceof nd&&ng(t)?t.getFilters():[t]}(i.where));let l=[];i.orderBy&&(l=i.orderBy.map(e=>new nu(r2(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;i.limit&&(u=null==(n="object"==typeof(t=i.limit)?t.value:t)?null:n);let h=null;i.startAt&&(h=function(e){let t=!!e.before;return new na(e.values||[],t)}(i.startAt));let c=null;return i.endAt&&(c=function(e){let t=!e.before;return new na(e.values||[],t)}(i.endAt)),new nV(r,a,l,o,u,"F",h,c)}function r1(e){return{fieldPath:e.canonicalString()}}function r2(e){return J.fromServerFormat(e.fieldPath)}class r5{constructor(e,t,n,r,i=$.min(),s=$.min(),a=tA.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new r5(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new r5(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new r5(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new r5(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class r4{constructor(e){this.wt=e}}function r6(e,t){let n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:r3(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument()){var i;r.document={name:rK(i=e.wt,t.key),fields:t.data.value.mapValue.fields,updateTime:rL(i,t.version.toTimestamp()),createTime:rL(i,t.createTime.toTimestamp())}}else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:r8(t.version)};else{if(!t.isUnknownDocument())return S(57904,{document:t});r.unknownDocument={path:n.path.toArray(),version:r8(t.version)}}return r}function r3(e){let t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function r8(e){let t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function r9(e){let t=new K(e.seconds,e.nanoseconds);return $.fromTimestamp(t)}function r7(e,t){let n=(t.baseMutations||[]).map(t=>rX(e.wt,t));for(let e=0;e<t.mutations.length-1;++e){let n=t.mutations[e];e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform&&(n.updateTransforms=t.mutations[e+1].transform.fieldTransforms,t.mutations.splice(e+1,1),++e)}let r=t.mutations.map(t=>rX(e.wt,t)),i=K.fromMillis(t.localWriteTimeMs);return new rf(t.batchId,i,n,r)}function ie(e){let t=r9(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?r9(e.lastLimboFreeSnapshotVersion):$.min();return new r5(void 0!==e.query.documents?function(e){let t=e.documents.length;return D(1===t,1966,{count:t}),nF(new nV(rj(e.documents[0])))}(e.query):nF(r0(e.query)),e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,tA.fromBase64String(e.resumeToken))}function it(e,t){let n,r=r8(t.snapshotVersion),i=r8(t.lastLimboFreeSnapshotVersion);n=nA(t.target)?rY(e.wt,t.target):rZ(e.wt,t.target).gt;let s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:nk(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function ir(e){let t=r0({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?nL(t,t.limit,"L"):t}function ii(e,t){return new rp(t.largestBatchId,rX(e.wt,t.overlayMutation))}function is(e,t){let n=t.path.lastSegment();return[e,e_(t.path.popLast()),n]}function ia(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:r8(r.readTime),documentKey:e_(r.documentKey.path),largestBatchId:r.largestBatchId}}class io{getBundleMetadata(e,t){return tv(e,e4).get(t).next(e=>{if(e)return{id:e.bundleId,createTime:r9(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return tv(e,e4).put({bundleId:t.id,createTime:r8(rB(t.createTime)),version:t.version})}getNamedQuery(e,t){return tv(e,e6).get(t).next(e=>{if(e)return{name:e.name,query:ir(e.bundledQuery),readTime:r9(e.readTime)}})}saveNamedQuery(e,t){return tv(e,e6).put({name:t.name,readTime:r8(rB(t.readTime)),bundledQuery:t.bundledQuery})}}
4class il{constructor(e,t){this.serializer=e,this.userId=t}static St(e,t){return new il(e,t.uid||"")}getOverlay(e,t){return tv(e,ta).get(is(this.userId,t)).next(e=>e?ii(this.serializer,e):null)}getOverlays(e,t){let n=nJ();return eu.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){let r=[];return n.forEach((n,i)=>{let s=new rp(t,i);r.push(this.bt(e,s))}),eu.waitFor(r)}removeOverlaysForBatchId(e,t,n){let r=new Set;t.forEach(e=>r.add(e_(e.getCollectionPath())));let i=[];return r.forEach(t=>{let r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(tv(e,ta).X(tl,r))}),eu.waitFor(i)}getOverlaysForCollection(e,t,n){let r=nJ(),i=e_(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,1/0],!0);return tv(e,ta).J(tl,s).next(e=>{for(let t of e){let e=ii(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,r){let i,s=nJ(),a=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,1/0],!0);return tv(e,ta).te({index:th,range:a},(e,t,n)=>{let a=ii(this.serializer,t);s.size()<r||a.largestBatchId===i?(s.set(a.getKey(),a),i=a.largestBatchId):n.done()}).next(()=>s)}bt(e,t){return tv(e,ta).put(function(e,t,n){let[r,i,s]=is(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:rW(e.wt,n.mutation)}}(this.serializer,this.userId,t))}}class iu{Dt(e){return tv(e,td)}getSessionToken(e){return this.Dt(e).get("sessionToken").next(e=>{let t=null==e?void 0:e.value;return t?tA.fromUint8Array(t):tA.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.Dt(e).put({name:"sessionToken",value:t.toUint8Array()})}}class ih{constructor(){}vt(e,t){this.Ct(e,t),t.Ft()}Ct(e,t){if("nullValue"in e)this.Mt(t,5);else if("booleanValue"in e)this.Mt(t,10),t.xt(+!!e.booleanValue);else if("integerValue"in e)this.Mt(t,15),t.xt(tO(e.integerValue));else if("doubleValue"in e){let n=tO(e.doubleValue);isNaN(n)?this.Mt(t,13):(this.Mt(t,15),eS(n)?t.xt(0):t.xt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Mt(t,20),"string"==typeof n&&(n=tR(n)),t.Ot(`${n.seconds||""}`),t.xt(n.nanos||0)}else if("stringValue"in e)this.Nt(e.stringValue,t),this.Bt(t);else if("bytesValue"in e)this.Mt(t,30),t.Lt(tV(e.bytesValue)),this.Bt(t);else if("referenceValue"in e)this.kt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Mt(t,45),t.xt(n.latitude||0),t.xt(n.longitude||0)}else"mapValue"in e?ne(e)?this.Mt(t,Number.MAX_SAFE_INTEGER):t9(e)?this.qt(e.mapValue,t):(this.Qt(e.mapValue,t),this.Bt(t)):"arrayValue"in e?(this.$t(e.arrayValue,t),this.Bt(t)):S(19022,{Ut:e})}Nt(e,t){this.Mt(t,25),this.Kt(e,t)}Kt(e,t){t.Ot(e)}Qt(e,t){let n=e.fields||{};for(let e of(this.Mt(t,55),Object.keys(n)))this.Nt(e,t),this.Ct(n[e],t)}qt(e,t){var n,r;let i=e.fields||{};this.Mt(t,53);let s=(null==(r=null==(n=i[tQ].arrayValue)?void 0:n.values)?void 0:r.length)||0;this.Mt(t,15),t.xt(tO(s)),this.Nt(tQ,t),this.Ct(i[tQ],t)}$t(e,t){let n=e.values||[];for(let e of(this.Mt(t,50),n))this.Ct(e,t)}kt(e,t){this.Mt(t,37),W.fromName(e).path.forEach(e=>{this.Mt(t,60),this.Kt(e,t)})}Mt(e,t){e.xt(t)}Bt(e){e.xt(2)}}function ic(e){return Math.ceil((64-function(e){let t=0;for(let n=0;n<8;++n){let r=function(e){if(0===e)return 8;let t=0;return e>>4||(t+=4,e<<=4),e>>6||(t+=2,e<<=2),e>>7||(t+=1),t}(255&e[n]);if(t+=r,8!==r)break}return t}(e))/8)}ih.Wt=new ih;class id{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Gt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.zt(n.value),n=t.next();this.jt()}Ht(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.Jt(n.value),n=t.next();this.Yt()}Zt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.zt(e);else if(e<2048)this.zt(960|e>>>6),this.zt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.zt(480|e>>>12),this.zt(128|63&e>>>6),this.zt(128|63&e);else{let e=t.codePointAt(0);this.zt(240|e>>>18),this.zt(128|63&e>>>12),this.zt(128|63&e>>>6),this.zt(128|63&e)}}this.jt()}Xt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.Jt(e);else if(e<2048)this.Jt(960|e>>>6),this.Jt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Jt(480|e>>>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e);else{let e=t.codePointAt(0);this.Jt(240|e>>>18),this.Jt(128|63&e>>>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e)}}this.Yt()}en(e){let t=this.tn(e),n=ic(t);this.nn(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}rn(e){let t=this.tn(e),n=ic(t);this.nn(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}sn(){this._n(255),this._n(255)}an(){this.un(255),this.un(255)}reset(){this.position=0}seed(e){this.nn(e.length),this.buffer.set(e,this.position),this.position+=e.length}cn(){return this.buffer.slice(0,this.position)}tn(e){let t=function(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=!!(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=255*!!n;return t}zt(e){let t=255&e;0===t?(this._n(0),this._n(255)):255===t?(this._n(255),this._n(0)):this._n(t)}Jt(e){let t=255&e;0===t?(this.un(0),this.un(255)):255===t?(this.un(255),this.un(0)):this.un(e)}jt(){this._n(0),this._n(1)}Yt(){this.un(0),this.un(1)}_n(e){this.nn(1),this.buffer[this.position++]=e}un(e){this.nn(1),this.buffer[this.position++]=~e}nn(e){let t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);let r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class im{constructor(e){this.ln=e}Lt(e){this.ln.Gt(e)}Ot(e){this.ln.Zt(e)}xt(e){this.ln.en(e)}Ft(){this.ln.sn()}}class ig{constructor(e){this.ln=e}Lt(e){this.ln.Ht(e)}Ot(e){this.ln.Xt(e)}xt(e){this.ln.rn(e)}Ft(){this.ln.an()}}class ip{constructor(){this.ln=new id,this.hn=new im(this.ln),this.Pn=new ig(this.ln)}seed(e){this.ln.seed(e)}Tn(e){return 0===e?this.hn:this.Pn}cn(){return this.ln.cn()}reset(){this.ln.reset()}}class iy{constructor(e,t,n,r){this.In=e,this.En=t,this.dn=n,this.An=r}Rn(){let e=this.An.length,t=0===e||255===this.An[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.An,0),t!==e?n.set([0],this.An.length):++n[n.length-1],new iy(this.In,this.En,this.dn,n)}Vn(e,t,n){return{indexId:this.In,uid:e,arrayValue:iI(this.dn),directionalValue:iI(this.An),orderedDocumentKey:iI(t),documentKey:n.path.toArray()}}mn(e,t,n){let r=this.Vn(e,t,n);return[r.indexId,r.uid,r.arrayValue,r.directionalValue,r.orderedDocumentKey,r.documentKey]}}function iw(e,t){let n=e.In-t.In;
4return 0!==n||0!==(n=iv(e.dn,t.dn))||0!==(n=iv(e.An,t.An))?n:W.comparator(e.En,t.En)}function iv(e,t){for(let n=0;n<e.length&&n<t.length;++n){let r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}function iI(e){return(0,h.Ov)()?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}(e):e}function iT(e){return"string"!=typeof e?e:function(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(e)}class iE{constructor(e){for(let t of(this.fn=new tS((e,t)=>J.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.gn=e.orderBy,this.pn=[],e.filters))t.isInequality()?this.fn=this.fn.add(t):this.pn.push(t)}get yn(){return this.fn.size>1}wn(e){if(D(e.collectionGroup===this.collectionId,49279),this.yn)return!1;let t=Y(e);if(void 0!==t&&!this.Sn(t))return!1;let n=Z(e),r=new Set,i=0,s=0;for(;i<n.length&&this.Sn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(this.fn.size>0){let e=this.fn.getIterator().getNext();if(!r.has(e.field.canonicalString())){let t=n[i];if(!this.bn(e,t)||!this.Dn(this.gn[s++],t))return!1}++i}for(;i<n.length;++i){let e=n[i];if(s>=this.gn.length||!this.Dn(this.gn[s++],e))return!1}return!0}vn(){if(this.yn)return null;let e=new tS(J.comparator),t=[];for(let n of this.pn)if(!n.field.isKeyField())if("array-contains"===n.op||"array-contains-any"===n.op)t.push(new ee(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new ee(n.field,0))}for(let n of this.gn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new ee(n.field,+("asc"!==n.dir))));return new X(X.UNKNOWN_ID,this.collectionId,t,et.empty())}Sn(e){for(let t of this.pn)if(this.bn(t,e))return!0;return!1}bn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;let n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}Dn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function ix(e){return e instanceof nc}function ib(e){return e instanceof nd&&ng(e)}function iS(e){return ix(e)||ib(e)||function(e){if(e instanceof nd&&nf(e)){for(let t of e.getFilters())if(!ix(t)&&!ib(t))return!1;return!0}return!1}(e)}function i_(e,t){return D(e instanceof nc||e instanceof nd,38388),D(t instanceof nc||t instanceof nd,25473),ik(e instanceof nc?t instanceof nc?nd.create([e,t],"and"):iD(e,t):t instanceof nc?iD(t,e):function(e,t){if(D(e.filters.length>0&&t.filters.length>0,48005),nm(e)&&nm(t))return ny(e,t.getFilters());let n=nf(e)?e:t,r=nf(e)?t:e,i=n.filters.map(e=>i_(e,r));return nd.create(i,"or")}(e,t))}function iD(e,t){if(nm(t))return ny(t,e.getFilters());{let n=t.filters.map(t=>i_(e,t));return nd.create(n,"or")}}function ik(e){if(D(e instanceof nc||e instanceof nd,11850),e instanceof nc)return e;let t=e.getFilters();if(1===t.length)return ik(t[0]);if(np(e))return e;let n=t.map(e=>ik(e)),r=[];return n.forEach(t=>{t instanceof nc?r.push(t):t instanceof nd&&(t.op===e.op?r.push(...t.filters):r.push(t))}),1===r.length?r[0]:nd.create(r,e.op)}class iC{constructor(){this.Cn=new iA}addToCollectionParentIndex(e,t){return this.Cn.add(t),eu.resolve()}getCollectionParents(e,t){return eu.resolve(this.Cn.getEntries(t))}addFieldIndex(e,t){return eu.resolve()}deleteFieldIndex(e,t){return eu.resolve()}deleteAllFieldIndexes(e){return eu.resolve()}createTargetIndexes(e,t){return eu.resolve()}getDocumentsMatchingTarget(e,t){return eu.resolve(null)}getIndexType(e,t){return eu.resolve(0)}getFieldIndexes(e,t){return eu.resolve([])}getNextCollectionGroupToUpdate(e){return eu.resolve(null)}getMinOffset(e,t){return eu.resolve(ei.min())}getMinOffsetFromCollectionGroup(e,t){return eu.resolve(ei.min())}updateCollectionGroup(e,t,n){return eu.resolve()}updateIndexEntries(e,t){return eu.resolve()}}class iA{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new tS(Q.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new tS(Q.comparator)).toArray()}}let iN="IndexedDbIndexManager",iR=new Uint8Array(0);class iO{constructor(e,t){this.databaseId=t,this.Fn=new iA,this.Mn=new nG(e=>nk(e),(e,t)=>nC(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.Fn.has(t)){let n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Fn.add(t)});let i={collectionId:n,parent:e_(r)};return tv(e,e1).put(i)}return eu.resolve()}getCollectionParents(e,t){let n=[],r=IDBKeyRange.bound([t,""],[t+"\0",""],!1,!0);return tv(e,e1).J(r).next(e=>{for(let r of e){if(r.collectionId!==t)break;n.push(eD(r.parent))}return n})}addFieldIndex(e,t){let n=tv(e,e3),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;let i=n.add(r);if(t.indexState){let n=tv(e,e9);return i.next(e=>{n.put(ia(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let n=tv(e,e3),r=tv(e,e9),i=tv(e,tn);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){let t=tv(e,e3),n=tv(e,tn),r=tv(e,e9);return t.X().next(()=>n.X()).next(()=>r.X())}createTargetIndexes(e,t){return eu.forEach(this.xn(t),t=>this.getIndexType(e,t).next(n=>{if(0===n||1===n){let n=new iE(t).vn();if(null!=n)return this.addFieldIndex(e,n)}}))}getDocumentsMatchingTarget(e,t){let n=tv(e,tn),r=!0,i=new Map;return eu.forEach(this.xn(t),t=>this.On(e,t).next(e=>{r&&(r=!!e),i.set(t,e)})).next(()=>
4{if(r){let e=nY(),r=[];return eu.forEach(i,(i,s)=>{T(iN,`Using index id=${i.indexId}|cg=${i.collectionGroup}|f=${i.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")} to execute ${nk(t)}`);let a=function(e,t){let n=Y(t);if(void 0===n)return null;for(let t of nN(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),o=function(e,t){let n=new Map;for(let r of Z(t))for(let t of nN(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}(s,i),l=function(e,t){let n=[],r=!0;for(let i of Z(t)){let t=0===i.kind?nR(e,i.fieldPath,e.startAt):nO(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new na(n,r)}(s,i),u=function(e,t){let n=[],r=!0;for(let i of Z(t)){let t=0===i.kind?nO(e,i.fieldPath,e.endAt):nR(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new na(n,r)}(s,i),h=this.Nn(i,s,l),c=this.Nn(i,s,u),d=this.Bn(i,s,o),m=this.Ln(i.indexId,a,h,l.inclusive,c,u.inclusive,d);return eu.forEach(m,i=>n.Z(i,t.limit).next(t=>{t.forEach(t=>{let n=W.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))})}))}).next(()=>r)}return eu.resolve(null)})}xn(e){let t=this.Mn.get(e);return t||(t=0===e.filters.length?[e]:(function(e){if(0===e.getFilters().length)return[];let t=function e(t){if(D(t instanceof nc||t instanceof nd,34018),t instanceof nc)return t;if(1===t.filters.length)return e(t.filters[0]);let n=t.filters.map(t=>e(t)),r=nd.create(n,t.op);return iS(r=ik(r))?r:(D(r instanceof nd,64498),D(nm(r),40251),D(r.filters.length>1,57927),r.filters.reduce((e,t)=>i_(e,t)))}(function e(t){var n,r;if(D(t instanceof nc||t instanceof nd,20012),t instanceof nc){if(t instanceof nx){let e=(null==(r=null==(n=t.value.arrayValue)?void 0:n.values)?void 0:r.map(e=>nc.create(t.field,"==",e)))||[];return nd.create(e,"or")}return t}let i=t.filters.map(t=>e(t));return nd.create(i,t.op)}(e));return D(iS(t),7391),ix(t)||ib(t)?[t]:t.getFilters()})(nd.create(e.filters,"and")).map(t=>nD(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)),this.Mn.set(e,t)),t}Ln(e,t,n,r,i,s,a){let o=(null!=t?t.length:1)*Math.max(n.length,i.length),l=o/(null!=t?t.length:1),u=[];for(let h=0;h<o;++h){let o=t?this.kn(t[h/l]):iR,c=this.qn(e,o,n[h%l],r),d=this.Qn(e,o,i[h%l],s),m=a.map(t=>this.qn(e,o,t,!0));u.push(...this.createRange(c,d,m))}return u}qn(e,t,n,r){let i=new iy(e,W.empty(),t,n);return r?i:i.Rn()}Qn(e,t,n,r){let i=new iy(e,W.empty(),t,n);return r?i.Rn():i}On(e,t){let n=new iE(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{let t=null;for(let r of e)n.wn(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let n=2,r=this.xn(t);return eu.forEach(r,t=>this.On(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new tS(J.comparator),n=!1;for(let r of e.filters)for(let e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(let n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+ +!!n}(t)&&(n=1):n=0})).next(()=>null!==t.limit&&r.length>1&&2===n?1:n)}$n(e,t){let n=new ip;for(let r of Z(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;let i=n.Tn(r.kind);ih.Wt.vt(e,i)}return n.cn()}kn(e){let t=new ip;return ih.Wt.vt(e,t.Tn(0)),t.cn()}Un(e,t){let n=new ip;return ih.Wt.vt(t2(this.databaseId,t),n.Tn(function(e){let t=Z(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.cn()}Bn(e,t,n){if(null===n)return[];let r=[];r.push(new ip);let i=0;for(let s of Z(e)){let e=n[i++];for(let n of r)if(this.Kn(t,s.fieldPath)&&t4(e))r=this.Wn(r,s,e);else{let t=n.Tn(s.kind);ih.Wt.vt(e,t)}}return this.Gn(r)}Nn(e,t,n){return this.Bn(e,t,n.position)}Gn(e){let t=[];for(let n=0;n<e.length;++n)t[n]=e[n].cn();return t}Wn(e,t,n){let r=[...e],i=[];for(let e of n.arrayValue.values||[])for(let n of r){let r=new ip;r.seed(n.cn()),ih.Wt.vt(e,r.Tn(t.kind)),i.push(r)}return i}Kn(e,t){return!!e.filters.find(e=>e instanceof nc&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let n=tv(e,e3),r=tv(e,e9);return(t?n.J(e8,IDBKeyRange.bound(t,t)):n.J()).next(e=>{let t=[];return eu.forEach(e,e=>r.get([e.indexId,this.uid]).next(n=>{t.push(function(e,t){let n=t?new et(t.sequenceNumber,new ei(r9(t.readTime),new W(eD(t.documentKey)),t.largestBatchId)):et.empty(),r=e.fields.map(([e,t])=>new ee(J.fromServerFormat(e),t));return new X(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)=>
4{let n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:B(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){let r=tv(e,e3),i=tv(e,e9);return this.zn(e).next(e=>r.J(e8,IDBKeyRange.bound(t,t)).next(t=>eu.forEach(t,t=>i.put(ia(t.indexId,this.uid,e,n)))))}updateIndexEntries(e,t){let n=new Map;return eu.forEach(t,(t,r)=>{let i=n.get(t.collectionGroup);return(i?eu.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(n.set(t.collectionGroup,i),eu.forEach(i,n=>this.jn(e,t,n).next(t=>{let i=this.Hn(r,n);return t.isEqual(i)?eu.resolve():this.Jn(e,r,n,t,i)}))))})}Yn(e,t,n,r){return tv(e,tn).put(r.Vn(this.uid,this.Un(n,t.key),t.key))}Zn(e,t,n,r){return tv(e,tn).delete(r.mn(this.uid,this.Un(n,t.key),t.key))}jn(e,t,n){let r=tv(e,tn),i=new tS(iw);return r.te({index:ti,range:IDBKeyRange.only([n.indexId,this.uid,iI(this.Un(n,t))])},(e,r)=>{i=i.add(new iy(n.indexId,t,iT(r.arrayValue),iT(r.directionalValue)))}).next(()=>i)}Hn(e,t){let n=new tS(iw),r=this.$n(t,e);if(null==r)return n;let i=Y(t);if(null!=i){let s=e.data.field(i.fieldPath);if(t4(s))for(let i of s.arrayValue.values||[])n=n.add(new iy(t.indexId,e.key,this.kn(i),r))}else n=n.add(new iy(t.indexId,e.key,iR,r));return n}Jn(e,t,n,r,i){T(iN,"Updating index entries for document '%s'",t.key);let s=[];return function(e,t,n,r,i){let s=e.getIterator(),a=t.getIterator(),o=tD(s),l=tD(a);for(;o||l;){let e=!1,t=!1;if(o&&l){let r=n(o,l);r<0?t=!0:r>0&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(l),l=tD(a)):t?(i(o),o=tD(s)):(o=tD(s),l=tD(a))}}(r,i,iw,r=>{s.push(this.Yn(e,t,n,r))},r=>{s.push(this.Zn(e,t,n,r))}),eu.waitFor(s)}zn(e){let t=1;return tv(e,e9).te({index:te,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)=>iw(e,t)).filter((e,t,n)=>!t||0!==iw(e,n[t-1]));let r=[];for(let i of(r.push(e),n)){let n=iw(i,e),s=iw(i,t);if(0===n)r[0]=e.Rn();else if(n>0&&s<0)r.push(i),r.push(i.Rn());else if(s>0)break}r.push(t);let i=[];for(let e=0;e<r.length;e+=2){if(this.Xn(r[e],r[e+1]))return[];let t=r[e].mn(this.uid,iR,W.empty()),n=r[e+1].mn(this.uid,iR,W.empty());i.push(IDBKeyRange.bound(t,n))}return i}Xn(e,t){return iw(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(iV)}getMinOffset(e,t){return eu.mapArray(this.xn(t),t=>this.On(e,t).next(e=>e||S(44426))).next(iV)}}function iV(e){D(0!==e.length,28825);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){let i=e[r].indexState.offset;0>es(i,t)&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new ei(t.readTime,t.documentKey,n)}let iM={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class iP{static withCacheSize(e){return new iP(e,iP.DEFAULT_COLLECTION_PERCENTILE,iP.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function iF(e,t,n){let r=e.store(eR),i=e.store(eF),s=[],a=IDBKeyRange.only(n.batchId),o=0,l=r.te({range:a},(e,t,n)=>(o++,n.delete()));s.push(l.next(()=>{D(1===o,47070,{batchId:n.batchId})}));let u=[];for(let e of n.mutations){var h,c;let r=(h=e.key.path,c=n.batchId,[t,e_(h),c]);s.push(i.delete(r)),u.push(e.key)}return eu.waitFor(s).next(()=>u)}function iL(e){let t;if(!e)return 0;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw S(14731);t=e.noDocument}return JSON.stringify(t).length}iP.DEFAULT_COLLECTION_PERCENTILE=10,iP.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,iP.DEFAULT=new iP(0x2800000,iP.DEFAULT_COLLECTION_PERCENTILE,iP.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),iP.DISABLED=new iP(-1,0,0);class iB{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.er={}}static St(e,t,n,r){return D(""!==e.uid,64387),new iB(e.isAuthenticated()?e.uid:"",t,n,r)}checkEmpty(e){let t=!0,n=IDBKeyRange.bound([this.userId,-1/0],[this.userId,1/0]);return iU(e).te({index:eV,range:n},(e,n,r)=>{t=!1,r.done()}).next(()=>t)}addMutationBatch(e,t,n,r){let i=tv(e,eF),s=iU(e);return s.add({}).next(a=>{D("number"==typeof a,49019);let o=new rf(a,t,n,r),l=function(e,t,n){let r=n.baseMutations.map(t=>rW(e.wt,t)),i=n.mutations.map(t=>rW(e.wt,t));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,o),u=[],h=new tS((e,t)=>B(e.canonicalString(),t.canonicalString()));for(let e of r){var c,d;let t=(c=this.userId,d=e.key.path,[c,e_(d),a]);h=h.add(e.key.path.popLast()),u.push(s.put(l)),u.push(i.put(t,eP))}return h.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.er[a]=o.keys()}),eu.waitFor(u).next(()=>o)})}lookupMutationBatch(e,t){return iU(e).get(t).next(e=>e?(D(e.userId===this.userId,48,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),r7(this.serializer,e)):null)}tr(e,t){return this.er[t]?eu.resolve(this.er[t]):this.lookupMutationBatch(e,t).next(e=>{if(e){let n=e.keys();return this.er[t]=n,n}return null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return iU(e).te({index:eV,range:r},(e,t,r)=>{t.userId===this.userId&&(D(t.batchId>=n,47524,{nr:n}),i=r7(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,1/0]),n=-1;return iU(e).te({index:eV,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,-1],[this.userId,1/0]);return iU(e).J(eV,t).next(e=>e.map(e=>r7(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){let n=[this.userId,e_(t.path)],r=IDBKeyRange.lowerBound(n),i=[];return tv(e,eF).te({range:r},(n,r,s)=>{let[a,o,l]=n,u=eD(o);if(a===this.userId&&t.path.isEqual(u))return iU(e).get(l).next(e=>{if(!e)throw S(61480,{rr:n,batchId:l});D(e.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:e.userId,batchId:l}),i.push(r7(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tS(B),r=[];return t.forEach(t=>{let i=[this.userId,e_(t.path)],s=IDBKeyRange.lowerBound(i),a=tv(e,eF).te({range:s},(e,r,i)=>{let[s,a,o]=e,l=eD(a);s===this.userId&&t.path.isEqual(l)?n=n.add(o):i.done()});r.push(a)}),eu.waitFor(r).next(()=>this.ir(e,n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=[this.userId,e_(n)],s=IDBKeyRange.lowerBound(i),a=new tS(B);return tv(e,eF).te({range:s},(e,t,i)=>{let[s,o,l]=e,u=eD(o);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(a=a.add(l)):i.done()}).next(()=>this.ir(e,a))}ir(e,t){let n=[],r=[];return t.forEach(t=>{r.push(iU(e).get(t).next(e=>{if(null===e)throw S(35274,{batchId:t});D(e.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),n.push(r7(this.serializer,e))}))}),eu.waitFor(r).next(()=>n)}removeMutationBatch(e,t){return iF(e.he,this.userId,t).next(n=>(e.addOnCommittedListener(()=>{this.sr(t.batchId)}),eu.forEach(n,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}sr(e){delete this.er[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>
4{if(!t)return eu.resolve();let n=IDBKeyRange.lowerBound([this.userId]),r=[];return tv(e,eF).te({range:n},(e,t,n)=>{if(e[0]===this.userId){let t=eD(e[1]);r.push(t)}else n.done()}).next(()=>{D(0===r.length,56720,{_r:r.map(e=>e.canonicalString())})})})}containsKey(e,t){return iz(e,this.userId,t)}ar(e){return tv(e,eN).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function iz(e,t,n){let r=[t,e_(n.path)],i=r[1],s=IDBKeyRange.lowerBound(r),a=!1;return tv(e,eF).te({range:s,ee:!0},(e,n,r)=>{let[s,o,l]=e;s===t&&o===i&&(a=!0),r.done()}).next(()=>a)}function iU(e){return tv(e,eR)}class iq{constructor(e){this.ur=e}next(){return this.ur+=2,this.ur}static cr(){return new iq(0)}static lr(){return new iq(-1)}}class iK{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.hr(e).next(t=>{let n=new iq(t.highestTargetId);return t.highestTargetId=n.next(),this.Pr(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.hr(e).next(e=>$.fromTimestamp(new K(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.hr(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(e,t,n){return this.hr(e).next(r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.Pr(e,r)))}addTargetData(e,t){return this.Tr(e,t).next(()=>this.hr(e).next(n=>(n.targetCount+=1,this.Ir(t,n),this.Pr(e,n))))}updateTargetData(e,t){return this.Tr(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>tv(e,ej).delete(t.targetId)).next(()=>this.hr(e)).next(t=>(D(t.targetCount>0,8065),t.targetCount-=1,this.Pr(e,t)))}removeTargets(e,t,n){let r=0,i=[];return tv(e,ej).te((s,a)=>{let o=ie(a);o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r++,i.push(this.removeTargetData(e,o)))}).next(()=>eu.waitFor(i)).next(()=>r)}forEachTarget(e,t){return tv(e,ej).te((e,n)=>{t(ie(n))})}hr(e){return tv(e,e0).get(eZ).next(e=>(D(null!==e,2888),e))}Pr(e,t){return tv(e,e0).put(eZ,t)}Tr(e,t){return tv(e,ej).put(it(this.serializer,t))}Ir(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.hr(e).next(e=>e.targetCount)}getTargetData(e,t){let n=nk(t),r=IDBKeyRange.bound([n,-1/0],[n,1/0]),i=null;return tv(e,ej).te({range:r,index:eQ},(e,n,r)=>{let s=ie(n);nC(t,s.target)&&(i=s,r.done())}).next(()=>i)}addMatchingKeys(e,t,n){let r=[],i=i$(e);return t.forEach(t=>{let s=e_(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))}),eu.waitFor(r)}removeMatchingKeys(e,t,n){let r=i$(e);return eu.forEach(t,t=>{let i=e_(t.path);return eu.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])})}removeMatchingKeysForTargetId(e,t){let n=i$(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){let n=IDBKeyRange.bound([t],[t+1],!1,!0),r=i$(e),i=nY();return r.te({range:n,ee:!0},(e,t,n)=>{let r=new W(eD(e[1]));i=i.add(r)}).next(()=>i)}containsKey(e,t){let n=e_(t.path),r=IDBKeyRange.bound([n],[n+"\0"],!1,!0),i=0;return i$(e).te({index:eX,ee:!0,range:r},([e,t],n,r)=>{0!==e&&(i++,r.done())}).next(()=>i>0)}Rt(e,t){return tv(e,ej).get(t).next(e=>e?ie(e):null)}}function i$(e){return tv(e,eJ)}let iG="LruGarbageCollector";function ij([e,t],[n,r]){let i=B(e,n);return 0===i?B(t,r):i}class iQ{constructor(e){this.Er=e,this.buffer=new tS(ij),this.dr=0}Ar(){return++this.dr}Rr(e){let t=[e,this.Ar()];if(this.buffer.size<this.Er)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>ij(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class iH{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Vr=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.mr(6e4)}stop(){this.Vr&&(this.Vr.cancel(),this.Vr=null)}get started(){return null!==this.Vr}mr(e){T(iG,`Garbage collection scheduled in ${e}ms`),this.Vr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Vr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){ep(e)?T(iG,"Ignoring IndexedDB error during garbage collection: ",e):await el(e)}await this.mr(3e5)})}}class iJ{constructor(e,t){this.gr=e,this.params=t}calculateTargetCount(e,t){return this.gr.pr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return eu.resolve(eb.le);let n=new iQ(t);return this.gr.forEachTarget(e,e=>n.Rr(e.sequenceNumber)).next(()=>this.gr.yr(e,e=>n.Rr(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.gr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.gr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(T("LruGarbageCollector","Garbage collection skipped; disabled"),eu.resolve(iM)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(T("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),iM):this.wr(e,t))}getCacheSize(e){return this.gr.getCacheSize(e)}wr(e,t){let n,r,i,s,a,o,l,h=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(T("LruGarbageCollector",`C
4apping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,s=Date.now(),this.nthSequenceNumber(e,r))).next(r=>(n=r,a=Date.now(),this.removeTargets(e,n,t))).next(t=>(i=t,o=Date.now(),this.removeOrphanedDocuments(e,n))).next(e=>(l=Date.now(),I()<=u.$b.DEBUG&&T("LruGarbageCollector",`LRU Garbage Collection
5	Counted targets in ${s-h}ms
6	Determined least recently used ${r} in `+(a-s)+"ms\n"+`	Removed ${i} targets in `+(o-a)+"ms\n"+`	Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-h}ms`),eu.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e})))}}class iW{constructor(e,t){this.db=e,this.garbageCollector=new iJ(this,t)}pr(e){let t=this.Sr(e);return this.db.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}Sr(e){let t=0;return this.yr(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}yr(e,t){return this.br(e,(e,n)=>t(n))}addReference(e,t,n){return iX(e,n)}removeReference(e,t,n){return iX(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return iX(e,t)}Dr(e,t){let n;return n=!1,tv(e,eN).ne(r=>iz(e,r,t).next(e=>(e&&(n=!0),eu.resolve(!e)))).next(()=>n)}removeOrphanedDocuments(e,t){let n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[],i=0;return this.br(e,(s,a)=>{if(a<=t){let t=this.Dr(e,s).next(t=>{if(!t)return i++,n.getEntry(e,s).next(()=>(n.removeEntry(s,$.min()),i$(e).delete([0,e_(s.path)])))});r.push(t)}}).next(()=>eu.waitFor(r)).next(()=>n.apply(e)).next(()=>i)}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return iX(e,t)}br(e,t){let n=i$(e),r,i=eb.le;return n.te({index:eX},([e,n],{path:s,sequenceNumber:a})=>
6{0===e?(i!==eb.le&&t(new W(eD(r)),i),i=a,r=s):i=eb.le}).next(()=>{i!==eb.le&&t(new W(eD(r)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function iX(e,t){var n;return i$(e).put((n=e.currentSequenceNumber,{targetId:0,path:e_(t.path),sequenceNumber:n}))}class iY{constructor(){this.changes=new nG(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,ns.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return void 0!==n?eu.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 iZ{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return tv(e,eL).put(n)}removeEntry(e,t,n){return tv(e,eL).delete(function(e,t){let n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],r3(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next(n=>(n.byteSize+=t,this.vr(e,n)))}getEntry(e,t){let n=ns.newInvalidDocument(t);return tv(e,eL).te({index:ez,range:IDBKeyRange.only(i1(t))},(e,r)=>{n=this.Cr(t,r)}).next(()=>n)}Fr(e,t){let n={size:0,document:ns.newInvalidDocument(t)};return tv(e,eL).te({index:ez,range:IDBKeyRange.only(i1(t))},(e,r)=>{n={document:this.Cr(t,r),size:iL(r)}}).next(()=>n)}getEntries(e,t){let n=nj;return this.Mr(e,t,(e,t)=>{let r=this.Cr(e,t);n=n.insert(e,r)}).next(()=>n)}Or(e,t){let n=nj,r=new tE(W.comparator);return this.Mr(e,t,(e,t)=>{let i=this.Cr(e,t);n=n.insert(e,i),r=r.insert(e,iL(t))}).next(()=>({documents:n,Nr:r}))}Mr(e,t,n){if(t.isEmpty())return eu.resolve();let r=new tS(i5);t.forEach(e=>r=r.add(e));let i=IDBKeyRange.bound(i1(r.first()),i1(r.last())),s=r.getIterator(),a=s.getNext();return tv(e,eL).te({index:ez,range:i},(e,t,r)=>{let i=W.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&0>i5(a,i);)n(a,null),a=s.getNext();a&&a.isEqual(i)&&(n(a,t),a=s.hasNext()?s.getNext():null),a?r.H(i1(a)):r.done()}).next(()=>{for(;a;)n(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,t,n,r,i){let s=t.path,a=[s.popLast().toArray(),s.lastSegment(),r3(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return tv(e,eL).J(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let n=nj;for(let i of e){let e=this.Cr(W.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(nq(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n})}getAllFromCollectionGroup(e,t,n,r){let i=nj,s=i2(t,n),a=i2(t,ei.max());return tv(e,eL).te({index:eq,range:IDBKeyRange.bound(s,a,!0)},(e,t,n)=>{let s=this.Cr(W.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(i=i.insert(s.key,s)).size===r&&n.done()}).next(()=>i)}newChangeBuffer(e){return new i0(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return tv(e,e$).get(eG).next(e=>(D(!!e,20021),e))}vr(e,t){return tv(e,e$).put(eG,t)}Cr(e,t){if(t){let e=function(e,t){let n;if(t.document)n=function(e,t,n){let r=r$(e,t.name),i=rB(t.updateTime),s=t.createTime?rB(t.createTime):$.min(),a=new ni({mapValue:{fields:t.fields}}),o=ns.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}(e.wt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){let e=W.fromSegments(t.noDocument.path),r=r9(t.noDocument.readTime);n=ns.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return S(56709);{let e=W.fromSegments(t.unknownDocument.path),r=r9(t.unknownDocument.version);n=ns.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){let t=new K(e[0],e[1]);return $.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!(e.isNoDocument()&&e.version.isEqual($.min())))return e}return ns.newInvalidDocument(e)}}class i0 extends iY{constructor(e,t){super(),this.Br=e,this.trackRemovals=t,this.Lr=new nG(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){let t=[],n=0,r=new tS((e,t)=>B(e.canonicalString(),t.canonicalString()));
6return this.changes.forEach((i,s)=>{let a=this.Lr.get(i);if(t.push(this.Br.removeEntry(e,i,a.readTime)),s.isValidDocument()){let o=r6(this.Br.serializer,s);r=r.add(i.path.popLast());let l=iL(o);n+=l-a.size,t.push(this.Br.addEntry(e,i,o))}else if(n-=a.size,this.trackRemovals){let n=r6(this.Br.serializer,s.convertToNoDocument($.min()));t.push(this.Br.addEntry(e,i,n))}}),r.forEach(n=>{t.push(this.Br.indexManager.addToCollectionParentIndex(e,n))}),t.push(this.Br.updateMetadata(e,n)),eu.waitFor(t)}getFromCache(e,t){return this.Br.Fr(e,t).next(e=>(this.Lr.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Br.Or(e,t).next(({documents:e,Nr:t})=>(t.forEach((t,n)=>{this.Lr.set(t,{size:n,readTime:e.get(t).readTime})}),e))}}function i1(e){let t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function i2(e,t){let n=t.documentKey.path.toArray();return[e,r3(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function i5(e,t){let n=e.path.toArray(),r=t.path.toArray(),i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=B(n[e],r[e]))return i;return(i=B(n.length,r.length))||(i=B(n[n.length-2],r[r.length-2]))||B(n[n.length-1],r[r.length-1])}class i4{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class i6{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&&rs(n.mutation,e,tk.empty(),K.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,nY()).next(()=>t))}getLocalViewOfDocuments(e,t,n=nY()){let r=nJ();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=nH();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let n=nJ();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,nY()))}populateOverlays(e,t,n){let 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 i=nj,s=nJ(),a=nJ();return t.forEach((e,t)=>{let a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof rl)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),rs(a.mutation,t,a.mutation.getFieldMask(),K.now())):s.set(t.key,tk.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>{var n;return a.set(e,new i4(t,null!=(n=s.get(e))?n:null))}),a))}recalculateAndSaveOverlays(e,t){let n=nJ(),r=new tE((e,t)=>e-t),i=nY();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let i of e)i.keys().forEach(e=>{let s=t.get(e);if(null===s)return;let a=n.get(e)||tk.empty();a=i.applyToLocalView(s,a),n.set(e,a);let o=(r.get(i.batchId)||nY()).add(e);r=r.insert(i.batchId,o)})}).next(()=>{let s=[],a=r.getReverseIterator();for(;a.hasNext();){let r=a.getNext(),o=r.key,l=r.value,u=nJ();l.forEach(e=>{if(!i.has(e)){let r=ri(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}}),s.push(this.documentOverlayCache.saveOverlays(e,o,u))}return eu.waitFor(s)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,n,r){return W.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):null!==t.collectionGroup?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next(i=>{let s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):eu.resolve(nJ()),a=-1,o=i;return s.next(t=>eu.forEach(t,(t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?eu.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,i)).next(()=>this.computeViews(e,o,t,nY())).next(e=>{let t;return{batchId:a,changes:(t=nQ,e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t)}}))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new W(t)).next(e=>{let t=nH();
vendor: 4,134 bytes, line 6
6return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){let i=t.collectionGroup,s=nH();return this.indexManager.getCollectionParents(e,i).next(a=>eu.forEach(a,a=>{let o=new nV(a.child(i),null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next(e=>{e.forEach((e,t)=>{s=s.insert(e,t)})})}).next(()=>s))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r))).next(e=>{i.forEach((t,n)=>{let r=n.getKey();null===e.get(r)&&(e=e.insert(r,ns.newInvalidDocument(r)))});let n=nH();return e.forEach((e,r)=>{let s=i.get(e);void 0!==s&&rs(s.mutation,r,tk.empty(),K.now()),nq(t,r)&&(n=n.insert(e,r))}),n})}}class i3{constructor(e){this.serializer=e,this.kr=new Map,this.qr=new Map}getBundleMetadata(e,t){return eu.resolve(this.kr.get(t))}saveBundleMetadata(e,t){return this.kr.set(t.id,{id:t.id,version:t.version,createTime:rB(t.createTime)}),eu.resolve()}getNamedQuery(e,t){return eu.resolve(this.qr.get(t))}saveNamedQuery(e,t){return this.qr.set(t.name,{name:t.name,query:ir(t.bundledQuery),readTime:rB(t.readTime)}),eu.resolve()}}class i8{constructor(){this.overlays=new tE(W.comparator),this.Qr=new Map}getOverlay(e,t){return eu.resolve(this.overlays.get(t))}getOverlays(e,t){let n=nJ();return eu.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.bt(e,t,r)}),eu.resolve()}removeOverlaysForBatchId(e,t,n){let r=this.Qr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Qr.delete(n)),eu.resolve()}getOverlaysForCollection(e,t,n){let r=nJ(),i=t.length+1,s=new W(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){let e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return eu.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new tE((e,t)=>e-t),s=this.overlays.getIterator();for(;s.hasNext();){let e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=nJ(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=nJ(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return eu.resolve(a)}bt(e,t,n){let r=this.overlays.get(n.key);if(null!==r){let e=this.Qr.get(r.largestBatchId).delete(n.key);this.Qr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new rp(t,n));let i=this.Qr.get(t);void 0===i&&(i=nY(),this.Qr.set(t,i)),this.Qr.set(t,i.add(n.key))}}class i9{constructor(){this.sessionToken=tA.EMPTY_BYTE_STRING}getSessionToken(e){return eu.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,eu.resolve()}}class i7{constructor(){this.$r=new tS(se.Ur),this.Kr=new tS(se.Wr)}isEmpty(){return this.$r.isEmpty()}addReference(e,t){let n=new se(e,t);this.$r=this.$r.add(n),this.Kr=this.Kr.add(n)}Gr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.zr(new se(e,t))}jr(e,t){e.forEach(e=>this.removeReference(e,t))}Hr(e){let t=new W(new Q([])),n=new se(t,e),r=new se(t,e+1),i=[];return this.Kr.forEachInRange([n,r],e=>{this.zr(e),i.push(e.key)}),i}Jr(){this.$r.forEach(e=>this.zr(e))}zr(e){this.$r=this.$r.delete(e),this.Kr=this.Kr.delete(e)}Yr(e){let t=new W(new Q([])),n=new se(t,e),r=new se(t,e+1),i=nY();return this.Kr.forEachInRange([n,r],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new se(e,0),n=this.$r.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class se{constructor(e,t){this.key=e,this.Zr=t}static Ur(e,t){return W.comparator(e.key,t.key)||B(e.Zr,t.Zr)}static Wr(e,t){return B(e.Zr,t.Zr)||W.comparator(e.key,t.key)}}class st{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.nr=1,this.Xr=new tS(se.Ur)}checkEmpty(e){return eu.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){let i=this.nr;
6this.nr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new rf(i,t,n,r);for(let t of(this.mutationQueue.push(s),r))this.Xr=this.Xr.add(new se(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return eu.resolve(s)}lookupMutationBatch(e,t){return eu.resolve(this.ei(t))}getNextMutationBatchAfterBatchId(e,t){let n=this.ti(t+1),r=n<0?0:n;return eu.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return eu.resolve(0===this.mutationQueue.length?-1:this.nr-1)}getAllMutationBatches(e){return eu.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new se(t,0),r=new se(t,1/0),i=[];return this.Xr.forEachInRange([n,r],e=>{let t=this.ei(e.Zr);i.push(t)}),eu.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tS(B);return t.forEach(e=>{let t=new se(e,0),r=new se(e,1/0);this.Xr.forEachInRange([t,r],e=>{n=n.add(e.Zr)})}),eu.resolve(this.ni(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=n;W.isDocumentKey(i)||(i=i.child(""));let s=new se(new W(i),0),a=new tS(B);return this.Xr.forEachWhile(e=>{let t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.Zr)),!0)},s),eu.resolve(this.ni(a))}ni(e){let t=[];return e.forEach(e=>{let n=this.ei(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){D(0===this.ri(t.batchId,"removed"),55003),this.mutationQueue.shift();let n=this.Xr;return eu.forEach(t.mutations,r=>{let i=new se(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)}).next(()=>{this.Xr=n})}sr(e){}containsKey(e,t){let n=new se(t,0),r=this.Xr.firstAfterOrEqual(n);return eu.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,eu.resolve()}ri(e,t){return this.ti(e)}ti(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}ei(e){let t=this.ti(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class sn{constructor(e){this.ii=e,this.docs=new tE(W.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.ii(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let n=this.docs.get(t);return eu.resolve(n?n.document.mutableCopy():ns.newInvalidDocument(t))}getEntries(e,t){let n=nj;return t.forEach(e=>{let t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():ns.newInvalidDocument(e))}),eu.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=nj,s=t.path,a=new W(s.child("__id-9223372036854775808__")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){let{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||0>=es(er(a),n)||(r.has(a.key)||nq(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return eu.resolve(i)}getAllFromCollectionGroup(e,t,n,r){S(9500)}si(e,t){return eu.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new sr(this)}getSize(e){return eu.resolve(this.size)}}class sr extends iY{constructor(e){super(),this.Br=e}applyChanges(e){let t=[];
vendor: 4,468 bytes, line 6
6return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.Br.addEntry(e,r)):this.Br.removeEntry(n)}),eu.waitFor(t)}getFromCache(e,t){return this.Br.getEntry(e,t)}getAllFromCache(e,t){return this.Br.getEntries(e,t)}}class si{constructor(e){this.persistence=e,this.oi=new nG(e=>nk(e),nC),this.lastRemoteSnapshotVersion=$.min(),this.highestTargetId=0,this._i=0,this.ai=new i7,this.targetCount=0,this.ui=iq.cr()}forEachTarget(e,t){return this.oi.forEach((e,n)=>t(n)),eu.resolve()}getLastRemoteSnapshotVersion(e){return eu.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return eu.resolve(this._i)}allocateTargetId(e){return this.highestTargetId=this.ui.next(),eu.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this._i&&(this._i=t),eu.resolve()}Tr(e){this.oi.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.ui=new iq(t),this.highestTargetId=t),e.sequenceNumber>this._i&&(this._i=e.sequenceNumber)}addTargetData(e,t){return this.Tr(t),this.targetCount+=1,eu.resolve()}updateTargetData(e,t){return this.Tr(t),eu.resolve()}removeTargetData(e,t){return this.oi.delete(t.target),this.ai.Hr(t.targetId),this.targetCount-=1,eu.resolve()}removeTargets(e,t,n){let r=0,i=[];return this.oi.forEach((s,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.oi.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)}),eu.waitFor(i).next(()=>r)}getTargetCount(e){return eu.resolve(this.targetCount)}getTargetData(e,t){let n=this.oi.get(t)||null;return eu.resolve(n)}addMatchingKeys(e,t,n){return this.ai.Gr(t,n),eu.resolve()}removeMatchingKeys(e,t,n){this.ai.jr(t,n);let r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(t=>{i.push(r.markPotentiallyOrphaned(e,t))}),eu.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.ai.Hr(t),eu.resolve()}getMatchingKeysForTargetId(e,t){let n=this.ai.Yr(t);return eu.resolve(n)}containsKey(e,t){return eu.resolve(this.ai.containsKey(t))}}class ss{constructor(e,t){this.ci={},this.overlays={},this.li=new eb(0),this.hi=!1,this.hi=!0,this.Pi=new i9,this.referenceDelegate=e(this),this.Ti=new si(this),this.indexManager=new iC,this.remoteDocumentCache=new sn(e=>this.referenceDelegate.Ii(e)),this.serializer=new r4(t),this.Ei=new i3(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.hi=!1,Promise.resolve()}get started(){return this.hi}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new i8,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.ci[e.toKey()];return n||(n=new st(t,this.referenceDelegate),this.ci[e.toKey()]=n),n}getGlobalsCache(){return this.Pi}getTargetCache(){return this.Ti}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ei}runTransaction(e,t,n){T("MemoryPersistence","Starting transaction:",e);let r=new sa(this.li.next());return this.referenceDelegate.di(),n(r).next(e=>this.referenceDelegate.Ai(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ri(e,t){return eu.or(Object.values(this.ci).map(n=>()=>n.containsKey(e,t)))}}class sa extends eo{constructor(e){super(),this.currentSequenceNumber=e}}class so{constructor(e){this.persistence=e,this.Vi=new i7,this.mi=null}static fi(e){return new so(e)}get gi(){if(this.mi)return this.mi;throw S(60996)}addReference(e,t,n){return this.Vi.addReference(n,t),this.gi.delete(n.toString()),eu.resolve()}removeReference(e,t,n){return this.Vi.removeReference(n,t),this.gi.add(n.toString()),eu.resolve()}markPotentiallyOrphaned(e,t){return this.gi.add(t.toString()),eu.resolve()}removeTarget(e,t){this.Vi.Hr(t.targetId).forEach(e=>this.gi.add(e.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.gi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}di(){this.mi=new Set}Ai(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return eu.forEach(this.gi,n=>{let r=W.fromPath(n);return this.pi(e,r).next(e=>{e||t.removeEntry(r,$.min())})}).next(()=>(this.mi=null,t.apply(e)))}updateLimboDocument(e,t){return this.pi(e,t).next(e=>{e?this.gi.delete(t.toString()):this.gi.add(t.toString())})}Ii(e){return 0}pi(e,t){return eu.or([()=>eu.resolve(this.Vi.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ri(e,t)])}}
6class sl{constructor(e){this.serializer=e}q(e,t,n,r){let i=new ec("createOrUpgrade",t);n<1&&r>=1&&(e.createObjectStore(eC),e.createObjectStore(eN,{keyPath:"userId"}),e.createObjectStore(eR,{keyPath:eO,autoIncrement:!0}).createIndex(eV,eM,{unique:!0}),e.createObjectStore(eF),su(e),e.createObjectStore(ek));let s=eu.resolve();return n<3&&r>=3&&(0!==n&&(e.deleteObjectStore(eJ),e.deleteObjectStore(ej),e.deleteObjectStore(e0),su(e)),s=s.next(()=>(function(e){let t=e.store(e0),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:$.min().toTimestamp(),targetCount:0};return t.put(eZ,n)})(i))),n<4&&r>=4&&(0!==n&&(s=s.next(()=>i.store(eR).J().next(t=>{e.deleteObjectStore(eR),e.createObjectStore(eR,{keyPath:eO,autoIncrement:!0}).createIndex(eV,eM,{unique:!0});let n=i.store(eR),r=t.map(e=>n.put(e));return eu.waitFor(r)}))),s=s.next(()=>{e.createObjectStore(e5,{keyPath:"clientId"})})),n<5&&r>=5&&(s=s.next(()=>this.wi(i))),n<6&&r>=6&&(s=s.next(()=>(e.createObjectStore(e$),this.Si(i)))),n<7&&r>=7&&(s=s.next(()=>this.bi(i))),n<8&&r>=8&&(s=s.next(()=>this.Di(e,i))),n<9&&r>=9&&(s=s.next(()=>{e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&r>=10&&(s=s.next(()=>this.Ci(i))),n<11&&r>=11&&(s=s.next(()=>{e.createObjectStore(e4,{keyPath:"bundleId"}),e.createObjectStore(e6,{keyPath:"name"})})),n<12&&r>=12&&(s=s.next(()=>{let t=e.createObjectStore(ta,{keyPath:to});t.createIndex(tl,tu,{unique:!1}),t.createIndex(th,tc,{unique:!1})})),n<13&&r>=13&&(s=s.next(()=>(function(e){let t=e.createObjectStore(eL,{keyPath:eB});t.createIndex(ez,eU),t.createIndex(eq,eK)})(e)).next(()=>this.Fi(e,i)).next(()=>e.deleteObjectStore(ek))),n<14&&r>=14&&(s=s.next(()=>this.Mi(e,i))),n<15&&r>=15&&(s=s.next(()=>{e.createObjectStore(e3,{keyPath:"indexId",autoIncrement:!0}).createIndex(e8,"collectionGroup",{unique:!1}),e.createObjectStore(e9,{keyPath:e7}).createIndex(te,tt,{unique:!1}),e.createObjectStore(tn,{keyPath:tr}).createIndex(ti,ts,{unique:!1})})),n<16&&r>=16&&(s=s.next(()=>{t.objectStore(e9).clear()}).next(()=>{t.objectStore(tn).clear()})),n<17&&r>=17&&(s=s.next(()=>{e.createObjectStore(td,{keyPath:"name"})})),n<18&&r>=18&&(0,h.Ov)()&&(s=s.next(()=>{t.objectStore(e9).clear()}).next(()=>{t.objectStore(tn).clear()})),s}Si(e){let t=0;return e.store(ek).te((e,n)=>{t+=iL(n)}).next(()=>{let n={byteSize:t};return e.store(e$).put(eG,n)})}wi(e){let t=e.store(eN),n=e.store(eR);return t.J().next(t=>eu.forEach(t,t=>{let r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.J(eV,r).next(n=>eu.forEach(n,n=>{D(n.userId===t.userId,18650,"Cannot process batch from unexpected user",{batchId:n.batchId});let r=r7(this.serializer,n);return iF(e,t.userId,r).next(()=>{})}))}))}bi(e){let t=e.store(eJ),n=e.store(ek);return e.store(e0).get(eZ).next(e=>{let r=[];return n.te((n,i)=>{let s=new Q(n),a=[0,e_(s)];r.push(t.get(a).next(n=>n?eu.resolve():t.put({targetId:0,path:e_(s),sequenceNumber:e.highestListenSequenceNumber})))}).next(()=>eu.waitFor(r))})}Di(e,t){e.createObjectStore(e1,{keyPath:e2});let n=t.store(e1),r=new iA,i=e=>{if(r.add(e)){let t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:e_(r)})}};return t.store(ek).te({ee:!0},(e,t)=>i(new Q(e).popLast())).next(()=>t.store(eF).te({ee:!0},([e,t,n],r)=>i(eD(t).popLast())))}Ci(e){let t=e.store(ej);return t.te((e,n)=>{let r=ie(n),i=it(this.serializer,r);return t.put(i)})}Fi(e,t){let n=t.store(ek),r=[];return n.te((e,n)=>{let i=t.store(eL),s=(n.document?new W(Q.fromString(n.document.name).popFirst(5)):n.noDocument?W.fromSegments(n.noDocument.path):n.unknownDocument?W.fromSegments(n.unknownDocument.path):S(36783)).path.toArray(),a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(a))}).next(()=>eu.waitFor(r))}Mi(e,t){let n=t.store(eR),r=new iZ(this.serializer),i=new ss(so.fi,this.serializer.wt);return n.J().next(e=>{let n=new Map;
6return e.forEach(e=>{var t;let r=null!=(t=n.get(e.userId))?t:nY();r7(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),eu.forEach(n,(e,n)=>{let s=new y(n),a=il.St(this.serializer,s),o=i.getIndexManager(s);return new i6(r,iB.St(s,this.serializer,o,i.referenceDelegate),a,o).recalculateAndSaveOverlaysForDocumentKeys(new tw(t,eb.le),e).next()})})}}function su(e){e.createObjectStore(eJ,{keyPath:eW}).createIndex(eX,eY,{unique:!0}),e.createObjectStore(ej,{keyPath:"targetId"}).createIndex(eQ,eH,{unique:!0}),e.createObjectStore(e0)}let sh="IndexedDbPersistence",sc="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 sd{constructor(e,t,n,r,i,s,a,o,l,u,h=18){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.xi=i,this.window=s,this.document=a,this.Oi=l,this.Ni=u,this.Bi=h,this.li=null,this.hi=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Li=null,this.inForeground=!1,this.ki=null,this.qi=null,this.Qi=-1/0,this.$i=e=>Promise.resolve(),!sd.C())throw new C(k.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new iW(this,r),this.Ui=t+"main",this.serializer=new r4(o),this.Ki=new ed(this.Ui,this.Bi,new sl(this.serializer)),this.Pi=new iu,this.Ti=new iK(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new iZ(this.serializer),this.Ei=new io,this.window&&this.window.localStorage?this.Wi=this.window.localStorage:(this.Wi=null,!1===u&&E(sh,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Gi().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new C(k.FAILED_PRECONDITION,sc);return this.zi(),this.ji(),this.Hi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Ti.getHighestSequenceNumber(e))}).then(e=>{this.li=new eb(e,this.Oi)}).then(()=>{this.hi=!0}).catch(e=>(this.Ki&&this.Ki.close(),Promise.reject(e)))}Ji(e){return this.$i=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.Ki.U(async t=>{null===t.newVersion&&await e()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.xi.enqueueAndForget(async()=>{this.started&&await this.Gi()}))}Gi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>tv(e,e5).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Yi(e).next(e=>{e||(this.isPrimary=!1,this.xi.enqueueRetryable(()=>this.$i(!1)))})}).next(()=>this.Zi(e)).next(t=>this.isPrimary&&!t?this.Xi(e).next(()=>!1):!!t&&this.es(e).next(()=>!0))).catch(e=>{if(ep(e))return T(sh,"Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return T(sh,"Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.xi.enqueueRetryable(()=>this.$i(e)),this.isPrimary=e})}Yi(e){return tv(e,eC).get(eA).next(e=>eu.resolve(this.ts(e)))}ns(e){return tv(e,e5).delete(this.clientId)}async rs(){if(this.isPrimary&&!this.ss(this.Qi,18e5)){this.Qi=Date.now();let e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let t=tv(e,e5);return t.J().next(e=>{let n=this._s(e,18e5),r=e.filter(e=>-1===n.indexOf(e));return eu.forEach(r,e=>t.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this.Wi)for(let t of e)this.Wi.removeItem(this.us(t.clientId))}}Hi(){this.qi=this.xi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Gi().then(()=>this.rs()).then(()=>this.Hi()))}ts(e){return!!e&&e.ownerId===this.clientId}Zi(e){return this.Ni?eu.resolve(!0):tv(e,eC).get(eA).next(t=>{if(null!==t&&this.ss(t.leaseTimestampMs,5e3)&&!this.cs(t.ownerId)){if(this.ts(t)&&this.networkEnabled)return!0;
6if(!this.ts(t)){if(!t.allowTabSynchronization)throw new C(k.FAILED_PRECONDITION,sc);return!1}}return!(!this.networkEnabled||!this.inForeground)||tv(e,e5).J().next(e=>void 0===this._s(e,5e3).find(e=>{if(this.clientId!==e.clientId){let 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&&T(sh,`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.hi=!1,this.ls(),this.qi&&(this.qi.cancel(),this.qi=null),this.hs(),this.Ps(),await this.Ki.runTransaction("shutdown","readwrite",[eC,e5],e=>{let t=new tw(e,eb.le);return this.Xi(t).next(()=>this.ns(t))}),this.Ki.close(),this.Ts()}_s(e,t){return e.filter(e=>this.ss(e.updateTimeMs,t)&&!this.cs(e.clientId))}Is(){return this.runTransaction("getActiveClients","readonly",e=>tv(e,e5).J().next(e=>this._s(e,18e5).map(e=>e.clientId)))}get started(){return this.hi}getGlobalsCache(){return this.Pi}getMutationQueue(e,t){return iB.St(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Ti}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new iO(e,this.serializer.wt.databaseId)}getDocumentOverlayCache(e){return il.St(this.serializer,e)}getBundleCache(){return this.Ei}runTransaction(e,t,n){var r;let i;T(sh,"Starting transaction:",e);let s=18===(r=this.Bi)||17===r?ty:16===r||15===r?tp:14===r||13===r?tg:12===r?tf:11===r?tm:void S(60245);return this.Ki.runTransaction(e,"readonly"===t?"readonly":"readwrite",s,r=>(i=new tw(r,this.li?this.li.next():eb.le),"readwrite-primary"===t?this.Yi(i).next(e=>!!e||this.Zi(i)).next(t=>{if(!t)throw E(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.xi.enqueueRetryable(()=>this.$i(!1)),new C(k.FAILED_PRECONDITION,ea);return n(i)}).next(e=>this.es(i).next(()=>e)):this.Es(i).next(()=>n(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Es(e){return tv(e,eC).get(eA).next(e=>{if(null!==e&&this.ss(e.leaseTimestampMs,5e3)&&!this.cs(e.ownerId)&&!this.ts(e)&&!(this.Ni||this.allowTabSynchronization&&e.allowTabSynchronization))throw new C(k.FAILED_PRECONDITION,sc)})}es(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return tv(e,eC).put(eA,t)}static C(){return ed.C()}Xi(e){let t=tv(e,eC);return t.get(eA).next(e=>this.ts(e)?(T(sh,"Releasing primary lease."),t.delete(eA)):eu.resolve())}ss(e,t){let n=Date.now();return!(e<n-t)&&(!(e>n)||(E(`Detected an update time that is in the future: ${e} > ${n}`),!1))}zi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ki=()=>{this.xi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Gi()))},this.document.addEventListener("visibilitychange",this.ki),this.inForeground="visible"===this.document.visibilityState)}hs(){this.ki&&(this.document.removeEventListener("visibilitychange",this.ki),this.ki=null)}ji(){var e;"function"==typeof(null==(e=this.window)?void 0:e.addEventListener)&&(this.Li=()=>{this.ls();let e=/(?:Version|Mobile)\/1[456]/;(0,h.nr)()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.xi.enterRestrictedMode(!0),this.xi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Li))}Ps(){this.Li&&(this.window.removeEventListener("pagehide",this.Li),this.Li=null)}cs(e){var t;try{let n=null!==(null==(t=this.Wi)?void 0:t.getItem(this.us(e)));return T(sh,`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return E(sh,"Failed to get zombied client id.",e),!1}}ls(){if(this.Wi)try{this.Wi.setItem(this.us(this.clientId),String(Date.now()))}catch(e){E("Failed to set zombie client id.",e)}}Ts(){if(this.Wi)try{this.Wi.removeItem(this.us(this.clientId))}catch(e){}}us(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function sm(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class sf{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.ds=n,this.As=r}static Rs(e,t){let n=nY(),r=nY();for(let e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new sf(e,t.fromCache,n,r)}}class sg{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class sp{constructor(){this.Vs=!1,this.fs=!1,this.gs=100,this.ps=(0,h.nr)()?8:em((0,h.ZQ)())>0?6:4}initialize(e,t){this.ys=e,this.indexManager=t,this.Vs=!0}getDocumentsMatchingQuery(e,t,n,r){let i={result:null};return this.ws(e,t).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.Ss(e,t,r,n).next(e=>{i.result=e})}).next(()=>{if(i.result)return;let n=new sg;return this.bs(e,t,n).next(r=>{if(i.result=r,this.fs)return this.Ds(e,t,n,r.size)})}).next(()=>i.result)}Ds(e,t,n,r){return n.documentReadCount<this.gs?(I()<=u.$b.DEBUG&&T("QueryEngine","SDK will not create cache indexes for query:",nU(t),"since it only creates cache indexes for collection contains","more than or equal to",this.gs,"documents"),eu.resolve()):(I()<=u.$b.DEBUG&&T("QueryEngine","Query:",nU(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.ps*r?(I()<=u.$b.DEBUG&&T("QueryEngine","The SDK decides to create cache indexes for query:",nU(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,nF(t))):eu.resolve())}ws(e,t){if(nM(t))return eu.resolve(null);let n=nF(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(n=nF(t=nL(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{let i=nY(...r);return this.ys.getDocuments(e,i).next(r=>this.indexManager.getMinOffset(e,n).next(n=>{let s=this.vs(t,r);return this.Cs(t,s,i,n.readTime)?this.ws(e,nL(t,null,"F")):this.Fs(e,s,t,n)}))})))}Ss(e,t,n,r){return nM(t)||r.isEqual($.min())?eu.resolve(null):this.ys.getDocuments(e,n).next(i=>{let s=this.vs(t,i);return this.Cs(t,s,n,r)?eu.resolve(null):(I()<=u.$b.DEBUG&&T("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),nU(t)),this.Fs(e,s,t,en(r,-1)).next(e=>e))})}vs(e,t){let n=new tS(n$(e));return t.forEach((t,r)=>{nq(e,r)&&(n=n.add(r))}),n}Cs(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;let i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}
6bs(e,t,n){return I()<=u.$b.DEBUG&&T("QueryEngine","Using full collection scan to execute query:",nU(t)),this.ys.getDocumentsMatchingQuery(e,t,ei.min(),n)}Fs(e,t,n,r){return this.ys.getDocumentsMatchingQuery(e,n,r).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let sy="LocalStore";class sw{constructor(e,t,n,r){this.persistence=e,this.Ms=t,this.serializer=r,this.xs=new tE(B),this.Os=new nG(e=>nk(e),nC),this.Ns=new Map,this.Bs=e.getRemoteDocumentCache(),this.Ti=e.getTargetCache(),this.Ei=e.getBundleCache(),this.Ls(n)}Ls(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new i6(this.Bs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Bs.setIndexManager(this.indexManager),this.Ms.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.xs))}}async function sv(e,t){return await e.persistence.runTransaction("Handle user change","readonly",n=>{let r;return e.mutationQueue.getAllMutationBatches(n).next(i=>(r=i,e.Ls(t),e.mutationQueue.getAllMutationBatches(n))).next(t=>{let i=[],s=[],a=nY();for(let e of r)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(n,a).next(e=>({ks:e,removedBatchIds:i,addedBatchIds:s}))})})}function sI(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Ti.getLastRemoteSnapshotVersion(t))}function sT(e,t){return e.persistence.runTransaction("Allocate target","readwrite",n=>{let r;return e.Ti.getTargetData(n,t).next(i=>i?(r=i,eu.resolve(r)):e.Ti.allocateTargetId(n).next(i=>(r=new r5(t,i,"TargetPurposeListen",n.currentSequenceNumber),e.Ti.addTargetData(n,r).next(()=>r))))}).then(n=>{let r=e.xs.get(n.targetId);return(null===r||n.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(e.xs=e.xs.insert(n.targetId,n),e.Os.set(t,n.targetId)),n})}async function sE(e,t,n){let r=e.xs.get(t);try{n||await e.persistence.runTransaction("Release target",n?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,r))}catch(e){if(!ep(e))throw e;T(sy,`Failed to update sequence numbers for target ${t}: ${e}`)}e.xs=e.xs.remove(t),e.Os.delete(r.target)}function sx(e,t,n){let r=$.min(),i=nY();return e.persistence.runTransaction("Execute query","readwrite",s=>(function(e,t,n){let r=e.Os.get(n);return void 0!==r?eu.resolve(e.xs.get(r)):e.Ti.getTargetData(t,n)})(e,s,nF(t)).next(t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,e.Ti.getMatchingKeysForTargetId(s,t.targetId).next(e=>{i=e})}).next(()=>e.Ms.getDocumentsMatchingQuery(s,t,n?r:$.min(),n?i:nY())).next(n=>(s_(e,nK(t),n),{documents:n,$s:i})))}function sb(e,t){let n=e.Ti,r=e.xs.get(t);return r?Promise.resolve(r.target):e.persistence.runTransaction("Get target data","readonly",e=>n.Rt(e,t).next(e=>e?e.target:null))}function sS(e,t){let n=e.Ns.get(t)||$.min();return e.persistence.runTransaction("Get new document changes","readonly",r=>e.Bs.getAllFromCollectionGroup(r,t,en(n,-1),Number.MAX_SAFE_INTEGER)).then(n=>(s_(e,t,n),n))}function s_(e,t,n){let r=e.Ns.get(t)||$.min();n.forEach((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.Ns.set(t,r)}let sD="firestore_clients";function sk(e,t){return`${sD}_${e}_${t}`}let sC="firestore_mutations";function sA(e,t,n){let r=`${sC}_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}let sN="firestore_targets";function sR(e,t){return`${sN}_${e}_${t}`}let sO="SharedClientState";class sV{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Gs(e,t,n){let r=JSON.parse(n),i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(i=new C(r.error.code,r.error.message)),s?new sV(e,t,r.state,i):(E(sO,`Failed to parse mutation state for ID '${t}': ${n}`),null)}zs(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class sM{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Gs(e,t){let n=JSON.parse(t),r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(r=new C(n.error.code,n.error.message)),i?new sM(e,n.state,r):(E(sO,`Failed to parse target state for ID '${e}': ${t}`),null)}zs(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class sP{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Gs(e,t){let n=JSON.parse(t),r="object"==typeof n&&n.activeTargetIds instanceof Array,i=nZ;for(let e=0;r&&e<n.activeTargetIds.length;++e){var s;r="number"==typeof(s=n.activeTargetIds[e])&&Number.isInteger(s)&&!eS(s)&&s<=Number.MAX_SAFE_INTEGER&&s>=Number.MIN_SAFE_INTEGER,i=i.add(n.activeTargetIds[e])}return r?new sP(e,i):(E(sO,`Failed to parse client data for instance '${e}': ${t}`),null)}}class sF{constructor(e,t){this.clientId=e,this.onlineState=t}static Gs(e){let t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new sF(t.clientId,t.onlineState):(E(sO,`Failed to parse online state: ${e}`),null)}}class sL{constructor(){this.activeTargetIds=nZ}js(e){this.activeTargetIds=this.activeTargetIds.add(e)}Hs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}zs(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class sB{constructor(e,t,n,r,i){var s,a,o;this.window=e,this.xi=t,this.persistenceKey=n,this.Js=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Ys=this.Zs.bind(this),this.Xs=new tE(B),this.started=!1,this.eo=[];let l=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.no=sk(this.persistenceKey,this.Js),this.ro=(s=this.persistenceKey,`firestore_sequence_number_${s}`),this.Xs=this.Xs.insert(this.Js,new sL),this.io=RegExp(`^${sD}_${l}_([^_]*)$`),this.so=RegExp(`^${sC}_${l}_(\\d+)(?:_(.*))?$`),this.oo=RegExp(`^${sN}_${l}_(\\d+)$`),this._o=(a=this.persistenceKey,`firestore_online_state_${a}`),this.ao=(o=this.persistenceKey,`firestore_bundle_loaded_v2_${o}`),this.window.addEventListener("storage",this.Ys)}static C(e){return!(!e||!e.localStorage)}async start(){for(let e of(await this.syncEngine.Is())){if(e===this.Js)continue;let t=this.getItem(sk(this.persistenceKey,e));if(t){let n=sP.Gs(e,t);n&&(this.Xs=this.Xs.insert(n.clientId,n))}}this.uo();let e=this.storage.getItem(this._o);if(e){let t=this.co(e);t&&this.lo(t)}for(let e of this.eo)this.Zs(e);this.eo=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.ro,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ho(this.Xs)}isActiveQueryTarget(e){let t=!1;return this.Xs.forEach((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)}),t}addPendingMutation(e){this.Po(e,"pending")}updateMutationState(e,t,n){this.Po(e,t,n),this.To(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){let t=this.storage.getItem(sR(this.persistenceKey,e));if(t){let r=sM.Gs(e,t);r&&(n=r.state)}}return t&&this.Io.js(e),this.uo(),n}removeLocalQueryTarget(e){this.Io.Hs(e),this.uo()}isLocalQueryTarget(e){return this.Io.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(sR(this.persistenceKey,e))}updateQueryState(e,t,n){this.Eo(e,t,n)}
6handleUserChange(e,t,n){t.forEach(e=>{this.To(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ao(e)}notifyBundleLoaded(e){this.Ro(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Ys),this.removeItem(this.no),this.started=!1)}getItem(e){let t=this.storage.getItem(e);return T(sO,"READ",e,t),t}setItem(e,t){T(sO,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){T(sO,"REMOVE",e),this.storage.removeItem(e)}Zs(e){if(e.storageArea===this.storage){if(T(sO,"EVENT",e.key,e.newValue),e.key===this.no)return void E("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.xi.enqueueRetryable(async()=>{if(this.started){if(null!==e.key){if(this.io.test(e.key)){if(null==e.newValue){let t=this.Vo(e.key);return this.mo(t,null)}{let t=this.fo(e.key,e.newValue);if(t)return this.mo(t.clientId,t)}}else if(this.so.test(e.key)){if(null!==e.newValue){let t=this.po(e.key,e.newValue);if(t)return this.yo(t)}}else if(this.oo.test(e.key)){if(null!==e.newValue){let t=this.wo(e.key,e.newValue);if(t)return this.So(t)}}else if(e.key===this._o){if(null!==e.newValue){let t=this.co(e.newValue);if(t)return this.lo(t)}}else if(e.key===this.ro){let t=function(e){let t=eb.le;if(null!=e)try{let n=JSON.parse(e);D("number"==typeof n,30636,{bo:e}),t=n}catch(e){E(sO,"Failed to read sequence number from WebStorage",e)}return t}(e.newValue);t!==eb.le&&this.sequenceNumberHandler(t)}else if(e.key===this.ao){let t=this.Do(e.newValue);await Promise.all(t.map(e=>this.syncEngine.vo(e)))}}}else this.eo.push(e)})}}get Io(){return this.Xs.get(this.Js)}uo(){this.setItem(this.no,this.Io.zs())}Po(e,t,n){let r=new sV(this.currentUser,e,t,n),i=sA(this.persistenceKey,this.currentUser,e);this.setItem(i,r.zs())}To(e){let t=sA(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ao(e){let t={clientId:this.Js,onlineState:e};this.storage.setItem(this._o,JSON.stringify(t))}Eo(e,t,n){let r=sR(this.persistenceKey,e),i=new sM(e,t,n);this.setItem(r,i.zs())}Ro(e){let t=JSON.stringify(Array.from(e));this.setItem(this.ao,t)}Vo(e){let t=this.io.exec(e);return t?t[1]:null}fo(e,t){let n=this.Vo(e);return sP.Gs(n,t)}po(e,t){let n=this.so.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return sV.Gs(new y(i),r,t)}wo(e,t){let n=Number(this.oo.exec(e)[1]);return sM.Gs(n,t)}co(e){return sF.Gs(e)}Do(e){return JSON.parse(e)}async yo(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Co(e.batchId,e.state,e.error);T(sO,`Ignoring mutation for non-active user ${e.user.uid}`)}So(e){return this.syncEngine.Fo(e.targetId,e.state,e.error)}mo(e,t){let n=t?this.Xs.insert(e,t):this.Xs.remove(e),r=this.ho(this.Xs),i=this.ho(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Mo(s,a).then(()=>{this.Xs=n})}lo(e){this.Xs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ho(e){let t=nZ;return e.forEach((e,n)=>{t=t.unionWith(n.activeTargetIds)}),t}}class sz{constructor(){this.xo=new sL,this.Oo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.xo.js(e),this.Oo[e]||"not-current"}updateQueryState(e,t,n){this.Oo[e]=t}removeLocalQueryTarget(e){this.xo.Hs(e)}isLocalQueryTarget(e){return this.xo.activeTargetIds.has(e)}clearQueryState(e){delete this.Oo[e]}getAllActiveQueryTargets(){return this.xo.activeTargetIds}isActiveQueryTarget(e){return this.xo.activeTargetIds.has(e)}start(){return this.xo=new sL,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class sU{No(e){}shutdown(){}}let sq="ConnectivityMonitor";class sK{constructor(){this.Bo=()=>this.Lo(),this.ko=()=>this.qo(),this.Qo=[],this.$o()}No(e){this.Qo.push(e)}shutdown(){window.removeEventListener("online",this.Bo),window.removeEventListener("offline",this.ko)}$o(){window.addEventListener("online",this.Bo),window.addEventListener("offline",this.ko)}Lo(){for(let e of(T(sq,"Network connectivity changed: AVAILABLE"),this.Qo))e(0)}qo(){for(let e of(T(sq,"Network connectivity changed: UNAVAILABLE"),this.Qo))e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let s$=null;function sG(){return null===s$?s$=0x10000000+Math.round(0x80000000*Math.random()):s$++,"0x"+s$.toString(16)}let sj="RestConnection",sQ={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
6Query:"runAggregationQuery"};class sH{get Uo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.Ko=t+"://"+e.host,this.Wo=`projects/${n}/databases/${r}`,this.Go=this.databaseId.database===tU?`project_id=${n}`:`project_id=${n}&database_id=${r}`}zo(e,t,n,r,i){let s=sG(),a=this.jo(e,t.toUriEncodedString());T(sj,`Sending RPC '${e}' ${s}:`,a,n);let o={"google-cloud-resource-prefix":this.Wo,"x-goog-request-params":this.Go};this.Ho(o,r,i);let{host:l}=new URL(a),u=(0,h.zJ)(l);return this.Jo(e,a,o,n,u).then(t=>(T(sj,`Received RPC '${e}' ${s}: `,t),t),t=>{throw x(sj,`RPC '${e}' ${s} failed with error: `,t,"url: ",a,"request:",n),t})}Yo(e,t,n,r,i,s){return this.zo(e,t,n,r,i)}Ho(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+w,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)}jo(e,t){let n=sQ[e];return`${this.Ko}/v1/${t}:${n}`}terminate(){}}class sJ{constructor(e){this.Zo=e.Zo,this.Xo=e.Xo}e_(e){this.t_=e}n_(e){this.r_=e}i_(e){this.s_=e}onMessage(e){this.o_=e}close(){this.Xo()}send(e){this.Zo(e)}__(){this.t_()}a_(){this.r_()}u_(e){this.s_(e)}c_(e){this.o_(e)}}let sW="WebChannelConnection";class sX extends sH{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Jo(e,t,n,r,i){let s=sG();return new Promise((i,a)=>{let o=new d.ZS;o.setWithCredentials(!0),o.listenOnce(d.Bx.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case d.O4.NO_ERROR:let t=o.getResponseJson();T(sW,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case d.O4.TIMEOUT:T(sW,`RPC '${e}' ${s} timed out`),a(new C(k.DEADLINE_EXCEEDED,"Request time out"));break;case d.O4.HTTP_ERROR:let n=o.getStatus();if(T(sW,`RPC '${e}' ${s} failed with status:`,n,"response text:",o.getResponseText()),n>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);let t=null==e?void 0:e.error;if(t&&t.status&&t.message){let e=function(e){let t=e.toLowerCase().replace(/_/g,"-");return Object.values(k).indexOf(t)>=0?t:k.UNKNOWN}(t.status);a(new C(e,t.message))}else a(new C(k.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new C(k.UNAVAILABLE,"Connection failed."));break;default:S(9055,{l_:e,streamId:s,h_:o.getLastErrorCode(),P_:o.getLastError()})}}finally{T(sW,`RPC '${e}' ${s} completed.`)}});let l=JSON.stringify(r);T(sW,`RPC '${e}' ${s} sending request:`,r),o.send(t,"POST",l,n,15)})}T_(e,t,n){let i=sG(),s=[this.Ko,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=(0,d.fF)(),o=(0,d.Ao)(),l={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},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(l.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(l.useFetchStreams=!0),this.Ho(l.initMessageHeaders,t,n),l.encodeInitMessageHeaders=!0;let h=s.join("");T(sW,`Creating RPC '${e}' stream ${i}: ${h}`,l);let c=a.createWebChannel(h,l),m=!1,f=!1,g=new sJ({Zo:t=>{f?T(sW,`Not sending because RPC '${e}' stream ${i} is closed:`,t):(m||(T(sW,`Opening RPC '${e}' stream ${i} transport.`),c.open(),m=!0),T(sW,`RPC '${e}' stream ${i} sending:`,t),c.send(t))},Xo:()=>c.close()}),p=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return p(c,d.iO.EventType.OPEN,()=>{f||(T(sW,`RPC '${e}' stream ${i} transport opened.`),g.__())}),p(c,d.iO.EventType.CLOSE,()=>{f||(f=!0,T(sW,`RPC '${e}' stream ${i} transport closed`),g.u_())}),p(c,d.iO.EventType.ERROR,t=>{f||(f=!0,x(sW,`RPC '${e}' stream ${i} transport errored. Name:`,t.name,"Message:",t.message),g.u_(new C(k.UNAVAILABLE,"The operation could not be completed")))}),p(c,d.iO.EventType.MESSAGE,t=>{var n;if(!f){let s=t.data[0];D(!!s,16349);let a=(null==s?void 0:s.error)||(null==(n=s[0])?void 0:n.error);if(a){T(sW,`RPC '${e}' stream ${i} received error:`,a);let t=a.status,n=function(e){let t=r[e];if(void 0!==t)return rw(t)}(t),s=a.message;
6void 0===n&&(n=k.INTERNAL,s="Unknown error status: "+t+" with message "+a.message),f=!0,g.u_(new C(n,s)),c.close()}else T(sW,`RPC '${e}' stream ${i} received:`,s),g.c_(s)}}),p(o,d.Jh.STAT_EVENT,t=>{t.stat===d.ro.PROXY?T(sW,`RPC '${e}' stream ${i} detected buffering proxy`):t.stat===d.ro.NOPROXY&&T(sW,`RPC '${e}' stream ${i} detected no buffering proxy`)}),setTimeout(()=>{g.a_()},0),g}}function sY(){return"undefined"!=typeof window?window:null}function sZ(){return"undefined"!=typeof document?document:null}class s0{constructor(e,t,n=1e3,r=1.5,i=6e4){this.xi=e,this.timerId=t,this.I_=n,this.E_=r,this.d_=i,this.A_=0,this.R_=null,this.V_=Date.now(),this.reset()}reset(){this.A_=0}m_(){this.A_=this.d_}f_(e){this.cancel();let t=Math.floor(this.A_+this.g_()),n=Math.max(0,Date.now()-this.V_),r=Math.max(0,t-n);r>0&&T("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.A_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.R_=this.xi.enqueueAfterDelay(this.timerId,r,()=>(this.V_=Date.now(),e())),this.A_*=this.E_,this.A_<this.I_&&(this.A_=this.I_),this.A_>this.d_&&(this.A_=this.d_)}p_(){null!==this.R_&&(this.R_.skipDelay(),this.R_=null)}cancel(){null!==this.R_&&(this.R_.cancel(),this.R_=null)}g_(){return(Math.random()-.5)*this.A_}}let s1="PersistentStream";class s2{constructor(e,t,n,r,i,s,a,o){this.xi=e,this.y_=n,this.w_=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.S_=0,this.b_=null,this.D_=null,this.stream=null,this.v_=0,this.C_=new s0(e,t)}F_(){return 1===this.state||5===this.state||this.M_()}M_(){return 2===this.state||3===this.state}start(){this.v_=0,4!==this.state?this.auth():this.x_()}async stop(){this.F_()&&await this.close(0)}O_(){this.state=0,this.C_.reset()}N_(){this.M_()&&null===this.b_&&(this.b_=this.xi.enqueueAfterDelay(this.y_,6e4,()=>this.B_()))}L_(e){this.k_(),this.stream.send(e)}async B_(){if(this.M_())return this.close(0)}k_(){this.b_&&(this.b_.cancel(),this.b_=null)}q_(){this.D_&&(this.D_.cancel(),this.D_=null)}async close(e,t){this.k_(),this.q_(),this.C_.cancel(),this.S_++,4!==e?this.C_.reset():t&&t.code===k.RESOURCE_EXHAUSTED?(E(t.toString()),E("Using maximum backoff delay to prevent overloading the backend."),this.C_.m_()):t&&t.code===k.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Q_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.i_(t)}Q_(){}auth(){this.state=1;let e=this.U_(this.S_),t=this.S_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.S_===t&&this.K_(e,n)},t=>{e(()=>{let e=new C(k.UNKNOWN,"Fetching auth token failed: "+t.message);return this.W_(e)})})}K_(e,t){let n=this.U_(this.S_);this.stream=this.G_(e,t),this.stream.e_(()=>{n(()=>this.listener.e_())}),this.stream.n_(()=>{n(()=>(this.state=2,this.D_=this.xi.enqueueAfterDelay(this.w_,1e4,()=>(this.M_()&&(this.state=3),Promise.resolve())),this.listener.n_()))}),this.stream.i_(e=>{n(()=>this.W_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.v_?this.z_(e):this.onNext(e))})}x_(){this.state=5,this.C_.f_(async()=>{this.state=0,this.start()})}W_(e){return T(s1,`close with error: ${e}`),this.stream=null,this.close(4,e)}U_(e){return t=>{this.xi.enqueueAndForget(()=>this.S_===e?t():(T(s1,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class s5 extends s2{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}G_(e,t){return this.connection.T_("Listen",e,t)}z_(e){return this.onNext(e)}onNext(e){this.C_.reset();let t=function(e,t){let n;if("targetChange"in t){var r,i;t.targetChange;let s="NO_CHANGE"===(r=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===r?1:"REMOVE"===r?2:"CURRENT"===r?3:"RESET"===r?4:S(39313,{state:r}),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(D(void 0===i||"string"==typeof i,58123),tA.fromBase64String(i||"")):(D(void 0===i||i instanceof f||i instanceof Uint8Array,16193),tA.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;n=new rk(s,a,o,l&&new C(void 0===l.code?k.UNKNOWN:rw(l.code),l.message||"")||null)}else if("documentChange"in t){t.documentChange;let r=t.documentChange;r.document,r.document.name,r.document.updateTime;let i=r$(e,r.document.name),s=rB(r.document.updateTime),a=r.document.createTime?rB(r.document.createTime):$.min(),o=new ni({mapValue:{fields:r.document.fields}}),l=ns.newFoundDocument(i,s,a,o);n=new r_(r.targetIds||[],r.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let r=t.documentDelete;r.document;let i=r$(e,r.document),s=r.readTime?rB(r.readTime):$.min(),a=ns.newNoDocument(i,s);n=new r_([],r.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let r=t.documentRemove;r.document;let i=r$(e,r.document);n=new r_([],r.removedTargetIds||[],i,null)}else{if(!("filter"in t))return S(11601,{Vt:t});{t.filter;let e=t.filter;e.targetId;
6let{count:r=0,unchangedNames:i}=e,s=new ry(r,i);n=new rD(e.targetId,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return $.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?$.min():t.readTime?rB(t.readTime):$.min()}(e);return this.listener.j_(t,n)}H_(e){let t={};t.database=rQ(this.serializer),t.addTarget=function(e,t){let n,r=t.target;if((n=nA(r)?{documents:rY(e,r)}:{query:rZ(e,r).gt}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){var i;i=t.resumeToken,n.resumeToken=e.useProto3Json?i.toBase64():i.toUint8Array();let r=rF(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo($.min())>0){n.readTime=rL(e,t.snapshotVersion.toTimestamp());let r=rF(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);let n=function(e,t){let n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return S(28987,{purpose:e})}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.L_(t)}J_(e){let t={};t.database=rQ(this.serializer),t.removeTarget=e,this.L_(t)}}class s4 extends s2{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}get Y_(){return this.v_>0}start(){this.lastStreamToken=void 0,super.start()}Q_(){this.Y_&&this.Z_([])}G_(e,t){return this.connection.T_("Write",e,t)}z_(e){return D(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,D(!e.writeResults||0===e.writeResults.length,55816),this.listener.X_()}onNext(e){var t,n;D(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.C_.reset();let r=(t=e.writeResults,n=e.commitTime,t&&t.length>0?(D(void 0!==n,14353),t.map(e=>{let t;return(t=e.updateTime?rB(e.updateTime):rB(n)).isEqual($.min())&&(t=rB(n)),new re(t,e.transformResults||[])})):[]),i=rB(e.commitTime);return this.listener.ea(i,r)}ta(){let e={};e.database=rQ(this.serializer),this.L_(e)}Z_(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>rW(this.serializer,e))};this.L_(t)}}class s6{}class s3 extends s6{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.na=!1}ra(){if(this.na)throw new C(k.FAILED_PRECONDITION,"The client has already been terminated.")}zo(e,t,n,r){return this.ra(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.zo(e,rU(t,n),r,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===k.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new C(k.UNKNOWN,e.toString())})}Yo(e,t,n,r,i){return this.ra(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,a])=>this.connection.Yo(e,rU(t,n),r,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===k.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new C(k.UNKNOWN,e.toString())})}terminate(){this.na=!0,this.connection.terminate()}}class s8{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.ia=0,this.sa=null,this.oa=!0}_a(){0===this.ia&&(this.aa("Unknown"),this.sa=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.sa=null,this.ua("Backend didn't respond within 10 seconds."),this.aa("Offline"),Promise.resolve())))}ca(e){"Online"===this.state?this.aa("Unknown"):(this.ia++,this.ia>=1&&(this.la(),this.ua(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.aa("Offline")))}set(e){this.la(),this.ia=0,"Online"===e&&(this.oa=!1),this.aa(e)}aa(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}ua(e){let t=`Could not reach Cloud Firestore backend. ${e}
7This 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.oa?(E(t),this.oa=!1):T("OnlineStateTracker",t)}la(){null!==this.sa&&(this.sa.cancel(),this.sa=null)}}let s9="RemoteStore";class s7{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.ha=[],this.Pa=new Map,this.Ta=new Set,this.Ia=[],this.Ea=i,this.Ea.No(e=>{n.enqueueAndForget(async()=>
7{al(this)&&(T(s9,"Restarting streams for network reachability change."),await async function(e){e.Ta.add(4),await at(e),e.da.set("Unknown"),e.Ta.delete(4),await ae(e)}(this))})}),this.da=new s8(n,r)}}async function ae(e){if(al(e))for(let t of e.Ia)await t(!0)}async function at(e){for(let t of e.Ia)await t(!1)}function an(e,t){e.Pa.has(t.targetId)||(e.Pa.set(t.targetId,t),ao(e)?aa(e):ax(e).M_()&&ai(e,t))}function ar(e,t){let n=ax(e);e.Pa.delete(t),n.M_()&&as(e,t),0===e.Pa.size&&(n.M_()?n.N_():al(e)&&e.da.set("Unknown"))}function ai(e,t){if(e.Aa.Ke(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo($.min())>0){let n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}ax(e).H_(t)}function as(e,t){e.Aa.Ke(t),ax(e).J_(t)}function aa(e){e.Aa=new rA({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Rt:t=>e.Pa.get(t)||null,Pt:()=>e.datastore.serializer.databaseId}),ax(e).start(),e.da._a()}function ao(e){return al(e)&&!ax(e).F_()&&e.Pa.size>0}function al(e){return 0===e.Ta.size}async function au(e){e.da.set("Online")}async function ah(e){e.Pa.forEach((t,n)=>{ai(e,t)})}async function ac(e,t){e.Aa=void 0,ao(e)?(e.da.ca(t),aa(e)):e.da.set("Unknown")}async function ad(e,t,n){if(e.da.set("Online"),t instanceof rk&&2===t.state&&t.cause)try{await async function(e,t){let n=t.cause;for(let r of t.targetIds)e.Pa.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Pa.delete(r),e.Aa.removeTarget(r))}(e,t)}catch(n){T(s9,"Failed to remove targets %s: %s ",t.targetIds.join(","),n),await am(e,n)}else if(t instanceof r_?e.Aa.Xe(t):t instanceof rD?e.Aa.ot(t):e.Aa.nt(t),!n.isEqual($.min()))try{let t=await sI(e.localStore);n.compareTo(t)>=0&&await function(e,t){let n=e.Aa.It(t);
7return n.targetChanges.forEach((n,r)=>{if(n.resumeToken.approximateByteSize()>0){let i=e.Pa.get(r);i&&e.Pa.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{let r=e.Pa.get(t);if(!r)return;e.Pa.set(t,r.withResumeToken(tA.EMPTY_BYTE_STRING,r.snapshotVersion)),as(e,t);let i=new r5(r.target,t,n,r.sequenceNumber);ai(e,i)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){T(s9,"Failed to raise snapshot:",t),await am(e,t)}}async function am(e,t,n){if(!ep(t))throw t;e.Ta.add(1),await at(e),e.da.set("Offline"),n||(n=()=>sI(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{T(s9,"Retrying IndexedDB access"),await n(),e.Ta.delete(1),await ae(e)})}function af(e,t){return t().catch(n=>am(e,n,t))}async function ag(e){var t;let n=ab(e),r=e.ha.length>0?e.ha[e.ha.length-1].batchId:-1;for(;al(t=e)&&t.ha.length<10;)try{let t=await function(e,t){return e.persistence.runTransaction("Get next mutation batch","readonly",n=>(void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)))}(e.localStore,r);if(null===t){0===e.ha.length&&n.N_();break}r=t.batchId,function(e,t){e.ha.push(t);let n=ab(e);n.M_()&&n.Y_&&n.Z_(t.mutations)}(e,t)}catch(t){await am(e,t)}ap(e)&&ay(e)}function ap(e){return al(e)&&!ab(e).F_()&&e.ha.length>0}function ay(e){ab(e).start()}async function aw(e){ab(e).ta()}async function av(e){let t=ab(e);for(let n of e.ha)t.Z_(n.mutations)}
7async function aI(e,t,n){let r=e.ha.shift(),i=rg.from(r,t,n);await af(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await ag(e)}async function aT(e,t){t&&ab(e).Y_&&await async function(e,t){var n;if(function(e){switch(e){case k.OK:return S(64938);case k.CANCELLED:case k.UNKNOWN:case k.DEADLINE_EXCEEDED:case k.RESOURCE_EXHAUSTED:case k.INTERNAL:case k.UNAVAILABLE:case k.UNAUTHENTICATED:return!1;case k.INVALID_ARGUMENT:case k.NOT_FOUND:case k.ALREADY_EXISTS:case k.PERMISSION_DENIED:case k.FAILED_PRECONDITION:case k.ABORTED:case k.OUT_OF_RANGE:case k.UNIMPLEMENTED:case k.DATA_LOSS:return!0;default:return S(15467,{code:e})}}(n=t.code)&&n!==k.ABORTED){let n=e.ha.shift();ab(e).O_(),await af(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await ag(e)}}(e,t),ap(e)&&ay(e)}async function aE(e,t){t?(e.Ta.delete(2),await ae(e)):t||(e.Ta.add(2),await at(e),e.da.set("Unknown"))}function ax(e){var t,n,r;return e.Ra||(t=e.datastore,n=e.asyncQueue,r={e_:au.bind(null,e),n_:ah.bind(null,e),i_:ac.bind(null,e),j_:ad.bind(null,e)},t.ra(),e.Ra=new s5(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.Ia.push(async t=>{t?(e.Ra.O_(),ao(e)?aa(e):e.da.set("Unknown")):(await e.Ra.stop(),e.Aa=void 0)})),e.Ra}function ab(e){var t,n,r;return e.Va||(t=e.datastore,n=e.asyncQueue,r={e_:()=>Promise.resolve(),n_:aw.bind(null,e),i_:aT.bind(null,e),X_:av.bind(null,e),ea:aI.bind(null,e)},t.ra(),e.Va=new s4(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.Ia.push(async t=>{t?(e.Va.O_(),await ag(e)):(await e.Va.stop(),e.ha.length>0&&(T(s9,`Stopping write stream with ${e.ha.length} pending writes`),e.ha=[]))})),e.Va}class aS{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new A,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){let s=new aS(e,t,Date.now()+n,r,i);return s.start(n),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new C(k.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)}}class a_{static emptySet(e){return new a_(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||W.comparator(t.key,n.key):(e,t)=>W.comparator(e.key,t.key),this.keyedMap=nH(),this.sortedSet=new tE(this.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){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,n)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof a_)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n  "+e.join("  \n")+"\n)"}copy(e,t){let n=new a_;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class aD{constructor(){this.ma=new tE(W.comparator)}track(e){let t=e.doc.key,n=this.ma.get(t);n?0!==e.type&&3===n.type?this.ma=this.ma.insert(t,e):3===e.type&&1!==n.type?this.ma=this.ma.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.ma=this.ma.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.ma=this.ma.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.ma=this.ma.remove(t):1===e.type&&2===n.type?this.ma=this.ma.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.ma=this.ma.insert(t,{type:2,doc:e.doc}):S(63341,{Vt:e,fa:n}):this.ma=this.ma.insert(t,e)}ga(){let e=[];return this.ma.inorderTraversal((t,n)=>{e.push(n)}),e}}class ak{constructor(e,t,n,r,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,r,i){let s=[];
7return t.forEach(e=>{s.push({type:0,doc:e})}),new ak(e,t,a_.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&nB(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}class aC{constructor(){this.queries=aA(),this.onlineState="Unknown",this.ba=new Set}terminate(){!function(e,t){let n=e.queries;e.queries=aA(),n.forEach((e,n)=>{for(let e of n.ya)e.onError(t)})}(this,new C(k.ABORTED,"Firestore shutting down"))}}function aA(){return new nG(e=>nz(e),nB)}function aN(e,t){let n=!1;for(let r of t){let t=r.query,i=e.queries.get(t);if(i){for(let e of i.ya)e.va(r)&&(n=!0);i.pa=r}}n&&aO(e)}function aR(e,t,n){let r=e.queries.get(t);if(r)for(let e of r.ya)e.onError(n);e.queries.delete(t)}function aO(e){e.ba.forEach(e=>{e.next()})}(a=s||(s={})).Ca="default",a.Cache="cache";class aV{constructor(e){this.key=e}}class aM{constructor(e){this.key=e}}class aP{constructor(e,t){this.query=e,this.Ga=t,this.za=null,this.hasCachedResults=!1,this.current=!1,this.ja=nY(),this.mutatedKeys=nY(),this.Ha=n$(e),this.Ja=new a_(this.Ha)}get Ya(){return this.Ga}Za(e,t){let n=t?t.Xa:new aD,r=t?t.Ja:this.Ja,i=t?t.mutatedKeys:this.mutatedKeys,s=r,a=!1,o="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,l="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal((e,t)=>{let u=r.get(e),h=nq(this.query,t)?t:null,c=!!u&&this.mutatedKeys.has(u.key),d=!!h&&(h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations),m=!1;u&&h?u.data.isEqual(h.data)?c!==d&&(n.track({type:3,doc:h}),m=!0):this.eu(u,h)||(n.track({type:2,doc:h}),m=!0,(o&&this.Ha(h,o)>0||l&&0>this.Ha(h,l))&&(a=!0)):!u&&h?(n.track({type:0,doc:h}),m=!0):u&&!h&&(n.track({type:1,doc:u}),m=!0,(o||l)&&(a=!0)),m&&(h?(s=s.add(h),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))}),null!==this.query.limit)for(;s.size>this.query.limit;){let e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{Ja:s,Xa:n,Cs:a,mutatedKeys:i}}eu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){let i=this.Ja;this.Ja=e.Ja,this.mutatedKeys=e.mutatedKeys;let s=e.Xa.ga();s.sort((e,t)=>(function(e,t){let n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return S(20277,{Vt:e})}};return n(e)-n(t)})(e.type,t.type)||this.Ha(e.doc,t.doc)),this.tu(n),r=null!=r&&r;let a=t&&!r?this.nu():[],o=0===this.ja.size&&this.current&&!r?1:0,l=o!==this.za;return(this.za=o,0!==s.length||l)?{snapshot:new ak(this.query,e.Ja,i,s,e.mutatedKeys,0===o,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),ru:a}:{ru:a}}Da(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ja:this.Ja,Xa:new aD,mutatedKeys:this.mutatedKeys,Cs:!1},!1)):{ru:[]}}iu(e){return!this.Ga.has(e)&&!!this.Ja.has(e)&&!this.Ja.get(e).hasLocalMutations}tu(e){e&&(e.addedDocuments.forEach(e=>this.Ga=this.Ga.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ga=this.Ga.delete(e)),this.current=e.current)}nu(){if(!this.current)return[];let e=this.ja;this.ja=nY(),this.Ja.forEach(e=>{this.iu(e.key)&&(this.ja=this.ja.add(e.key))});let t=[];return e.forEach(e=>{this.ja.has(e)||t.push(new aM(e))}),this.ja.forEach(n=>{e.has(n)||t.push(new aV(n))}),t}su(e){this.Ga=e.$s,this.ja=nY();let t=this.Za(e.documents);return this.applyChanges(t,!0)}ou(){return ak.fromInitialDocuments(this.query,this.Ja,this.mutatedKeys,0===this.za,this.hasCachedResults)}}let aF="SyncEngine";class aL{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class aB{constructor(e){this.key=e,this._u=!1}}class az{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedCl
7ientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.au={},this.uu=new nG(e=>nz(e),nB),this.cu=new Map,this.lu=new Set,this.hu=new tE(W.comparator),this.Pu=new Map,this.Tu=new i7,this.Iu={},this.Eu=new Map,this.du=iq.lr(),this.onlineState="Unknown",this.Au=void 0}get isPrimaryClient(){return!0===this.Au}}async function aU(e,t,n,r,i){e.Ru=(t,n,r)=>(async function(e,t,n,r){let i=t.view.Za(n);i.Cs&&(i=await sx(e.localStore,t.query,!1).then(({documents:e})=>t.view.Za(e,i)));let s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s,a);return aX(e,t.targetId,o.ru),o.snapshot})(e,t,n,r);let s=await sx(e.localStore,t,!0),a=new aP(t,s.$s),o=a.Za(s.documents),l=rS.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);aX(e,n,u.ru);let h=new aL(t,n,a);return e.uu.set(t,h),e.cu.has(n)?e.cu.get(n).push(t):e.cu.set(n,[t]),u.snapshot}async function aq(e,t){try{let n=await function(e,t){let n=t.snapshotVersion,r=e.xs;return e.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{var s,a,o;let l,u,h=e.Bs.newChangeBuffer({trackRemovals:!0});r=e.xs;let c=[];
7t.targetChanges.forEach((s,a)=>{var o;let l=r.get(a);if(!l)return;c.push(e.Ti.removeMatchingKeys(i,s.removedDocuments,a).next(()=>e.Ti.addMatchingKeys(i,s.addedDocuments,a)));let u=l.withSequenceNumber(i.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(tA.EMPTY_BYTE_STRING,$.min()).withLastLimboFreeSnapshotVersion($.min()):s.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(s.resumeToken,n)),r=r.insert(a,u),o=u,(0===l.resumeToken.approximateByteSize()||o.snapshotVersion.toMicroseconds()-l.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)&&c.push(e.Ti.updateTargetData(i,u))});let d=nj,m=nY();if(t.documentUpdates.forEach(n=>{t.resolvedLimboDocuments.has(n)&&c.push(e.persistence.referenceDelegate.updateLimboDocument(i,n))}),c.push((s=i,a=h,o=t.documentUpdates,l=nY(),u=nY(),o.forEach(e=>l=l.add(e)),a.getEntries(s,l).next(e=>{let t=nj;return o.forEach((n,r)=>{let i=e.get(n);r.isFoundDocument()!==i.isFoundDocument()&&(u=u.add(n)),r.isNoDocument()&&r.version.isEqual($.min())?(a.removeEntry(n,r.readTime),t=t.insert(n,r)):!i.isValidDocument()||r.version.compareTo(i.version)>0||0===r.version.compareTo(i.version)&&i.hasPendingWrites?(a.addEntry(r),t=t.insert(n,r)):T(sy,"Ignoring outdated watch update for ",n,". Current version:",i.version," Watch version:",r.version)}),{qs:t,Qs:u}})).next(e=>{d=e.qs,m=e.Qs})),!n.isEqual($.min())){let t=e.Ti.getLastRemoteSnapshotVersion(i).next(t=>e.Ti.setTargetsMetadata(i,i.currentSequenceNumber,n));c.push(t)}return eu.waitFor(c).next(()=>h.apply(i)).next(()=>e.localDocuments.getLocalViewOfDocuments(i,d,m)).next(()=>d)}).then(t=>(e.xs=r,t))}(e.localStore,t);
7t.targetChanges.forEach((t,n)=>{let r=e.Pu.get(n);r&&(D(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?r._u=!0:t.modifiedDocuments.size>0?D(r._u,14607):t.removedDocuments.size>0&&(D(r._u,42227),r._u=!1))}),await aZ(e,n,t)}catch(e){await el(e)}}function aK(e,t,n){var r;if(e.isPrimaryClient&&0===n||!e.isPrimaryClient&&1===n){let n,i=[];e.uu.forEach((e,n)=>{let r=n.view.Da(t);r.snapshot&&i.push(r.snapshot)}),(r=e.eventManager).onlineState=t,n=!1,r.queries.forEach((e,r)=>{for(let e of r.ya)e.Da(t)&&(n=!0)}),n&&aO(r),i.length&&e.au.j_(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function a$(e,t,n){e.sharedClientState.updateQueryState(t,"rejected",n);let r=e.Pu.get(t),i=r&&r.key;if(i){let n=new tE(W.comparator);n=n.insert(i,ns.newNoDocument(i,$.min()));let r=nY().add(i),s=new rb($.min(),new Map,new tE(B),n,r);await aq(e,s),e.hu=e.hu.remove(i),e.Pu.delete(t),aY(e)}else await sE(e.localStore,t,!1).then(()=>aJ(e,t,n)).catch(el)}async function aG(e,t){var n;let r=t.batch.batchId;try{let i=await (n=e.localStore,n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let r=t.batch.keys(),i=n.Bs.newChangeBuffer({trackRemovals:!0});return(function(e,t,n,r){let i=n.batch,s=i.keys(),a=eu.resolve();return s.forEach(e=>{a=a.next(()=>r.getEntry(t,e)).next(t=>{let s=n.docVersions.get(e);D(null!==s,48541),0>t.version.compareTo(s)&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))})(n,e,t,i).next(()=>i.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=nY();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))}));aH(e,r,null),aQ(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await aZ(e,i)}catch(e){await el(e)}}async function aj(e,t,n){var r;try{let i=await (r=e.localStore,r.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return r.mutationQueue.lookupMutationBatch(e,t).next(t=>(D(null!==t,37113),n=t.keys(),r.mutationQueue.removeMutationBatch(e,t))).next(()=>r.mutationQueue.performConsistencyCheck(e)).next(()=>r.documentOverlayCache.removeOverlaysForBatchId(e,n,t)).next(()=>r.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,n)).next(()=>r.localDocuments.getDocuments(e,n))}));aH(e,t,n),aQ(e,t),e.sharedClientState.updateMutationState(t,"rejected",n),await aZ(e,i)}catch(e){await el(e)}}function aQ(e,t){(e.Eu.get(t)||[]).forEach(e=>{e.resolve()}),e.Eu.delete(t)}function aH(e,t,n){let r=e.Iu[e.currentUser.toKey()];if(r){let i=r.get(t);i&&(n?i.reject(n):i.resolve(),r=r.remove(t)),e.Iu[e.currentUser.toKey()]=r}}function aJ(e,t,n=null){for(let r of(e.sharedClientState.removeLocalQueryTarget(t),e.cu.get(t)))e.uu.delete(r),n&&e.au.Vu(r,n);e.cu.delete(t),e.isPrimaryClient&&e.Tu.Hr(t).forEach(t=>{e.Tu.containsKey(t)||aW(e,t)})}function aW(e,t){e.lu.delete(t.path.canonicalString());let n=e.hu.get(t);null!==n&&(ar(e.remoteStore,n),e.hu=e.hu.remove(t),e.Pu.delete(n),aY(e))}function aX(e,t,n){for(let r of n)r instanceof aV?(e.Tu.addReference(r.key,t),function(e,t){let n=t.key,r=n.path.canonicalString();e.hu.get(n)||e.lu.has(r)||(T(aF,"New document in limbo: "+n),e.lu.add(r),aY(e))}(e,r)):r instanceof aM?(T(aF,"Document no longer in limbo: "+r.key),e.Tu.removeReference(r.key,t),e.Tu.containsKey(r.key)||aW(e,r.key)):S(19791,{mu:r})}function aY(e){for(;e.lu.size>0&&e.hu.size<e.maxConcurrentLimboResolutions;){let t=e.lu.values().next().value;e.lu.delete(t);let n=new W(Q.fromString(t)),r=e.du.next();e.Pu.set(r,new aB(n)),e.hu=e.hu.insert(n,r),an(e.remoteStore,new r5(nF(new nV(n.path)),r,"TargetPurposeLimboResolution",eb.le))}}async function aZ(e,t,n){let r=[],i=[],s=[];e.uu.isEmpty()||(e.uu.forEach((a,o)=>{s.push(e.Ru(o,t,n).then(t=>{var s;if((t||n)&&e.isPrimaryClient){let r=t?!t.fromCache:null==(s=null==n?void 0:n.targetChanges.get(o.targetId))?void 0:s.current;
7e.sharedClientState.updateQueryState(o.targetId,r?"current":"not-current")}if(t){r.push(t);let e=sf.Rs(o.targetId,t);i.push(e)}}))}),await Promise.all(s),e.au.j_(r),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>eu.forEach(t,t=>eu.forEach(t.ds,r=>e.persistence.referenceDelegate.addReference(n,t.targetId,r)).next(()=>eu.forEach(t.As,r=>e.persistence.referenceDelegate.removeReference(n,t.targetId,r)))))}catch(e){if(!ep(e))throw e;T(sy,"Failed to update sequence numbers: "+e)}for(let n of t){let t=n.targetId;if(!n.fromCache){let n=e.xs.get(t),r=n.snapshotVersion,i=n.withLastLimboFreeSnapshotVersion(r);e.xs=e.xs.insert(t,i)}}}(e.localStore,i))}async function a0(e,t){if(!e.currentUser.isEqual(t)){T(aF,"User change. New user:",t.toKey());let n=await sv(e.localStore,t);e.currentUser=t,e.Eu.forEach(e=>{e.forEach(e=>{e.reject(new C(k.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Eu.clear(),e.sharedClientState.handleUserChange(t,n.removedBatchIds,n.addedBatchIds),await aZ(e,n.ks)}}function a1(e,t){let n=e.Pu.get(t);if(n&&n._u)return nY().add(n.key);{let n=nY(),r=e.cu.get(t);if(!r)return n;for(let t of r){let r=e.uu.get(t);n=n.unionWith(r.view.Ya)}return n}}async function a2(e,t){let n=await sx(e.localStore,t.query,!0),r=t.view.su(n);return e.isPrimaryClient&&aX(e,t.targetId,r.ru),r}async function a5(e,t){return sS(e.localStore,t).then(t=>aZ(e,t))}async function a4(e,t,n,r){var i;let s=await function(e,t){let n=e.mutationQueue;return e.persistence.runTransaction("Lookup mutation documents","readonly",r=>n.tr(r,t).next(t=>t?e.localDocuments.getDocuments(r,t):eu.resolve(null)))}(e.localStore,t);null!==s?("pending"===n?await ag(e.remoteStore):"acknowledged"===n||"rejected"===n?(aH(e,t,r||null),aQ(e,t),i=e.localStore,i.mutationQueue.sr(t)):S(6720,"Unknown batchState",{fu:n}),await aZ(e,s)):T(aF,"Cannot apply mutation batch with id: "+t)}async function a6(e,t){if(ot(e),on(e),!0===t&&!0!==e.Au){let t=e.sharedClientState.getAllActiveQueryTargets(),n=await a3(e,t.toArray());for(let t of(e.Au=!0,await aE(e.remoteStore,!0),n))an(e.remoteStore,t)}else if(!1===t&&!1!==e.Au){let t=[],n=Promise.resolve();e.cu.forEach((r,i)=>{e.sharedClientState.isLocalQueryTarget(i)?t.push(i):n=n.then(()=>(aJ(e,i),sE(e.localStore,i,!0))),ar(e.remoteStore,i)}),await n,await a3(e,t),e.Pu.forEach((t,n)=>{ar(e.remoteStore,n)}),e.Tu.Jr(),e.Pu=new Map,e.hu=new tE(W.comparator),e.Au=!1,await aE(e.remoteStore,!1)}}async function a3(e,t,n){let r=[],i=[];for(let n of t){let t,s=e.cu.get(n);if(s&&0!==s.length)for(let n of(t=await sT(e.localStore,nF(s[0])),s)){let t=e.uu.get(n),r=await a2(e,t);r.snapshot&&i.push(r.snapshot)}else{let r=await sb(e.localStore,n);t=await sT(e.localStore,r),await aU(e,a8(r),n,!1,t.resumeToken)}r.push(t)}return e.au.j_(i),r}function a8(e){var t,n,r,i,s;return t=e.path,n=e.collectionGroup,r=e.orderBy,i=e.filters,s=e.limit,new nV(t,n,r,i,s,"F",e.startAt,e.endAt)}function a9(e){return e.localStore.persistence.Is()}async function a7(e,t,n,r){if(e.Au)return void T(aF,"Ignoring unexpected query state notification.");let i=e.cu.get(t);if(i&&i.length>0)switch(n){case"current":case"not-current":{let r=await sS(e.localStore,nK(i[0])),s=rb.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,tA.EMPTY_BYTE_STRING);await aZ(e,r,s);break}case"rejected":await sE(e.localStore,t,!0),aJ(e,t,r);break;default:S(64155,n)}}async function oe(e,t,n){let r=ot(e);if(r.Au){for(let e of t){if(r.cu.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){T(aF,"Adding an already active target "+e);continue}let t=await sb(r.localStore,e),n=await sT(r.localStore,t);await aU(r,a8(t),n.targetId,!1,n.resumeToken),an(r.remoteStore,n)}for(let e of n)r.cu.has(e)&&await sE(r.localStore,e,!1).then(()=>{ar(r.remoteStore,e),aJ(r,e)}).catch(el)}}function ot(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=aq.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=a1.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=a$.bind(null,e),e.au.j_=aN.bind(null,e.eventManager),e.au.Vu=aR.bind(null,e.eventManager),e}function on(e){return e.remoteStore.remoteSyncer.applySuccessfulWrite=aG.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=aj.bind(null,e),e}class or{constructor(){this.kind="memory",this.synchronizeTabs=!1}
7async initialize(e){this.serializer=new rP(e.databaseInfo.databaseId,!0),this.sharedClientState=this.pu(e),this.persistence=this.yu(e),await this.persistence.start(),this.localStore=this.wu(e),this.gcScheduler=this.Su(e,this.localStore),this.indexBackfillerScheduler=this.bu(e,this.localStore)}Su(e,t){return null}bu(e,t){return null}wu(e){var t,n;return t=this.persistence,n=new sp,new sw(t,n,e.initialUser,this.serializer)}yu(e){return new ss(so.fi,this.serializer)}pu(e){return new sz}async terminate(){var e,t;null==(e=this.gcScheduler)||e.stop(),null==(t=this.indexBackfillerScheduler)||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}or.provider={build:()=>new or};class oi extends or{constructor(e,t,n){super(),this.Du=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Du.initialize(this,e),await on(this.Du.syncEngine),await ag(this.Du.remoteStore),await this.persistence.Ji(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}wu(e){var t,n;return t=this.persistence,n=new sp,new sw(t,n,e.initialUser,this.serializer)}Su(e,t){return new iH(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}bu(e,t){let n=new ex(t,this.persistence);return new eE(e.asyncQueue,n)}yu(e){let t=sm(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?iP.withCacheSize(this.cacheSizeBytes):iP.DEFAULT;return new sd(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,sY(),sZ(),this.serializer,this.sharedClientState,!!this.forceOwnership)}pu(e){return new sz}}class os extends oi{constructor(e,t){super(e,t,!1),this.Du=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);let t=this.Du.syncEngine;this.sharedClientState instanceof sB&&(this.sharedClientState.syncEngine={Co:a4.bind(null,t),Fo:a7.bind(null,t),Mo:oe.bind(null,t),Is:a9.bind(null,t),vo:a5.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ji(async e=>{await a6(this.Du.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())})}pu(e){let t=sY();if(!sB.C(t))throw new C(k.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let n=sm(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new sB(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class oa{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=>aK(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=a0.bind(null,this.syncEngine),await aE(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new aC}createDatastore(e){var t;let n=new rP(e.databaseInfo.databaseId,!0),r=new sX(e.databaseInfo);return t=e.authCredentials,new s3(t,e.appCheckCredentials,r,n)}createRemoteStore(e){var t,n;return t=this.localStore,n=this.datastore,new s7(t,n,e.asyncQueue,e=>aK(this.syncEngine,e,0),sK.C()?new sK:new sU)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){let o=new az(e,t,n,r,i,s);return a&&(o.Au=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){T(s9,"RemoteStore shutting down."),e.Ta.add(5),await at(e),e.Ea.shutdown(),e.da.set("Unknown")}(this.remoteStore),null==(e=this.datastore)||e.terminate(),null==(t=this.eventManager)||t.terminate()}}oa.provider={build:()=>new oa};let oo=new Map;class ol{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new C(k.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)||t;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=0x2800000;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new C(k.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new C(k.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=function(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}(null!=(n=e.experimentalLongPollingOptions)?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new C(k.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new C(k.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new C(k.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){var t,n;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&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&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 ol({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new C(k.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"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new C(k.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 ol(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new R;switch(e.type){case"firstParty":return new M(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new C(k.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
7d credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){let t=oo.get(e);t&&(T("ComponentProvider","Removing Datastore"),oo.delete(e),t.terminate())}(this),Promise.resolve()}}class oh{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new oh(this.firestore,e,this._query)}}class oc{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 od(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new oc(this.firestore,e,this._key)}}class od extends oh{constructor(e,t,n){super(e,t,new nV(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new oc(this.firestore,null,new W(e))}withConverter(e){return new od(this.firestore,e,this._path)}}let om="AsyncQueue";class of{constructor(e=Promise.resolve()){this.zu=[],this.ju=!1,this.Hu=[],this.Ju=null,this.Yu=!1,this.Zu=!1,this.Xu=[],this.C_=new s0(this,"async_queue_retry"),this.ec=()=>{let e=sZ();e&&T(om,"Visibility state changed to "+e.visibilityState),this.C_.p_()},this.tc=e;let t=sZ();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.ec)}get isShuttingDown(){return this.ju}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.nc(),this.rc(e)}enterRestrictedMode(e){if(!this.ju){this.ju=!0,this.Zu=e||!1;let t=sZ();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.ec)}}enqueue(e){if(this.nc(),this.ju)return new Promise(()=>{});let t=new A;return this.rc(()=>this.ju&&this.Zu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.zu.push(e),this.sc()))}async sc(){if(0!==this.zu.length){try{await this.zu[0](),this.zu.shift(),this.C_.reset()}catch(e){if(!ep(e))throw e;T(om,"Operation failed with retryable error: "+e)}this.zu.length>0&&this.C_.f_(()=>this.sc())}}rc(e){let t=this.tc.then(()=>(this.Yu=!0,e().catch(e=>{throw this.Ju=e,this.Yu=!1,E("INTERNAL UNHANDLED ERROR: ",og(e)),e}).then(e=>(this.Yu=!1,e))));return this.tc=t,t}enqueueAfterDelay(e,t,n){this.nc(),this.Xu.indexOf(e)>-1&&(t=0);let r=aS.createAndSchedule(this,e,t,n,e=>this.oc(e));return this.Hu.push(r),r}nc(){this.Ju&&S(47125,{_c:og(this.Ju)})}verifyOperationInProgress(){}async ac(){let e;do e=this.tc,await e;while(e!==this.tc)}uc(e){for(let t of this.Hu)if(t.timerId===e)return!0;return!1}cc(e){return this.ac().then(()=>{for(let t of(this.Hu.sort((e,t)=>e.targetTimeMs-t.targetTimeMs),this.Hu))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.ac()})}lc(e){this.Xu.push(e)}oc(e){let t=this.Hu.indexOf(e);this.Hu.splice(t,1)}}function og(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}class op extends ou{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new of,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new of(e),this._firestoreClient=void 0,await e}}}function oy(e,t,n){n||(n=tU);let r=(0,o.j6)(e,"firestore");if(r.isInitialized(n)){let e=r.getImmediate({identifier:n}),i=r.getOptions(n);if((0,h.bD)(i,t))return e;throw new C(k.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&void 0!==t.localCache)throw new C(k.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");
7if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new C(k.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return t.host&&(0,h.zJ)(t.host)&&(0,h.gE)(t.host),r.initialize({options:t,instanceIdentifier:n})}class ow{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new C(k.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new J(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class ov{constructor(e){this._methodName=e}}class oI extends ov{_toFieldTransform(e){return new n7(e.path,new n1)}isEqual(e){return e instanceof oI}}let oT=RegExp("[~\\*/\\[\\]]");function oE(e,t,n,r,i){let s=r&&!r.isEmpty(),a=void 0!==i,o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=` in field ${r}`),a&&(l+=` in document ${i}`),l+=")"),new C(k.INVALID_ARGUMENT,o+e+l)}class ox{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new oc(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new ob(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){let t=this._document.data.field(oS("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class ob extends ox{data(){return super.data()}}function oS(e,t){return"string"==typeof t?function(e,t,n){if(t.search(oT)>=0)throw oE(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,void 0);try{return new ow(...t.split("."))._internalPath}catch(n){throw oE(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,void 0)}}(e,t):t instanceof ow?t._internalPath:t._delegate._internalPath}class o_ extends ox{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new oD(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){let n=this._document.data.field(oS("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class oD extends o_{data(e={}){return super.data(e)}}class ok{constructor(e){let t;this.kind="persistent",(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),t=e.tabManager):(t=function(e){return new oA(null==e?void 0:e.forceOwnership)}(void 0))._initialize(e),this._onlineComponentProvider=t._onlineComponentProvider,this._offlineComponentProvider=t._offlineComponentProvider}toJSON(){return{kind:this.kind}}}function oC(e){return new ok(e)}class oA{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=oa.provider,this._offlineComponentProvider={build:t=>new oi(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class oN{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=oa.provider,this._offlineComponentProvider={build:t=>new os(t,null==e?void 0:e.cacheSizeBytes)}}}function oR(){return new oN}function oO(){return new oI("serverTimestamp")}new WeakMap,function(e=!0){w=o.MF,(0,o.om)(new l.uA("firestore",(t,{instanceIdentifier:n,options:r})=>{let i=t.getProvider("app").getImmediate(),s=new op(new O(t.getProvider("auth-internal")),new F(i,t.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new C(k.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new tq(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:e},r),s._setSettings(r),s},"PUBLIC").setMultipleInstances(!0)),(0,o.KO)(g,p,void 0),(0,o.KO)(g,p,"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.