1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[776],{68439:(e,t,r)=>{r.d(t,{$:()=>tT,A:()=>lb,B:()=>r9,C:()=>t$,D:()=>nL,F:()=>lE,H:()=>lN,N:()=>ac,P:()=>aI,Q:()=>nR,R:()=>Q,S:()=>rl,T:()=>P,Y:()=>x,Z:()=>nK,_:()=>g,a:()=>k,a0:()=>r7,a1:()=>nY,a2:()=>nW,a5:()=>lp,a7:()=>lg,a9:()=>nP,aR:()=>nO,aU:()=>n7,a_:()=>lT,aa:()=>t5,ab:()=>lf,af:()=>ly,aq:()=>tJ,b:()=>O,b4:()=>se,c:()=>eM,d:()=>I,e:()=>S,f:()=>rt,g:()=>nj,h:()=>nJ,i:()=>tF,j:()=>n2,k:()=>rr,l:()=>rn,m:()=>ee,n:()=>rs,o:()=>ri,p:()=>et,q:()=>t7,r:()=>e0,s:()=>ek,t:()=>tU,u:()=>t9,v:()=>G,w:()=>X,y:()=>Z,z:()=>lx});var n,s,i,a,o=r(45458),l=r(76653),u=r(89532),c=r(29979),h=r(11708),d=r(35005);r(65364);var m=r(88220).Buffer;class f{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}}f.UNAUTHENTICATED=new f(null),f.GOOGLE_CREDENTIALS=new f("google-credentials-uid"),f.FIRST_PARTY=new f("first-party-uid"),f.MOCK_USER=new f("mock-user");let p="12.15.0";function g(e){p=e}let y=new c.Vy("@firebase/firestore");function w(){return y.logLevel}function v(e,...t){if(y.logLevel<=c.$b.DEBUG){let r=t.map(T);y.debug(`Firestore (${p}): ${e}`,...r)}}function _(e,...t){if(y.logLevel<=c.$b.ERROR){let r=t.map(T);y.error(`Firestore (${p}): ${e}`,...r)}}function E(e,...t){if(y.logLevel<=c.$b.WARN){let r=t.map(T);y.warn(`Firestore (${p}): ${e}`,...r)}}function T(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function x(e,t,r){let n="Unexpected state";"string"==typeof t?n=t:r=t,b(e,n,r)}function b(e,t,r){let n=`FIRESTORE (${p}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==r)try{n+=" CONTEXT: "+JSON.stringify(r)}catch(e){n+=" CONTEXT: "+r}throw _(n),Error(n)}function N(e,t,r,n){let s="Unexpected state";"string"==typeof r?s=r:n=r,e||b(t,s,n)}let S={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 I extends l.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class V{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class C{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class A{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(f.UNAUTHENTICATED))}shutdown(){}}class D{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class k{constructor(e){this.t=e,this.currentUser=f.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){N(void 0===this.o,42304);let r=this.i,n=e=>this.i!==r?(r=this.i,t(e)):Promise.resolve(),s=new V;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new V,e.enqueueRetryable(()=>n(this.currentUser))};let i=()=>{let t=s;e.enqueueRetryable(async()=>{await t.promise,await n(this.currentUser)})},a=e=>{v("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),i())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(v("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new V)}},0),i()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(v("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(N("string"==typeof t.accessToken,31837,{l:t}),new C(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 N(null===e||"string"==typeof e,2055,{h:e}),new f(e)}}class R{constructor(e,t,r){this.T=e,this.P=t,this.R=r,this.type="FirstParty",this.user=f.FIRST_PARTY,this.I=new Map}A(){return this.R?this.R():null}get headers(){this.I.set("X-Goog-AuthUser",this.T);let e=this.A();return e&&this.I.set("Authorization",e),this.P&&this.I.set("X-Goog-Iam-Authorization-Token",this.P),this.I}}class L{constructor(e,t,r){this.T=e,this.P=t,this.R=r}getToken(){return Promise.resolve(new R(this.T,this.P,this.R))}start(e,t){e.enqueueRetryable(()=>t(f.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class U{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 O{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,(0,o._isFirebaseServerApp)(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){N(void 0===this.o,3512);let r=e=>{null!=e.error&&v("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let r=e.token!==this.m;return this.m=e.token,v("FirebaseAppCheckTokenProvider",`Received ${r?"new":"existing"} token.`),r?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>r(t))};let n=e=>{v("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(e=>n(e)),setTimeout(()=>{if(!this.appCheck){let e=this.V.getImmediate({optional:!0});e?n(e):v("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new U(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(N("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new U(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class P{static newId(){let e=62*Math.floor(256/62),t="";for(;t.length<20;){let r=function(){let e="u">typeof self&&(self.crypto||self.msCrypto),t=new Uint8Array(40);if(e&&"function"==typeof e.getRandomValues)e.getRandomValues(t);else for(let e=0;e<40;
1e++)t[e]=Math.floor(256*Math.random());return t}();for(let n=0;n<r.length;++n)t.length<20&&r[n]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(r[n]%62))}return t}}function M(e,t){return e<t?-1:+(e>t)}function F(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++){let r=e.charAt(n),s=t.charAt(n);if(r!==s)return $(r)===$(s)?M(r,s):$(r)?1:-1}return M(e.length,t.length)}function $(e){let t=e.charCodeAt(0);return t>=55296&&t<=57343}function B(e,t,r){return e.length===t.length&&e.every((e,n)=>r(e,t[n]))}let q="__name__";class z{constructor(e,t,r){void 0===t?t=0:t>e.length&&x(637,{offset:t,range:e.length}),void 0===r?r=e.length-t:r>e.length-t&&x(1746,{length:r,range:e.length-t}),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return 0===z.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof z?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,r=this.limit();t<r;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++){let r=z.compareSegments(e.get(n),t.get(n));if(0!==r)return r}return M(e.length,t.length)}static compareSegments(e,t){let r=z.isNumericId(e),n=z.isNumericId(t);return r&&!n?-1:!r&&n?1:r&&n?z.extractNumericId(e).compare(z.extractNumericId(t)):F(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return u.jz.fromString(e.substring(4,e.length-2))}}class Q extends z{construct(e,t,r){return new Q(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toStringWithLeadingSlash(){return`/${this.canonicalString()}`}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let r of e){if(r.indexOf("//")>=0)throw new I(S.INVALID_ARGUMENT,`Invalid segment (${r}). Paths must not contain // in them.`);t.push(...r.split("/").filter(e=>e.length>0))}return new Q(t)}static emptyPath(){return new Q([])}}let j=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class K extends z{construct(e,t,r){return new K(e,t,r)}static isValidIdentifier(e){return j.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),K.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===q}static keyField(){return new K([q])}static fromServerFormat(e){let t=[],r="",n=0,s=()=>{if(0===r.length)throw new I(S.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(r),r=""},i=!1;for(;n<e.length;){let t=e[n];if("\\"===t){if(n+1===e.length)throw new I(S.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[n+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new I(S.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);r+=t,n+=2}else"`"===t?i=!i:"."!==t||i?r+=t:s(),n++}if(s(),i)throw new I(S.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new K(t)}static emptyPath(){return new K([])}}class G{constructor(e){this.path=e}static fromPath(e){return new G(Q.fromString(e))}static fromName(e){return new G(Q.fromString(e).popFirst(5))}static empty(){return new G(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 G(new Q(e.slice()))}}function H(e,t,r){if(!r)throw new I(S.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function W(e){if(!G.isDocumentKey(e))throw new I(S.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Y(e){if(G.isDocumentKey(e))throw new I(S.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function J(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function X(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{var t;let r=(t=e).constructor?t.constructor.name:null;return r?`a custom ${r} object`:"an object"}}return"function"==typeof e?"a function":x(12329,{type:typeof e})}function Z(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new I(S.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let r=X(e);throw new I(S.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${r}`)}}return e}function ee(e,t){if(t<=0)throw new I(S.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}function et(e,t){let r={typeString:e};return t&&(r.value=t),r}function er(e,t){let r;if(!J(e))throw new I(S.INVALID_ARGUMENT,"JSON must be an object");for(let n in t)if(t[n]){let s=t[n].typeString,i="value"in t[n]?{value:t[n].value}:void 0;if(!(n in e)){r=`JSON missing required field: '${n}'`;break}let a=e[n];if(s&&typeof a!==s){r=`JSON field '${n}' must be a ${s}.`;break}if(void 0!==i&&a!==i.value){r=`Expected '${n}' field to equal '${i.value}'`;break}}if(r)throw new I(S.INVALID_ARGUMENT,r);return!0}class en{static now(){return en.fromMillis(Date.now())}static fromDate(e){return en.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),r=Math.floor((e-1e3*t)*1e6);return new en(t,r)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new I(S.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new I(S.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?M(this.nanoseconds,e.nanoseconds):M(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:en._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(er(e,en._jsonSchema))return new en(e.seconds,e.nanoseconds)}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}
1}en._jsonSchemaVersion="firestore/timestamp/1.0",en._jsonSchema={type:et("string",en._jsonSchemaVersion),seconds:et("number"),nanoseconds:et("number")};class es{static fromTimestamp(e){return new es(e)}static min(){return new es(new en(0,0))}static max(){return new es(new en(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}}class ei{constructor(e,t,r,n){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=n}}ei.UNKNOWN_ID=-1;class ea{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new ea(es.min(),G.empty(),-1)}static max(){return new ea(es.max(),G.empty(),-1)}}class eo{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function el(e){if(e.code!==S.FAILED_PRECONDITION||"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab."!==e.message)throw e;v("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&&x(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new eu((r,n)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(r,n)},this.catchCallback=e=>{this.wrapFailure(t,e).next(r,n)}})}toPromise(){return new Promise((e,t)=>{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,r)=>{t(e)})}static reject(e){return new eu((t,r)=>{r(e)})}static waitFor(e){return new eu((t,r)=>{let n=0,s=0,i=!1;e.forEach(e=>{++n,e.next(()=>{++s,i&&s===n&&t()},e=>r(e))}),i=!0,s===n&&t()})}static or(e){let t=eu.resolve(!1);for(let r of e)t=t.next(e=>e?eu.resolve(e):r());return t}static forEach(e,t){let r=[];return e.forEach((e,n)=>{r.push(t.call(this,e,n))}),this.waitFor(r)}static mapArray(e,t){return new eu((r,n)=>{let s=e.length,i=Array(s),a=0;for(let o=0;o<s;o++){let l=o;t(e[l]).next(e=>{i[l]=e,++a===s&&r(i)},e=>n(e))}})}static doWhile(e,t){return new eu((r,n)=>{let s=()=>{!0===e()?t().next(()=>{s()},n):r()};s()})}}function ec(e){return"IndexedDbTransactionError"===e.name}class eh{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ae(e),this.ue=e=>t.writeSequenceNumber(e))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ue&&this.ue(e),e}}eh.ce=-1;function ed(e){return 0===e&&1/e==-1/0}class em{constructor(e,t){this.comparator=e,this.root=t||ep.EMPTY}insert(e,t){return new em(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,ep.BLACK,null,null))}remove(e){return new em(this.comparator,this.root.remove(e,this.comparator).copy(null,null,ep.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let r=this.comparator(e,t.key);if(0===r)return t.value;r<0?t=t.left:r>0&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){let n=this.comparator(e,r.key);if(0===n)return t+r.left.size;n<0?r=r.left:(t+=r.left.size+1,r=r.right)}return -1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,r)=>(e(t,r),!1))}toString(){let e=[];return this.inorderTraversal((t,r)=>(e.push(`${t}:${r}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new ef(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new ef(this.root,e,this.comparator,!1)}getReverseIterator(){return new ef(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new ef(this.root,e,this.comparator,!0)}}class ef{constructor(e,t,r,n){this.isReverse=n,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?r(e.key,t):1,t&&n&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),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 ep{constructor(e,t,r,n,s){this.key=e,this.value=t,this.color=null!=r?r:ep.RED,this.left=null!=n?n:ep.EMPTY,this.right=null!=s?s:ep.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,s){return new ep(null!=e?e:this.key,null!=t?t:this.value,
1null!=r?r:this.color,null!=n?n:this.left,null!=s?s:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,r){let n=this,s=r(e,n.key);return(n=s<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===s?n.copy(null,t,null,null,null):n.copy(null,null,null,null,n.right.insert(e,t,r))).fixUp()}removeMin(){if(this.left.isEmpty())return ep.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 r,n=this;if(0>t(e,n.key))n.left.isEmpty()||n.left.isRed()||n.left.left.isRed()||(n=n.moveRedLeft()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed()&&(n=n.rotateRight()),n.right.isEmpty()||n.right.isRed()||n.right.left.isRed()||(n=n.moveRedRight()),0===t(e,n.key)){if(n.right.isEmpty())return ep.EMPTY;r=n.right.min(),n=n.copy(r.key,r.value,null,null,n.right.removeMin())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.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,ep.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,ep.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 x(43730,{key:this.key,value:this.value});if(this.right.isRed())throw x(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw x(27949);return e+ +!this.isRed()}}ep.EMPTY=null,ep.RED=!0,ep.BLACK=!1,ep.EMPTY=new class{constructor(){this.size=0}get key(){throw x(57766)}get value(){throw x(16141)}get color(){throw x(16727)}get left(){throw x(29726)}get right(){throw x(36894)}copy(e,t,r,n,s){return this}insert(e,t,r){return new ep(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 eg{constructor(e){this.comparator=e,this.data=new em(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,r)=>(e(t),!1))}forEachInRange(e,t){let r=this.data.getIteratorFrom(e[0]);for(;r.hasNext();){let n=r.getNext();if(this.comparator(n.key,e[1])>=0)return;t(n.key)}}forEachWhile(e,t){let r;for(r=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ey(this.data.getIterator())}getIteratorFrom(e){return new ey(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 eg)||this.size!==e.size)return!1;let t=this.data.getIterator(),r=e.data.getIterator();for(;t.hasNext();){let e=t.getNext().key,n=r.getNext().key;if(0!==this.comparator(e,n))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 eg(this.comparator);return t.data=e,t}}
1class ey{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class ew{constructor(e){this.fields=e,e.sort(K.comparator)}static empty(){return new ew([])}unionWith(e){let t=new eg(K.comparator);for(let e of this.fields)t=t.add(e);for(let r of e)t=t.add(r);return new ew(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return B(this.fields,e.fields,(e,t)=>e.isEqual(t))}}function ev(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function e_(e,t){for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}function eE(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class eT extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ex{constructor(e){this.binaryString=e}static fromBase64String(e){return new ex(function(e){try{return atob(e)}catch(e){throw"u">typeof DOMException&&e instanceof DOMException?new eT("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new ex(function(e){let t="";for(let r=0;r<e.length;++r)t+=String.fromCharCode(e[r]);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 r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return M(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ex.EMPTY_BYTE_STRING=new ex("");let eb=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function eN(e){if(N(!!e,39018),"string"==typeof e){let t=0,r=eb.exec(e);if(N(!!r,46558,{timestamp:e}),r[1]){let e=r[1];t=Number(e=(e+"000000000").substr(0,9))}return{seconds:Math.floor(new Date(e).getTime()/1e3),nanos:t}}return{seconds:eS(e.seconds),nanos:eS(e.nanos)}}function eS(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function eI(e){return"string"==typeof e?ex.fromBase64String(e):ex.fromUint8Array(e)}let eV="server_timestamp",eC="__type__",eA="__previous_value__",eD="__local_write_time__";function ek(e){return(e?.mapValue?.fields||{})[eC]?.stringValue===eV}function eR(e){let t=e.mapValue.fields[eA];return ek(t)?eR(t):t}function eL(e){let t=eN(e.mapValue.fields[eD].timestampValue);return new en(t.seconds,t.nanos)}class eU{constructor(e,t,r,n,s,i,a,o,l,u,c){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=n,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=u,this.apiKey=c}}let eO="(default)";class eP{constructor(e,t){this.projectId=e,this.database=t||eO}static empty(){return new eP("","")}get isDefaultDatabase(){return this.database===eO}isEqual(e){return e instanceof eP&&e.projectId===this.projectId&&e.database===this.database}}function eM(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new I(S.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new eP(e.options.projectId,t)}let eF="__type__",e$="__max__",eB={fields:{__type__:{stringValue:e$}}},eq="__vector__",ez="value",eQ={nullValue:"NULL_VALUE"},ej={booleanValue:!0},eK={booleanValue:!1};function eG(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?ek(e)?4:tt(e)?0x1fffffffffffff:e9(e)?10:11:x(28295,{value:e})}function eH(e,t,r){if(e===t)return!0;let n=eG(e);if(n!==eG(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return eL(e).isEqual(eL(t));case 3:if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let s=eN(e.timestampValue),i=eN(t.timestampValue);return s.seconds===i.seconds&&s.nanos===i.nanos;case 5:return e.stringValue===t.stringValue;case 6:return eI(e.bytesValue).isEqual(eI(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return eS(e.geoPointValue.latitude)===eS(t.geoPointValue.latitude)&&eS(e.geoPointValue.longitude)===eS(t.geoPointValue.longitude);case 2:let a,o;if("integerValue"in e&&"integerValue"in t)return eS(e.integerValue)===eS(t.integerValue);if("doubleValue"in e&&"doubleValue"in t)a=eS(e.doubleValue),o=eS(t.doubleValue);else{if(!r?.Ee)return!1;a=eS(e.integerValue??e.doubleValue),o=eS(t.integerValue??t.doubleValue)}return a===o?!!r?.he||ed(a)===ed(o):!!(void 0===r||r.Te)&&isNaN(a)&&isNaN(o);case 9:return B(e.arrayValue.values||[],t.arrayValue.values||[],(e,t)=>eH(e,t,r));case 10:case 11:let l=e.mapValue.fields||{},u=t.mapValue.fields||{};if(ev(l)!==ev(u))return!1;for(let e in l)if(l.hasOwnProperty(e)&&(void 0===u[e]||!eH(l[e],u[e],r)))return!1;return!0;default:return x(52216,{left:e})}}function eW(e,t){return void 0!==(e.values||[]).find(e=>eH(e,t))}function eY(e,t){var r,n,s,i,a,o;if(e===t)return 0;let l=eG(e),u=eG(t);if(l!==u)return M(l,u);switch(l){case 0:case 0x1fffffffffffff:return 0;case 1:return M(e.booleanValue,t.booleanValue);case 2:let c,h;return c=eS(e.integerValue||e.doubleValue),c<(h=eS(t.integerValue||t.doubleValue))?-1:c>h?1:c===h?0:isNaN(c)?isNaN(h)?0:-1:1;case 3:return eJ(e.timestampValue,t.timestampValue);case 4:return eJ(eL(e),eL(t));case 5:return F(e.stringValue,t.stringValue);case 6:let d,m;return r=e.bytesValue,n=t.bytesValue,d=eI(r),m=eI(n),d.compareTo(m);case 7:return function(e,t){let r=e.split("/"),n=t.split("/");for(let e=0;e<r.length&&e<n.length;e++){let t=M(r[e],n[e]);if(0!==t)return t}return M(r.length,n.length)}(e.referenceValue,t.referenceValue);case 8:let f;return s=e.geoPointValue,i=t.geoPointValue,0!==(f=M(eS(s.latitude),eS(i.latitude)))?f:M(eS(s.longitude),eS(i.longitude));case 9:return eX(e.arrayValue,t.arrayValue);case 10:let p,g,y,w,v;return a=e.mapValue,o=t.mapValue,p=a.fields||{},g=o.fields||{},y=p[ez]?.arrayValue,w=g[ez]?.arrayValue,0!==(v=M(y?.values?.length||0,w?.values?.length||0))?v:eX(y,w);case 11:return function(e,t){if(e===eB&&t===eB)return 0;if(e===eB)return 1;if(t===eB)return -1;let r=e.fields||{},n=Object.keys(r),s=t.fields||{},i=Object.keys(s);n.sort(),i.sort();for(let e=0;e<n.length&&e<i.length;++e){let t=F(n[e],i[e]);if(0!==t)return t;let a=eY(r[n[e]],s[i[e]]);if(0!==a)return a}return M(n.length,i.length)}(e.mapValue,t.mapValue);default:throw x(23264,{Pe:l})}}function eJ(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return M(e,t);let r=eN(e),n=eN(t),s=M(r.seconds,n.seconds);return 0!==s?s:M(r.nanos,n.nanos)}function eX(e,t){let r=e.values||[],n=t.values||[];for(let e=0;e<r.length&&e<n.length;++e){let t=eY(r[e],n[e]);if(void 0!==t&&0!==t)return t}return M(r.length,n.length)}function eZ(e){var t,r;let n;return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?(n=eN(e.timestampValue),`time(${n.seconds},${n.nanos}
1)`):"stringValue"in e?e.stringValue:"bytesValue"in e?eI(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,G.fromName(t).toString()):"geoPointValue"in e?(r=e.geoPointValue,`geo(${r.latitude},${r.longitude})`):"arrayValue"in e?function(e){let t="[",r=!0;for(let n of e.values||[])r?r=!1:t+=",",t+=eZ(n);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),r="{",n=!0;for(let s of t)n?n=!1:r+=",",r+=`${s}:${eZ(e.fields[s])}`;return r+"}"}(e.mapValue):x(61005,{value:e})}function e0(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function e1(e){return!!e&&"integerValue"in e}function e2(e){return!!e&&"doubleValue"in e}function e3(e){return e1(e)||e2(e)}function e4(e){return!!e&&"arrayValue"in e}function e6(e){return!!e&&"nullValue"in e}function e5(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function e8(e){return!!e&&"mapValue"in e}function e9(e){return(e?.mapValue?.fields||{})[eF]?.stringValue===eq}function e7(e){return(e?.mapValue?.fields||{})[ez]?.arrayValue}function te(e){if(e.geoPointValue)return{geoPointValue:{...e.geoPointValue}};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:{...e.timestampValue}};if(e.mapValue){let t={mapValue:{fields:{}}};return e_(e.mapValue.fields,(e,r)=>t.mapValue.fields[e]=te(r)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let r=0;r<(e.arrayValue.values||[]).length;++r)t.arrayValue.values[r]=te(e.arrayValue.values[r]);return t}return{...e}}function tt(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===e$}class tr{constructor(e){this.value=e}static empty(){return new tr({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let r=0;r<e.length-1;++r)if(!e8(t=(t.mapValue.fields||{})[e.get(r)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=te(t)}setAll(e){let t=K.emptyPath(),r={},n=[];e.forEach((e,s)=>{if(!t.isImmediateParentOf(s)){let e=this.getFieldsMap(t);this.applyChanges(e,r,n),r={},n=[],t=s.popLast()}e?r[s.lastSegment()]=te(e):n.push(s.lastSegment())});let s=this.getFieldsMap(t);this.applyChanges(s,r,n)}delete(e){let t=this.field(e.popLast());e8(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return eH(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let r=0;r<e.length;++r){let n=t.mapValue.fields[e.get(r)];e8(n)&&n.mapValue.fields||(n={mapValue:{fields:{}}},t.mapValue.fields[e.get(r)]=n),t=n}return t.mapValue.fields}applyChanges(e,t,r){for(let n of(e_(t,(t,r)=>e[t]=r),r))delete e[n]}clone(){return new tr(te(this.value))}}function tn(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:ed(t)?"-0":t}}function ts(e){return{integerValue:""+e}}function ti(e,t,r){return Number.isInteger(t)&&r?.preferIntegers||"number"==typeof t&&Number.isInteger(t)&&!ed(t)&&t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?ts(t):tn(e,t)}class ta{constructor(){this._=void 0}}function to(e,t){return e instanceof tf?e3(t)?t:{integerValue:0}:null}class tl extends ta{}class tu extends ta{constructor(e){super(),this.elements=e}}function tc(e,t){let r=tv(t);for(let t of e.elements)r.some(e=>eH(e,t))||r.push(t);return{arrayValue:{values:r}}}class th extends ta{constructor(e){super(),this.elements=e}}function td(e,t){let r=tv(t);for(let t of e.elements)r=r.filter(e=>!eH(e,t));return{arrayValue:{values:r}}}class tm extends ta{constructor(e,t){super(),this.serializer=e,this.Re=t}}class tf extends tm{}class tp extends tm{}class tg extends tm{}function ty(e,t,r){if(!e3(t))return e.Re;let n=r(tw(t),tw(e.Re));return e1(t)&&e1(e.Re)?ts(n):tn(e.serializer,n)}function tw(e){return eS(e.integerValue||e.doubleValue)}function tv(e){return e4(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class t_{constructor(e,t){this.field=e,this.transform=t}}class tE{constructor(e,t){this.version=e,this.transformResults=t}}class tT{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new tT}static exists(e){return new tT(void 0,e)}static updateTime(e){return new tT(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 tx(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class tb{}function tN(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new tR(e.key,tT.none()):new tV(e.key,e.data,tT.
1none());{let r=e.data,n=tr.empty(),s=new eg(K.comparator);for(let e of t.fields)if(!s.has(e)){let t=r.field(e);null===t&&e.length>1&&(e=e.popLast(),t=r.field(e)),null===t?n.delete(e):n.set(e,t),s=s.add(e)}return new tC(e.key,n,new ew(s.toArray()),tT.none())}}function tS(e,t,r,n){return e instanceof tV?function(e,t,r,n){if(!tx(e.precondition,t))return r;let s=e.value.clone(),i=tk(e.fieldTransforms,n,t);return s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null}(e,t,r,n):e instanceof tC?function(e,t,r,n){if(!tx(e.precondition,t))return r;let s=tk(e.fieldTransforms,n,t),i=t.data;return(i.setAll(tA(e)),i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null===r)?null:r.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,r,n):tx(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):r}function tI(e,t){var r,n;return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(r=e.fieldTransforms,n=t.fieldTransforms,!!(void 0===r&&void 0===n||!(!r||!n)&&B(r,n,(e,t)=>{var r,n;return e.field.isEqual(t.field)&&(r=e.transform,n=t.transform,r instanceof tu&&n instanceof tu||r instanceof th&&n instanceof th?B(r.elements,n.elements,eH):r instanceof tf&&n instanceof tf||r instanceof tp&&n instanceof tp||r instanceof tg&&n instanceof tg?eH(r.Re,n.Re):r instanceof tl&&n instanceof tl)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class tV extends tb{constructor(e,t,r,n=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=n,this.type=0}getFieldMask(){return null}}class tC extends tb{constructor(e,t,r,n,s=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=n,this.fieldTransforms=s,this.type=1}getFieldMask(){return this.fieldMask}}function tA(e){let t=new Map;return e.fieldMask.fields.forEach(r=>{if(!r.isEmpty()){let n=e.data.field(r);t.set(r,n)}}),t}function tD(e,t,r){let n=new Map;N(e.length===r.length,32656,{Ie:r.length,Ae:e.length});for(let i=0;i<r.length;i++){var s;let a=e[i],o=a.transform,l=t.data.field(a.field);n.set(a.field,(s=r[i],o instanceof tu?tc(o,l):o instanceof th?td(o,l):s))}return n}function tk(e,t,r){let n=new Map;for(let s of e){let e=s.transform,i=r.data.field(s.field);n.set(s.field,function(e,t,r){var n;let s,i,a;return e instanceof tl?(n=t,s={fields:{[eC]:{stringValue:eV},[eD]:{timestampValue:{seconds:r.seconds,nanos:r.nanoseconds}}}},n&&ek(n)&&(n=eR(n)),n&&(s.fields[eA]=n),{mapValue:s}):e instanceof tu?tc(e,t):e instanceof th?td(e,t):e instanceof tf?(a=tw(i=to(e,t))+tw(e.Re),e1(i)&&e1(e.Re)?ts(a):tn(e.serializer,a)):e instanceof tp?ty(e,t,Math.min):e instanceof tg?ty(e,t,Math.max):void 0}(e,i,t))}return n}class tR extends tb{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class tL extends tb{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class tU{constructor(e,t){this.position=e,this.inclusive=t}}function tO(e,t,r){let n=0;for(let s=0;s<e.position.length;s++){let i=t[s],a=e.position[s];if(n=i.field.isKeyField()?G.comparator(G.fromName(a.referenceValue),r.key):eY(a,r.data.field(i.field)),"desc"===i.dir&&(n*=-1),0!==n)break}return n}function tP(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 r=0;r<e.position.length;r++)if(!eH(e.position[r],t.position[r]))return!1;return!0}class tM{}class tF extends tM{constructor(e,t,r){super(),this.field=e,this.op=t,this.value=r}static create(e,t,r){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,r):new tz(e,t,r):"array-contains"===t?new tG(e,r):"in"===t?new tH(e,r):"not-in"===t?new tW(e,r):"array-contains-any"===t?new tY(e,r):new tF(e,t,r)}static createKeyFieldInFilter(e,t,r){return"in"===t?new tQ(e,r):new tj(e,r)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(eY(t,this.value)):null!==t&&eG(this.value)===eG(t)&&this.matchesComparison(eY(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 x(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class t$ extends tM{constructor(e,t){super(),this.filters=e,this.op=t,this.Ve=null}static create(e,t){return new t$(e,t)}matches(e){return tB(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.Ve||(this.Ve=this.filters.reduce((e,t)=>
1e.concat(t.getFlattenedFilters()),[])),this.Ve}getFilters(){return Object.assign([],this.filters)}}function tB(e){return"and"===e.op}function tq(e){for(let t of e.filters)if(t instanceof t$)return!1;return!0}class tz extends tF{constructor(e,t,r){super(e,t,r),this.key=G.fromName(r.referenceValue)}matches(e){let t=G.comparator(e.key,this.key);return this.matchesComparison(t)}}class tQ extends tF{constructor(e,t){super(e,"in",t),this.keys=tK("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class tj extends tF{constructor(e,t){super(e,"not-in",t),this.keys=tK("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function tK(e,t){return(t.arrayValue?.values||[]).map(e=>G.fromName(e.referenceValue))}class tG extends tF{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return e4(t)&&eW(t.arrayValue,this.value)}}class tH extends tF{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&eW(this.value.arrayValue,t)}}class tW extends tF{constructor(e,t){super(e,"not-in",t)}matches(e){if(eW(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!eW(this.value.arrayValue,t)}}class tY extends tF{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!e4(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>eW(this.value.arrayValue,e))}}class tJ{constructor(e,t="asc"){this.field=e,this.dir=t}}class tX{constructor(e,t,r,n,s,i,a){this.key=e,this.documentType=t,this.version=r,this.readTime=n,this.createTime=s,this.data=i,this.documentState=a}static newInvalidDocument(e){return new tX(e,0,es.min(),es.min(),es.min(),tr.empty(),0)}static newFoundDocument(e,t,r,n){return new tX(e,1,t,es.min(),r,n,0)}static newNoDocument(e,t){return new tX(e,2,t,es.min(),es.min(),tr.empty(),0)}static newUnknownDocument(e,t){return new tX(e,3,t,es.min(),es.min(),tr.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(es.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=tr.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=tr.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=es.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 tX&&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 tX(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 tZ{constructor(e,t=null,r=[],n=[],s=null,i=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=n,this.limit=s,this.startAt=i,this.endAt=a,this.de=null}}function t0(e,t=null,r=[],n=[],s=null,i=null,a=null){return new tZ(e,t,r,n,s,i,a)}function t1(e){if(null===e.de){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 tF)return t.field.canonicalString()+t.op.toString()+eZ(t.value);if(tq(t)&&tB(t))return t.filters.map(t=>e(t)).join(",");{let r=t.filters.map(t=>e(t)).join(",");return`${t.op}(${r})`}})(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=>eZ(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>eZ(e)).join(",")),e.de=t}return e.de}function t2(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let s=0;s<e.orderBy.length;s++){var r,n;if(r=e.orderBy[s],n=t.orderBy[s],!(r.dir===n.dir&&r.field.isEqual(n.field)))return!1}if(e.filters.length!==t.filters.length)return!1;for(let r=0;r<e.filters.length;r++)if(!function e(t,r){return t instanceof tF?r instanceof tF&&t.op===r.op&&t.field.isEqual(r.field)&&eH(t.value,r.value):t instanceof t$?r instanceof t$&&t.op===r.op&&t.filters.length===r.filters.length&&t.filters.reduce((t,n,s)=>t&&e(n,r.filters[s]),!0):void x(19439)}(e.filters[r],t.filters[r]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!tP(e.startAt,t.startAt)&&tP(e.endAt,t.endAt)}function t3(e){return!!e.isCorePipeline}function t4(e){return!!e.path&&G.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class t6{constructor(e,t=null,r=[],n=[],s=null,i="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=n,this.limit=s,this.limitType=i,this.startAt=a,this.endAt=o,this.fe=null,this.me=null,this.pe=null,this.startAt,this.endAt}}function t5(e){return new t6(e)}function t8(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 t9(e){return null!==e.collectionGroup}function t7(e){if(null===e.fe){let t;e.fe=[];let r=new Set;for(let t of e.explicitOrderBy)e.fe.push(t),r.add(t.field.canonicalString());let n=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";
1(t=new eg(K.comparator),e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t).forEach(t=>{r.has(t.canonicalString())||t.isKeyField()||e.fe.push(new tJ(t,n))}),r.has(K.keyField().canonicalString())||e.fe.push(new tJ(K.keyField(),n))}return e.fe}function re(e){return e.me||(e.me=function(e,t){if("F"===e.limitType)return t0(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 tJ(e.field,t)});let r=e.endAt?new tU(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new tU(e.startAt.position,e.startAt.inclusive):null;return t0(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)}}(e,t7(e))),e.me}function rt(e,t){let r=e.filters.concat([t]);return new t6(e.path,e.collectionGroup,e.explicitOrderBy.slice(),r,e.limit,e.limitType,e.startAt,e.endAt)}function rr(e,t){let r=e.explicitOrderBy.concat([t]);return new t6(e.path,e.collectionGroup,r,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}function rn(e,t,r){return new t6(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,r,e.startAt,e.endAt)}function rs(e,t){return new t6(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}function ri(e,t){return new t6(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}function ra(e){var t;let r;return`Query(target=${r=(t=re(e)).path.canonicalString(),null!==t.collectionGroup&&(r+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(r+=`, filters: [${t.filters.map(e=>(function e(t){return t instanceof tF?`${t.field.canonicalString()} ${t.op} ${eZ(t.value)}`:t instanceof t$?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),null==t.limit||(r+=", limit: "+t.limit),t.orderBy.length>0&&(r+=`, orderBy: [${t.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),t.startAt&&(r+=", startAt: ",r+=t.startAt.inclusive?"b:":"a:",r+=t.startAt.position.map(e=>eZ(e)).join(",")),t.endAt&&(r+=", endAt: ",r+=t.endAt.inclusive?"a:":"b:",r+=t.endAt.position.map(e=>eZ(e)).join(",")),`Target(${r})`}; limitType=${e.limitType})`}function ro(e,t){var r,n,s,i;let a,o,l;return t.isFoundDocument()&&(a=t.key.path,null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(a):G.isDocumentKey(e.path)?e.path.isEqual(a):e.path.isImmediateParentOf(a))&&function(e,t){for(let r of t7(e))if(!r.field.isKeyField()&&null===t.data.field(r.field))return!1;return!0}(e,t)&&function(e,t){for(let r of e.filters)if(!r.matches(t))return!1;return!0}(e,t)&&(r=e,n=t,(!r.startAt||(s=r.startAt,o=tO(s,t7(r),n),s.inclusive?!!(o<=0):!!(o<0)))&&(!r.endAt||(i=r.endAt,l=tO(i,t7(r),n),i.inclusive?!!(l>=0):!!(l>0))))}function rl(e){return(t,r)=>{let n=!1;for(let s of t7(e)){let e=function(e,t,r){var n;let s,i,a=e.field.isKeyField()?G.comparator(t.key,r.key):(n=e.field,s=t.data.field(n),i=r.data.field(n),null!==s&&null!==i?eY(s,i):x(42886));switch(e.dir){case"asc":return a;case"desc":return -1*a;default:return x(19790,{direction:e.dir})}}(s,t,r);if(0!==e)return e;n=n||s.field.isKeyField()}return 0}}class ru{constructor(e,t){this.count=e,this.unchangedNames=t}}function rc(e){if(void 0===e)return _("GRPC error has no .code"),S.UNKNOWN;switch(e){case s.OK:return S.OK;case s.CANCELLED:return S.CANCELLED;case s.UNKNOWN:return S.UNKNOWN;case s.DEADLINE_EXCEEDED:return S.DEADLINE_EXCEEDED;case s.RESOURCE_EXHAUSTED:return S.RESOURCE_EXHAUSTED;case s.INTERNAL:return S.INTERNAL;case s.UNAVAILABLE:return S.UNAVAILABLE;case s.UNAUTHENTICATED:return S.UNAUTHENTICATED;case s.INVALID_ARGUMENT:return S.INVALID_ARGUMENT;case s.NOT_FOUND:return S.NOT_FOUND;case s.ALREADY_EXISTS:return S.ALREADY_EXISTS;case s.PERMISSION_DENIED:return S.PERMISSION_DENIED;case s.FAILED_PRECONDITION:return S.FAILED_PRECONDITION;case s.ABORTED:return S.ABORTED;case s.OUT_OF_RANGE:return S.OUT_OF_RANGE;case s.UNIMPLEMENTED:return S.UNIMPLEMENTED;case s.DATA_LOSS:return S.DATA_LOSS;default:return x(39323,{code:e})}}(i=s||(s={}))[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.UNIMPLEMENT
1ED=12]="UNIMPLEMENTED",i[i.INTERNAL=13]="INTERNAL",i[i.UNAVAILABLE=14]="UNAVAILABLE",i[i.DATA_LOSS=15]="DATA_LOSS";class rh{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),r=this.inner[t];if(void 0!==r){for(let[t,n]of r)if(this.equalsFn(t,e))return n}}has(e){return void 0!==this.get(e)}set(e,t){let r=this.mapKeyFn(e),n=this.inner[r];if(void 0===n)return this.inner[r]=[[e,t]],void this.innerSize++;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return void(n[r]=[e,t]);n.push([e,t]),this.innerSize++}delete(e){let t=this.mapKeyFn(e),r=this.inner[t];if(void 0===r)return!1;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return 1===r.length?delete this.inner[t]:r.splice(n,1),this.innerSize--,!0;return!1}forEach(e){e_(this.inner,(t,r)=>{for(let[t,n]of r)e(t,n)})}isEmpty(){return eE(this.inner)}size(){return this.innerSize}}let rd=new em(G.comparator),rm=new em(G.comparator);function rf(...e){let t=rm;for(let r of e)t=t.insert(r.key,r);return t}function rp(e){let t=rm;return e.forEach((e,r)=>t=t.insert(e,r.overlayedDocument)),t}function rg(){return new rh(e=>e.toString(),(e,t)=>e.isEqual(t))}let ry=new em(G.comparator),rw=new eg(G.comparator);function rv(...e){let t=rw;for(let r of e)t=t.add(r);return t}let r_=new eg(M),rE=new u.jz([0xffffffff,0xffffffff],0);function rT(e){let t=(new TextEncoder).encode(e),r=new u.VV;return r.update(t),new Uint8Array(r.digest())}function rx(e){let t=new DataView(e.buffer),r=t.getUint32(0,!0),n=t.getUint32(4,!0),s=t.getUint32(8,!0),i=t.getUint32(12,!0);return[new u.jz([r,n],0),new u.jz([s,i],0)]}class rb{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||t>=8)throw new rN(`Invalid padding: ${t}`);if(r<0||e.length>0&&0===this.hashCount)throw new rN(`Invalid hash count: ${r}`);if(0===e.length&&0!==t)throw new rN(`Invalid padding when bitmap length is 0: ${t}`);this.ge=8*e.length-t,this.ye=u.jz.fromNumber(this.ge)}we(e,t,r){let n=e.add(t.multiply(u.jz.fromNumber(r)));return 1===n.compare(rE)&&(n=new u.jz([n.getBits(0),n.getBits(1)],0)),n.modulo(this.ye).toNumber()}be(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.ge)return!1;let[t,r]=rx(rT(e));for(let e=0;e<this.hashCount;e++){let n=this.we(t,r,e);if(!this.be(n))return!1}return!0}static create(e,t,r){let n=new rb(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);return r.forEach(e=>n.insert(e)),n}insert(e){if(0===this.ge)return;let[t,r]=rx(rT(e));for(let e=0;e<this.hashCount;e++){let n=this.we(t,r,e);this.ve(n)}}ve(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class rN extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class rS{constructor(e,t,r,n,s,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=r,this.documentUpdates=n,this.augmentedDocumentUpdates=s,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,r){let n=new Map;return n.set(e,rI.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new rS(es.min(),n,new em(M),rd,rd,rv())}}class rI{constructor(e,t,r,n,s){this.resumeToken=e,this.current=t,this.addedDocuments=r,this.modifiedDocuments=n,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t,r){return new rI(r,t,rv(),rv(),rv())}}class rV{constructor(e,t,r,n){this.Se=e,this.removedTargetIds=t,this.key=r,this.De=n}}class rC{constructor(e,t){this.targetId=e,this.xe=t}}class rA{constructor(e,t,r=ex.EMPTY_BYTE_STRING,n=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=n}}class rD{constructor(e){this.targetId=e,this.Ce=0,this.Fe=rU(),this.Oe=ex.EMPTY_BYTE_STRING,this.Me=!1,this.Ne=!0}get current(){return this.Me}get resumeToken(){return this.Oe}get Le(){return 0!==this.Ce}get Be(){return this.Ne}Ue(e){e.approximateByteSize()>0&&(this.Ne=!0,this.Oe=e)}ke(){let e=rv(),t=rv(),r=rv();return this.Fe.forEach((n,s)=>{switch(s){case 0:e=e.add(n);break;case 2:t=t.add(n);break;case 1:r=r.add(n);break;default:x(38017,{changeType:s})}}),new rI(this.Oe,this.Me,e,t,r)}qe(){this.Ne=!1,this.Fe=rU()}$e(e,t){this.Ne=!0,this.Fe=this.Fe.insert(e,t)}Ke(e){this.Ne=!0,this.Fe=this.Fe.remove(e)}We(){this.Ce+=1}
1Qe(){this.Ce-=1,N(this.Ce>=0,3241,{Ce:this.Ce,targetId:this.targetId})}Ge(){this.Ne=!0,this.Me=!0}}let rk="WatchChangeAggregator";class rR{constructor(e){this.ze=e,this.je=new Map,this.He=rd,this.Je=rL(),this.Ye=rd,this.Ze=rL(),this.Xe=new em(M)}et(e){for(let t of e.Se)e.De&&e.De.isFoundDocument()?this.tt(t,e.De):this.nt(t,e.key,e.De);for(let t of e.removedTargetIds)this.nt(t,e.key,e.De)}rt(e){this.forEachTarget(e,t=>{let r=this.je.get(t);if(r)switch(e.state){case 0:this.it(t)&&r.Ue(e.resumeToken);break;case 1:r.Qe(),r.Le||r.qe(),r.Ue(e.resumeToken);break;case 2:r.Qe(),r.Le||this.removeTarget(t);break;case 3:this.it(t)&&(r.Ge(),r.Ue(e.resumeToken));break;case 4:this.it(t)&&(this.st(t),r.Ue(e.resumeToken));break;default:x(56790,{state:e.state})}else v(rk,`handleTargetChange received targetChange for untracked target ID (${t}) with state (${e.state})`)})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.je.forEach((e,r)=>{this.it(r)&&t(r)})}_t(e){return t3(e)?"documents"===e.getPipelineSourceType()&&1===e.getPipelineDocuments()?.length:t4(e)}ot(e){let t=e.targetId,r=e.xe.count,n=this.ut(t);if(n){let s=n.target;if(this._t(s))if(0===r){let e=new G(t3(s)?Q.fromString(s.getPipelineDocuments()[0]):s.path);this.nt(t,e,tX.newNoDocument(e,es.min()))}else N(1===r,20013,"Single document existence filter with count: "+r);else{let n=this.ct(t);if(n!==r){let r=this.lt(e),s=r?this.Et(r,e,n):1;0!==s&&(this.st(t),this.Xe=this.Xe.insert(t,2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}lt(e){let t,r,n=e.xe.unchangedNames;if(!n||!n.bits)return null;let{bits:{bitmap:s="",padding:i=0},hashCount:a=0}=n;try{t=eI(s).toUint8Array()}catch(e){if(e instanceof eT)return E("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{r=new rb(t,i,a)}catch(e){return E(e instanceof rN?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===r.ge?null:r}Et(e,t,r){return 2*(t.xe.count!==r-this.Pt(e,t.targetId))}Pt(e,t){let r=this.ze.getRemoteKeysForTarget(t),n=0;return r.forEach(r=>{let s=this.ze.Tt(),i=`projects/${s.projectId}/databases/${s.database}/documents/${r.path.canonicalString()}`;e.mightContain(i)||(this.nt(t,r,null),n++)}),n}Rt(e){let t=new Map;this.je.forEach((r,n)=>{let s=this.ut(n);if(s){if(r.current&&this._t(s.target)){let t=new G(t3(s.target)?Q.fromString(s.target.getPipelineDocuments()[0]):s.target.path);this.It(t).has(n)||this.At(n,t)||this.nt(n,t,tX.newNoDocument(t,e))}r.Be&&(t.set(n,r.ke()),r.qe())}});let r=rv();this.Ze.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{let t=this.ut(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1,!1)}),n&&(r=r.add(e))}),this.He.forEach((t,r)=>r.setReadTime(e)),this.Ye.forEach((t,r)=>r.setReadTime(e));let n=new rS(e,t,this.Xe,this.He,this.Ye,r);return this.He=rd,this.Je=rL(),this.Ye=rd,this.Ze=rL(),this.Xe=new em(M),n}tt(e,t){let r=this.je.get(e);if(!r||!this.it(e))return void v(rk,`addDocumentToTarget received document for unknown inactive target (${e})`);let n=2*!!this.At(e,t.key);r.$e(t.key,n),t3(this.ut(e).target)&&"exact"!==this.ut(e).target.getPipelineFlavor()?this.Ye=this.Ye.insert(t.key,t):this.He=this.He.insert(t.key,t),this.Je=this.Je.insert(t.key,this.It(t.key).add(e)),this.Ze=this.Ze.insert(t.key,this.Vt(t.key).add(e))}nt(e,t,r){let n=this.je.get(e);n&&this.it(e)?(this.At(e,t)?n.$e(t,1):n.Ke(t),this.Ze=this.Ze.insert(t,this.Vt(t).delete(e)),this.Ze=this.Ze.insert(t,this.Vt(t).add(e)),r&&(t3(this.ut(e).target)&&"exact"!==this.ut(e).target.getPipelineFlavor()?this.Ye=this.Ye.insert(t,r):this.He=this.He.insert(t,r))):v(r
1k,`removeDocumentFromTarget received document for unknown or inactive target (${e})`)}removeTarget(e){this.je.delete(e)}ct(e){let t=this.je.get(e);if(!t)return 0;let r=t.ke();return this.ze.getRemoteKeysForTarget(e).size+r.addedDocuments.size-r.removedDocuments.size}We(e){let t=this.je.get(e);t||(v(rk,`recordPendingTargetRequest set up tracking for target ID ${e}`),t=new rD(e),this.je.set(e,t)),t.We()}Vt(e){let t=this.Ze.get(e);return t||(t=new eg(M),this.Ze=this.Ze.insert(e,t)),t}It(e){let t=this.Je.get(e);return t||(t=new eg(M),this.Je=this.Je.insert(e,t)),t}it(e){let t=null!==this.ut(e);return t||v(rk,"Detected inactive target",e),t}ut(e){let t=this.je.get(e);return void 0===t||t.Le?null:this.ze.dt(e)}st(e){this.je.set(e,new rD(e)),this.ze.getRemoteKeysForTarget(e).forEach(t=>{this.nt(e,t,null)})}At(e,t){return this.ze.getRemoteKeysForTarget(e).has(t)}}function rL(){return new em(G.comparator)}function rU(){return new em(G.comparator)}let rO={asc:"ASCENDING",desc:"DESCENDING"},rP={"<":"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 rF{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function r$(e,t){return e.useProto3Json||null==t?t:{value:t}}function rB(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 rq(e){let t=eN(e);return new en(t.seconds,t.nanos)}function rz(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function rQ(e,t){return rB(e,t.toTimestamp())}function rj(e){return N(!!e,49232),es.fromTimestamp(rq(e))}function rK(e,t){return rG(e,t).canonicalString()}function rG(e,t){let r=new Q(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?r:r.child(t)}function rH(e){let t=Q.fromString(e);return N(r3(t),10190,{key:t.toString()}),t}function rW(e,t){return rK(e.databaseId,t.path)}function rY(e,t){let r=rH(t);if(r.get(1)!==e.databaseId.projectId)throw new I(S.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+r.get(1)+" vs "+e.databaseId.projectId);if(r.get(3)!==e.databaseId.database)throw new I(S.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+r.get(3)+" vs "+e.databaseId.database);return new G(rZ(r))}function rJ(e,t){return rK(e.databaseId,t)}function rX(e){return new Q(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function rZ(e){return N(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function r0(e,t,r){return{name:rW(e,t),fields:r.value.mapValue.fields}}function r1(e){return{fieldPath:e.canonicalString()}}function r2(e){return K.fromServerFormat(e.fieldPath)}function r3(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function r4(e){return!!e&&"function"==typeof e._toProto&&"ProtoValue"===e._protoValueType}function r6(e,t){let r={fields:{}};return t.forEach((t,n)=>{if("string"!=typeof n)throw Error(`Cannot encode map with non-string key: ${n}`);r.fields[n]=t._toProto(e)}),{mapValue:r}}function r5(e){return{stringValue:e}}function r8(e){return new rF(e,!0)}class r9{constructor(e){this._byteString=e}static fromBase64String(e){try{return new r9(ex.fromBase64String(e))}catch(e){throw new I(S.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new r9(ex.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:r9._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(er(e,r9._jsonSchema))return r9.fromBase64String(e.bytes)}}r9._jsonSchemaVersion="firestore/bytes/1.0",r9._jsonSchema={type:et("string",r9._jsonSchemaVersion),bytes:et("string")};class r7{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new I(S.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new K(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class ne{constructor(e){this._methodName=e}}class nt{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new I(S.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new I(S.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return M(this._lat,e._lat)||M(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:nt._jsonSchemaVersion}}static fromJSON(e){if(er(e,nt._jsonSchema))return new nt(e.latitude,e.longitude)}}function nr(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}nt._jsonSchemaVersion="firestore/geoPoint/1.0",nt._jsonSchema={type:et("string",nt._jsonSchemaVersion),latitude:et("number"),longitude:et("number")};
1class nn{bt(e){}shutdown(){}}let ns="ConnectivityMonitor";class ni{constructor(){this.vt=()=>this.St(),this.Dt=()=>this.xt(),this.Ct=[],this.Ft()}bt(e){this.Ct.push(e)}shutdown(){window.removeEventListener("online",this.vt),window.removeEventListener("offline",this.Dt)}Ft(){window.addEventListener("online",this.vt),window.addEventListener("offline",this.Dt)}St(){for(let e of(v(ns,"Network connectivity changed: AVAILABLE"),this.Ct))e(0)}xt(){for(let e of(v(ns,"Network connectivity changed: UNAVAILABLE"),this.Ct))e(1)}static C(){return"u">typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let na=null;function no(){return null===na?na=0x10000000+Math.round(0x80000000*Math.random()):na++,"0x"+na.toString(16)}let nl="RestConnection",nu={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"};class nc{get Ot(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),n=encodeURIComponent(this.databaseId.database);this.Mt=t+"://"+e.host,this.Nt=`projects/${r}/databases/${n}`,this.Lt=this.databaseId.database===eO?`project_id=${r}`:`project_id=${r}&database_id=${n}`}Bt(e,t,r,n,s){let i=no(),a=this.Ut(e,t.toUriEncodedString());v(nl,`Sending RPC '${e}' ${i}:`,a,r);let o={"google-cloud-resource-prefix":this.Nt,"x-goog-request-params":this.Lt};this.kt(o,n,s);let{host:u}=new URL(a),c=(0,l.zJ)(u);return this.qt(e,a,o,r,c).then(t=>(v(nl,`Received RPC '${e}' ${i}: `,t),t),t=>{throw E(nl,`RPC '${e}' ${i} failed with error: `,t,"url: ",a,"request:",r),t})}$t(e,t,r,n,s,i){return this.Bt(e,t,r,n,s)}kt(e,t,r){e["X-Goog-Api-Client"]="gl-js/ fire/"+p,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((t,r)=>e[r]=t),r&&r.headers.forEach((t,r)=>e[r]=t)}Ut(e,t){let r=nu[e],n=`${this.Mt}/v1/${t}:${r}`;return this.databaseInfo.apiKey&&(n=`${n}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),n}terminate(){}}class nh{constructor(e){this.Kt=e.Kt,this.Wt=e.Wt}Qt(e){this.Gt=e}zt(e){this.jt=e}Ht(e){this.Jt=e}onMessage(e){this.Yt=e}close(){this.Wt()}send(e){this.Kt(e)}Zt(){this.Gt()}Xt(){this.jt()}en(e){this.Jt(e)}tn(e){this.Yt(e)}}let nd="WebChannelConnection",nm=(e,t,r)=>{e.listen(t,e=>{try{r(e)}catch(e){setTimeout(()=>{throw e},0)}})};class nf extends nc{constructor(e){super(e),this.nn=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}static rn(){nf.sn||(nm((0,h.Ao)(),h.Jh.STAT_EVENT,e=>{e.stat===h.ro.PROXY?v(nd,"STAT_EVENT: detected buffering proxy"):e.stat===h.ro.NOPROXY&&v(nd,"STAT_EVENT: detected no buffering proxy")}),nf.sn=!0)}qt(e,t,r,n,s){let i=no();return new Promise((s,a)=>{let o=new h.ZS;o.setWithCredentials(!0),o.listenOnce(h.Bx.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case h.O4.NO_ERROR:let t=o.getResponseJson();v(nd,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case h.O4.TIMEOUT:v(nd,`RPC '${e}' ${i} timed out`),a(new I(S.DEADLINE_EXCEEDED,"Request time out"));break;case h.O4.HTTP_ERROR:let r=o.getStatus();if(v(nd,`RPC '${e}' ${i} failed with status:`,r,"response text:",o.getResponseText()),r>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);let t=e?.error;if(t&&t.status&&t.message){let e,r=(e=t.status.toLowerCase().replace(/_/g,"-"),Object.values(S).indexOf(e)>=0?e:S.UNKNOWN);a(new I(r,t.message))}else a(new I(S.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new I(S.UNAVAILABLE,"Connection failed."));break;default:x(9055,{_n:e,streamId:i,an:o.getLastErrorCode(),un:o.getLastError()})}}finally{v(nd,`RPC '${e}' ${i} completed.`)}});let l=JSON.stringify(n);v(nd,`RPC '${e}' ${i} sending request:`,n),o.send(t,"POST",l,r,15)})}cn(e,t,r){let n=no(),i=[this.Mt,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=this.createWebChannelTransport(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`}
1,sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(o.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(o.useFetchStreams=!0),this.kt(o.initMessageHeaders,t,r),o.encodeInitMessageHeaders=!0;let u=i.join("");v(nd,`Creating RPC '${e}' stream ${n}: ${u}`,o);let c=a.createWebChannel(u,o);this.En(c);let d=!1,m=!1,f=new nh({Kt:t=>{m?v(nd,`Not sending because RPC '${e}' stream ${n} is closed:`,t):(d||(v(nd,`Opening RPC '${e}' stream ${n} transport.`),c.open(),d=!0),v(nd,`RPC '${e}' stream ${n} sending:`,t),c.send(t))},Wt:()=>c.close()});return nm(c,h.iO.EventType.OPEN,()=>{m||(v(nd,`RPC '${e}' stream ${n} transport opened.`),f.Zt())}),nm(c,h.iO.EventType.CLOSE,()=>{m||(m=!0,v(nd,`RPC '${e}' stream ${n} transport closed`),f.en(),this.hn(c))}),nm(c,h.iO.EventType.ERROR,t=>{m||(m=!0,E(nd,`RPC '${e}' stream ${n} transport errored. Name:`,t.name,"Message:",t.message),f.en(new I(S.UNAVAILABLE,"The operation could not be completed")))}),nm(c,h.iO.EventType.MESSAGE,t=>{if(!m){let r=t.data[0];N(!!r,16349);let i=r?.error||r[0]?.error;if(i){v(nd,`RPC '${e}' stream ${n} received error:`,i);let t=i.status,r=function(e){let t=s[e];if(void 0!==t)return rc(t)}(t),a=i.message;"NOT_FOUND"===t&&a.includes("database")&&a.includes("does not exist")&&a.includes(this.databaseId.database)&&E(`Database '${this.databaseId.database}' not found. Please check your project configuration.`),void 0===r&&(r=S.INTERNAL,a="Unknown error status: "+t+" with message "+i.message),m=!0,f.en(new I(r,a)),c.close()}else v(nd,`RPC '${e}' stream ${n} received:`,r),f.tn(r)}}),nf.rn(),setTimeout(()=>{f.Xt()},0),f}terminate(){this.nn.forEach(e=>e.close()),this.nn=[]}En(e){this.nn.push(e)}hn(e){this.nn=this.nn.filter(t=>t===e)}kt(e,t,r){super.kt(e,t,r),this.databaseInfo.apiKey&&(e["x-goog-api-key"]=this.databaseInfo.apiKey)}createWebChannelTransport(){return(0,h.fF)()}}nf.sn=!1;class np{constructor(e,t,r=1e3,n=1.5,s=6e4){this.Tn=e,this.timerId=t,this.Pn=r,this.Rn=n,this.In=s,this.An=0,this.Vn=null,this.dn=Date.now(),this.reset()}reset(){this.An=0}fn(){this.An=this.In}mn(e){this.cancel();let t=Math.floor(this.An+this.pn()),r=Math.max(0,Date.now()-this.dn),n=Math.max(0,t-r);n>0&&v("ExponentialBackoff",`Backing off for ${n} ms (base delay: ${this.An} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.Vn=this.Tn.enqueueAfterDelay(this.timerId,n,()=>(this.dn=Date.now(),e())),this.An*=this.Rn,this.An<this.Pn&&(this.An=this.Pn),this.An>this.In&&(this.An=this.In)}gn(){null!==this.Vn&&(this.Vn.skipDelay(),this.Vn=null)}cancel(){null!==this.Vn&&(this.Vn.cancel(),this.Vn=null)}pn(){return(Math.random()-.5)*this.An}}let ng="PersistentStream";class ny{constructor(e,t,r,n,s,i,a,o){this.Tn=e,this.yn=r,this.wn=n,this.connection=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.bn=0,this.vn=null,this.Sn=null,this.stream=null,this.Dn=0,this.xn=new np(e,t)}Cn(){return 1===this.state||5===this.state||this.Fn()}Fn(){return 2===this.state||3===this.state}start(){this.Dn=0,4!==this.state?this.auth():this.On()}async stop(){this.Cn()&&await this.close(0)}Mn(){this.state=0,this.xn.reset()}Nn(){this.Fn()&&null===this.vn&&(this.vn=this.Tn.enqueueAfterDelay(this.yn,6e4,()=>this.Ln()))}Bn(e){this.Un(),this.stream.send(e)}async Ln(){if(this.Fn())return this.close(0)}Un(){this.vn&&(this.vn.cancel(),this.vn=null)}kn(){this.Sn&&(this.Sn.cancel(),this.Sn=null)}async close(e,t){this.Un(),this.kn(),this.xn.cancel(),this.bn++,4!==e?this.xn.reset():t&&t.code===S.RESOURCE_EXHAUSTED?(_(t.toString()),_("Using maximum backoff delay to prevent overloading the backend."),this.xn.fn()):t&&t.code===S.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.qn(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ht(t)}qn(){}auth(){this.state=1;
1let e=this.$n(this.bn),t=this.bn;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,r])=>{this.bn===t&&this.Kn(e,r)},t=>{e(()=>{let e=new I(S.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Wn(e)})})}Kn(e,t){let r=this.$n(this.bn);this.stream=this.Qn(e,t),this.stream.Qt(()=>{r(()=>this.listener.Qt())}),this.stream.zt(()=>{r(()=>(this.state=2,this.Sn=this.Tn.enqueueAfterDelay(this.wn,1e4,()=>(this.Fn()&&(this.state=3),Promise.resolve())),this.listener.zt()))}),this.stream.Ht(e=>{r(()=>this.Wn(e))}),this.stream.onMessage(e=>{r(()=>1==++this.Dn?this.Gn(e):this.onNext(e))})}On(){this.state=5,this.xn.mn(async()=>{this.state=0,this.start()})}Wn(e){return v(ng,`close with error: ${e}`),this.stream=null,this.close(4,e)}$n(e){return t=>{this.Tn.enqueueAndForget(()=>this.bn===e?t():(v(ng,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class nw extends ny{constructor(e,t,r,n,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,n,i),this.serializer=s}Qn(e,t){return this.connection.cn("Listen",e,t)}Gn(e){return this.onNext(e)}onNext(e){this.xn.reset();let t=function(e,t){let r;if("targetChange"in t){var n,s;t.targetChange;let i="NO_CHANGE"===(n=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===n?1:"REMOVE"===n?2:"CURRENT"===n?3:"RESET"===n?4:x(39313,{state:n}),a=t.targetChange.targetIds||[],o=(s=t.targetChange.resumeToken,e.useProto3Json?(N(void 0===s||"string"==typeof s,58123),ex.fromBase64String(s||"")):(N(void 0===s||s instanceof m||s instanceof Uint8Array,16193),ex.fromUint8Array(s||new Uint8Array))),l=t.targetChange.cause;r=new rA(i,a,o,l&&new I(void 0===l.code?S.UNKNOWN:rc(l.code),l.message||"")||null)}else if("documentChange"in t){t.documentChange;let n=t.documentChange;n.document,n.document.name,n.document.updateTime;let s=rY(e,n.document.name),i=rj(n.document.updateTime),a=n.document.createTime?rj(n.document.createTime):es.min(),o=new tr({mapValue:{fields:n.document.fields}}),l=tX.newFoundDocument(s,i,a,o);r=new rV(n.targetIds||[],n.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let n=t.documentDelete;n.document;let s=rY(e,n.document),i=n.readTime?rj(n.readTime):es.min(),a=tX.newNoDocument(s,i);r=new rV([],n.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let n=t.documentRemove;n.document;let s=rY(e,n.document);r=new rV([],n.removedTargetIds||[],s,null)}else{if(!("filter"in t))return x(11601,{ft:t});{t.filter;let e=t.filter;e.targetId;let{count:n=0,unchangedNames:s}=e,i=new ru(n,s);r=new rC(e.targetId,i)}}return r}(this.serializer,e),r=function(e){if(!("targetChange"in e))return es.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?es.min():t.readTime?rj(t.readTime):es.min()}(e);return this.listener.zn(t,r)}jn(e){let t,r={};r.database=rX(this.serializer),r.addTarget=function(e,t){var r,n;let s,i,a,o,l,u,c,h=t.target;if((s=t3(h)?{pipelineQuery:{structuredPipeline:{pipeline:{stages:h.stages.map(t=>t._toProto(e))}}}}:t4(h)?{documents:{documents:[rJ(e,h.path)]}}:{query:(a={structuredQuery:{}},o=h.path,null!==h.collectionGroup?(i=o,a.structuredQuery.from=[{collectionId:h.collectionGroup,allDescendants:!0}]):(i=o.popLast(),a.structuredQuery.from=[{collectionId:o.lastSegment()}]),a.parent=rJ(e,i),(l=function(e){if(0!==e.length)return function e(t){var r;let n;return t instanceof tF?function(e){if("=="===e.op){if(e5(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NAN"}};if(e6(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(e5(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NOT_NAN"}};if(e6(e.value))return{unaryFilter:{field:r1(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:r1(e.field),op:rP[e.op],value:e.value}}}(t):t instanceof t$?1===(n=(r=t).getFilters().map(t=>e(t))).length?n[0]:{compositeFilter:{op:rM[r.op],filters:n}}:x(54877,{filter:t})}(t$.create(e,"and"))}(h.filters))&&(a.structuredQuery.where=l),(u=function(e){if(0!==e.length)return e.map(e=>({field:r1(e.field),direction:rO[e.dir]}))}(h.orderBy))&&(a.structuredQuery.orderBy=u),null!==(c=r$(e,h.limit))&&(a.structuredQuery.limit=c),h.startAt&&(a.structuredQuery.startAt={before:(r=h.startAt).inclusive,values:r.position}),h.endAt&&(a.structuredQuery.endAt={before:!(n=h.endAt).inclusive,values:n.position}),{yt:a,parent:i}).yt}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){s.resumeToken=rz(e,t.resumeToken);let r=r$(e,t.expectedCount);null!==r&&(s.expectedCount=r)}else if(t.snapshotVersion.compareTo(es.min())>0){s.readTime=rB(e,t.snapshotVersion.toTimestamp());let r=r$(e,t.expectedCount);null!==r&&(s.expectedCount=r)}return s}(this.serializer,e);let n=(this.serializer,null==(t=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 x(28987,{purpose:e})}}(e.purpose))?null:{"goog-listen-tags":t});n&&(r.labels=n),this.Bn(r)}Hn(e){let t={};t.database=rX(this.serializer),t.removeTarget=e,this.Bn(t)}}class nv extends ny{constructor(e,t,r,n,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,n,i),this.serializer
1=s}get Jn(){return this.Dn>0}start(){this.lastStreamToken=void 0,super.start()}qn(){this.Jn&&this.Yn([])}Qn(e,t){return this.connection.cn("Write",e,t)}Gn(e){return N(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,N(!e.writeResults||0===e.writeResults.length,55816),this.listener.Zn()}onNext(e){var t,r;N(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.xn.reset();let n=(t=e.writeResults,r=e.commitTime,t&&t.length>0?(N(void 0!==r,14353),t.map(e=>{let t;return(t=e.updateTime?rj(e.updateTime):rj(r)).isEqual(es.min())&&(t=rj(r)),new tE(t,e.transformResults||[])})):[]),s=rj(e.commitTime);return this.listener.Xn(s,n)}er(){let e={};e.database=rX(this.serializer),this.Bn(e)}Yn(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>(function(e,t){var r,n;let s;if(t instanceof tV)s={update:r0(e,t.key,t.value)};else if(t instanceof tR)s={delete:rW(e,t.key)};else if(t instanceof tC){let r;s={update:r0(e,t.key,t.data),updateMask:(n=t.fieldMask,r=[],n.fields.forEach(e=>r.push(e.canonicalString())),{fieldPaths:r})}}else{if(!(t instanceof tL))return x(16599,{gt:t.type});s={verify:rW(e,t.key)}}return t.fieldTransforms.length>0&&(s.updateTransforms=t.fieldTransforms.map(e=>(function(e){let t=e.transform;if(t instanceof tl)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof tu)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof th)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof tf)return{fieldPath:e.field.canonicalString(),increment:t.Re};if(t instanceof tp)return{fieldPath:e.field.canonicalString(),minimum:t.Re};if(t instanceof tg)return{fieldPath:e.field.canonicalString(),maximum:t.Re};throw x(20930,{transform:e.transform})})(e))),t.precondition.isNone||(s.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:rQ(e,r.updateTime)}:void 0!==r.exists?{exists:r.exists}:x(27497)),s})(this.serializer,e))};this.Bn(t)}}class n_{}class nE extends n_{constructor(e,t,r,n){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=n,this.tr=!1}nr(){if(this.tr)throw new I(S.FAILED_PRECONDITION,"The client has already been terminated.")}Bt(e,t,r,n){return this.nr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,i])=>this.connection.Bt(e,rG(t,r),n,s,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===S.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new I(S.UNKNOWN,e.toString())})}$t(e,t,r,n,s){return this.nr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,a])=>this.connection.$t(e,rG(t,r),n,i,a,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===S.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new I(S.UNKNOWN,e.toString())})}terminate(){this.tr=!0,this.connection.terminate()}}let nT=new Map,nx={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class nb{static withCacheSize(e){return new nb(e,nb.DEFAULT_COLLECTION_PERCENTILE,nb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}nb.DEFAULT_COLLECTION_PERCENTILE=10,nb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,nb.DEFAULT=new nb(0x2800000,nb.DEFAULT_COLLECTION_PERCENTILE,nb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),nb.DISABLED=new nb(-1,0,0);let nN="LruGarbageCollector";function nS([e,t],[r,n]){let s=M(e,r);return 0===s?M(t,n):s}class nI{constructor(e){this.rr=e,this.buffer=new eg(nS),this.ir=0}sr(){return++this.ir}_r(e){let t=[e,this.sr()];if(this.buffer.size<this.rr)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>nS(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class nV{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.ar=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.ur(6e4)}stop(){this.ar&&(this.ar.cancel(),this.ar=null)}get started(){return null!==this.ar}ur(e){v(nN,`Garbage collection scheduled in ${e}ms`),this.ar=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.ar=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){ec(e)?v(nN,"Ignoring IndexedDB error during garbage collection: ",e):await el(e)}await this.ur(3e5)})}}class nC{constructor(e,t){this.cr=e,this.params=t}calculateTargetCount(e,t){return this.cr.lr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return eu.resolve(eh.ce);let r=new nI(t);return this.cr.forEachTarget(e,e=>r._r(e.sequenceNumber)).next(()=>this.cr.Er(e,e=>r._r(e))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.cr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.cr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(v("LruGarbageCollector","Garbage collection skipped; disabled"),eu.resolve(nx)):this.getCacheSize(e).next(r=>r<this.params.cacheSizeCollectionThreshold?(v("LruGarbageCollector",`Garbage collection skipped; Cache size ${r} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),nx):this.hr(e,t))}getCacheSize(e){return this.cr.getCacheSize(e)}hr(e,t){let r,n,s,i,a,o,l,u=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(v("LruGarbageCollector",`C
1apping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),n=this.params.maximumSequenceNumbersToCollect):n=t,i=Date.now(),this.nthSequenceNumber(e,n))).next(n=>(r=n,a=Date.now(),this.removeTargets(e,r,t))).next(t=>(s=t,o=Date.now(),this.removeOrphanedDocuments(e,r))).next(e=>(l=Date.now(),w()<=c.$b.DEBUG&&v("LruGarbageCollector",`LRU Garbage Collection 2 Counted targets in ${i-u}ms 3 Determined least recently used ${n} in `+(a-i)+"ms\n"+` Removed ${s} targets in `+(o-a)+"ms\n"+` Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-u}ms`),eu.resolve({didRun:!0,sequenceNumbersCollected:n,targetsRemoved:s,documentsRemoved:e})))}}let nA="firestore.googleapis.com";class nD{constructor(e){if(void 0===e.host){if(void 0!==e.ssl)throw new I(S.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=nA,this.ssl=!0}else this.host=e.host,this.ssl=e.ssl??!0;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 I(S.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,r,n){if(!0===t&&!0===n)throw new I(S.INVALID_ARGUMENT,`${e} and ${r} 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=nr(e.experimentalLongPollingOptions??{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new I(S.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new I(S.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new I(S.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){var t,r;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,r=e.experimentalLongPollingOptions,t.timeoutSeconds===r.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class nk{constructor(e,t,r,n){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new nD({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new I(S.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 I(S.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 nD(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new A;switch(e.type){case"firstParty":return new L(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new I(S.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
3d 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(){let e;return(e=nT.get(this))&&(v("ComponentProvider","Removing Datastore"),nT.delete(this),e.terminate()),Promise.resolve()}}class nR{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new nR(this.firestore,e,this._query)}}class nL{constructor(e,t,r){this.converter=t,this._key=r,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new nU(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new nL(this.firestore,e,this._key)}toJSON(){return{type:nL._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,r){if(er(t,nL._jsonSchema))return new nL(e,r||null,new G(Q.fromString(t.referencePath)))}}nL._jsonSchemaVersion="firestore/documentReference/1.0",nL._jsonSchema={type:et("string",nL._jsonSchemaVersion),referencePath:et("string")};class nU extends nR{constructor(e,t,r){super(e,t,t5(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new nL(this.firestore,null,new G(e))}withConverter(e){return new nU(this.firestore,e,this._path)}}function nO(e,t,...r){if(e=(0,l.Ku)(e),H("collection","path",t),e instanceof nk){let n=Q.fromString(t,...r);return Y(n),new nU(e,null,n)}{if(!(e instanceof nL||e instanceof nU))throw new I(S.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=e._path.child(Q.fromString(t,...r));return Y(n),new nU(e.firestore,null,n)}}function nP(e,t,...r){if(e=(0,l.Ku)(e),1==arguments.length&&(t=P.newId()),H("doc","path",t),e instanceof nk){let n=Q.fromString(t,...r);return W(n),new nL(e,null,new G(n))}{if(!(e instanceof nL||e instanceof nU))throw new I(S.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=e._path.child(Q.fromString(t,...r));return W(n),new nL(e.firestore,e instanceof nU?e.converter:null,new G(n))}}class nM{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0}(this._values,e._values)}toJSON(){return{type:nM._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(er(e,nM._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(e=>"number"==typeof e))return new nM(e.vectorValues);throw new I(S.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}nM._jsonSchemaVersion="firestore/vectorValue/1.0",nM._jsonSchema={type:et("string",nM._jsonSchemaVersion),vectorValues:et("object")};let nF=/^__.*__$/;class n${constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return null!==this.fieldMask?new tC(e,this.data,this.fieldMask,t,this.fieldTransforms):new tV(e,this.data,t,this.fieldTransforms)}}class nB{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new tC(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function nq(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw x(40011,{dataSource:e})}}class nz{constructor(e,t,r,n,s,i){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=n,void 0===s&&this.validatePath(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(e){return new nz({...this.settings,...e},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}childContextForField(e){let t=this.path?.child(e),r=this.contextWith({path:t,arrayElement:!1});return r.validatePathSegment(e),r}childContextForFieldPath(e){let t=this.path?.child(e),r=this.contextWith({path:t,arrayElement:!1});return r.validatePath(),r}childContextForArray(e){return this.contextWith({path:void 0,arrayElement:!0})}createError(e){return n6(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}validatePath(){if(this.path)for(let e=0;e<this.path.length;e++)this.validatePathSegment(this.path.get(e))}validatePathSegment(e){if(0===e.length)throw this.createError("Document fields must not be empty");if(nq(this.dataSource)&&nF.test(e))throw this.createError('Document fields cannot begin and end with "__"')}}class nQ{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer
3=r||r8(e)}createContext(e,t,r,n=!1){return new nz({dataSource:e,methodName:t,targetDoc:r,path:K.emptyPath(),arrayElement:!1,hasConverter:n},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function nj(e){let t=e._freezeSettings(),r=r8(e._databaseId);return new nQ(e._databaseId,!!t.ignoreUndefinedProperties,r)}function nK(e,t,r,n,s,i={}){let a,o,l=e.createContext(i.merge||i.mergeFields?2:0,t,r,s);n1("Data must be an object, but it was:",l,n);let u=nZ(n,l);if(i.merge)a=new ew(l.fieldMask),o=l.fieldTransforms;else if(i.mergeFields){let e=[];for(let n of i.mergeFields){let s=n2(t,n,r);if(!l.contains(s))throw new I(S.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);n5(e,s)||e.push(s)}a=new ew(e),o=l.fieldTransforms.filter(e=>a.covers(e.field))}else a=null,o=l.fieldTransforms;return new n$(new tr(u),a,o)}class nG extends ne{_toFieldTransform(e){if(2!==e.dataSource)throw 1===e.dataSource?e.createError(`${this._methodName}() can only appear at the top level of your update data`):e.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof nG}}class nH extends ne{_toFieldTransform(e){return new t_(e.path,new tl)}isEqual(e){return e instanceof nH}}function nW(e,t,r,n){let s=e.createContext(1,t,r);n1("Data must be an object, but it was:",s,n);let i=[],a=tr.empty();return e_(n,(e,n)=>{let o=n4(t,e,r);n=(0,l.Ku)(n);let u=s.childContextForFieldPath(o);if(n instanceof nG)i.push(o);else{let e=nX(n,u);null!=e&&(i.push(o),a.set(o,e))}}),new nB(a,new ew(i),s.fieldTransforms)}function nY(e,t,r,n,s,i){let a=e.createContext(1,t,r),o=[n2(t,n,r)],u=[s];if(i.length%2!=0)throw new I(S.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<i.length;e+=2)o.push(n2(t,i[e])),u.push(i[e+1]);let c=[],h=tr.empty();for(let e=o.length-1;e>=0;--e)if(!n5(c,o[e])){let t=o[e],r=u[e];r=(0,l.Ku)(r);let n=a.childContextForFieldPath(t);if(r instanceof nG)c.push(t);else{let e=nX(r,n);null!=e&&(c.push(t),h.set(t,e))}}return new nB(h,new ew(c),a.fieldTransforms)}function nJ(e,t,r,n=!1){return nX(r,e.createContext(n?4:3,t))}function nX(e,t,r){if(n0(e=(0,l.Ku)(e)))return n1("Unsupported field value:",t,e),nZ(e,t);if(e instanceof ne)return function(e,t){if(!nq(t.dataSource))throw t.createError(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.createError(`${e._methodName}() is not currently supported inside arrays`);let r=e._toFieldTransform(t);r&&t.fieldTransforms.push(r)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.arrayElement&&4!==t.dataSource)throw t.createError("Nested arrays are not supported");let r=[],n=0;for(let s of e){let e=nX(s,t.childContextForArray(n));null==e&&(e={nullValue:"NULL_VALUE"}),r.push(e),n++}return{arrayValue:{values:r}}}return function(e,t,r){if(null===(e=(0,l.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ti(t.serializer,e,r);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let r=en.fromDate(e);return{timestampValue:rB(t.serializer,r)}}if(e instanceof en){let r=new en(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:rB(t.serializer,r)}}if(e instanceof nt)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof r9)return{bytesValue:rz(t.serializer,e._byteString)};if(e instanceof nL){let r=t.databaseId,n=e.firestore._databaseId;if(!n.isEqual(r))throw t.createError(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:rK(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof nM){var n;return{mapValue:{fields:{[eF]:{stringValue:eq},[ez]:{arrayValue:{values:((n=e)instanceof nM?n.toArray():n).map(e=>{if("number"!=typeof e)throw t.createError("VectorValues must only contain numeric values.");return tn(t.serializer,e)})}}}}}}if(r4(e))return e._toProto(t.serializer);throw t.createError(`Unsupported field value: ${X(e)}`)}(e,t,r)}function nZ(e,t){let r={};return eE(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):e_(e,(e,n)=>{let s=nX(n,t.childContextForField(e));null!=s&&(r[e]=s)}),{mapValue:{fields:r}}}function n0(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof en||e instanceof nt||e instanceof r9||e instanceof nL||e instanceof ne||e instanceof nM||r4(e))}function n1(e,t,r){if(!n0(r)||!J(r)){let n=X(r);throw"an object"===n?t.createError(e+" a custom object"):t.createError(e+" "+n)}}function n2(e,t,r){if((t=(0,l.Ku)(t))instanceof r7)return t._internalPath;if("string"==typeof t)return n4(e,t);throw n6("Field path arguments must be of type string or ",e,!1,void 0,r)}let n3=RegExp("[~\\*/\\[\\]]");function n4(e,t,r){if(t.search(n3)>=0)throw n6(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,r);try{return new r7(...t.split("."))._internalPath}catch(n){throw n6(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,r)}}function n6(e,t,r,n,s){let i=n&&!n.isEmpty(),a=void 0!==s,o=`Function ${t}
3() called with invalid data`;r&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(i||a)&&(l+=" (found",i&&(l+=` in field ${n}`),a&&(l+=` in document ${s}`),l+=")"),new I(S.INVALID_ARGUMENT,o+e+l)}function n5(e,t){return e.some(e=>e.isEqual(t))}function n8(e){return"function"==typeof e._readUserData}class n9{constructor(e){this.optionDefinitions=e}_getKnownOptions(e,t){let r=tr.empty();for(let n in this.optionDefinitions)if(this.optionDefinitions.hasOwnProperty(n)){let s=this.optionDefinitions[n];if(n in e){let i,a=e[n];s.nestedOptions&&J(a)?i={mapValue:{fields:new n9(s.nestedOptions).getOptionsProto(t,a)}}:a&&(i=nX(a,t)??void 0),i&&r.set(K.fromServerFormat(s.serverName),i)}}return r}getOptionsProto(e,t,r){let n=this._getKnownOptions(t,e);if(r){let t=new Map(function(e,t){let r=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&r.push(t(e[n],n,e));return r}(r,(t,r)=>[K.fromServerFormat(r),void 0!==t?nX(t,e):null]));n.setAll(t)}return n.value.mapValue.fields??{}}}function n7(){return new nG("deleteField")}function se(){return new nH("serverTimestamp")}function st(e){return e instanceof ss?e:J(e)?function(e){let t=[];for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];t.push(sd(r)),t.push(st(n))}return new sf("map",t,"map")}(e):e instanceof Array?function(e){return new sf("array",e.map(e=>st(e)),"array")}(e):sm(e,void 0)}function sr(e){if(e instanceof ss)return e;if(e instanceof nM)return sd(e);if(Array.isArray(e))return sd(new nM(e));throw Error("Unsupported value: "+typeof e)}function sn(e){return"string"==typeof e?sc(e):st(e)}class ss{constructor(){this._protoValueType="ProtoValue"}add(e){return new sf("add",[this,st(e)],"add")}asBoolean(){if(this instanceof sp)return this;if(this instanceof sh)return new sy(this);if(this instanceof su)return new sw(this);if(this instanceof sf)return new sg(this);throw new I("invalid-argument",`Conversion of type ${typeof this} to BooleanExpression not supported.`)}subtract(e){return new sf("subtract",[this,st(e)],"subtract")}multiply(e){return new sf("multiply",[this,st(e)],"multiply")}divide(e){return new sf("divide",[this,st(e)],"divide")}mod(e){return new sf("mod",[this,st(e)],"mod")}equal(e){return new sf("equal",[this,st(e)],"equal").asBoolean()}notEqual(e){return new sf("not_equal",[this,st(e)],"notEqual").asBoolean()}lessThan(e){return new sf("less_than",[this,st(e)],"lessThan").asBoolean()}lessThanOrEqual(e){return new sf("less_than_or_equal",[this,st(e)],"lessThanOrEqual").asBoolean()}greaterThan(e){return new sf("greater_than",[this,st(e)],"greaterThan").asBoolean()}greaterThanOrEqual(e){return new sf("greater_than_or_equal",[this,st(e)],"greaterThanOrEqual").asBoolean()}arrayConcat(e,...t){return new sf("array_concat",[this,...[e,...t].map(e=>st(e))],"arrayConcat")}arrayContains(e){return new sf("array_contains",[this,st(e)],"arrayContains").asBoolean()}arrayContainsAll(e){return new sf("array_contains_all",[this,Array.isArray(e)?new sl(e.map(st),"arrayContainsAll"):e],"arrayContainsAll").asBoolean()}arrayContainsAny(e){return new sf("array_contains_any",[this,Array.isArray(e)?new sl(e.map(st),"arrayContainsAny"):e],"arrayContainsAny").asBoolean()}arrayReverse(){return new sf("array_reverse",[this])}arrayLength(){return new sf("array_length",[this],"arrayLength")}equalAny(e){return new sf("equal_any",[this,Array.isArray(e)?new sl(e.map(st),"equalAny"):e],"equalAny").asBoolean()}notEqualAny(e){return new sf("not_equal_any",[this,Array.isArray(e)?new sl(e.map(st),"notEqualAny"):e],"notEqualAny").asBoolean()}exists(){return new sf("exists",[this],"exists").asBoolean()}charLength(){return new sf("char_length",[this],"charLength")}like(e){return new sf("like",[this,st(e)],"like").asBoolean()}regexContains(e){return new sf("regex_contains",[this,st(e)],"regexContains").asBoolean()}regexFind(e){return new sf("regex_find",[this,st(e)],"regexFind")}regexFindAll(e){return new sf("regex_find_all",[this,st(e)],"regexFindAll")}regexMatch(e){return new sf("regex_match",[this,st(e)],"regexMatch").asBoolean()}stringContains(e){return new sf("string_contains",[this,st(e)],"stringContains").asBoolean()}startsWith(e){return new sf("starts_with",[this,st(e)],"startsWith").asBoolean()}endsWith(e){return new sf("ends_with",[this,st(e)],"endsWith").asBoolean()}toLower(){return new sf("to_lower",[this],"toLower")}toUpper(){return new sf("to_upper",[this],"toUpper")}trim(e){let t=[this];return e&&t.push(st(e)),new sf("trim",t,"trim")}ltrim(e){let t=[this];return e&&t.push(st(e)),new sf("ltrim",t,"ltrim")}rtrim(e){let t=[this];return e&&t.push(st(e)),new sf("rtrim",t,"rtrim")}type(){return new sf("type",[this])}isType(e){return new sf("is_type",[this,sd(e)],"isType").asBoolean()}stringConcat(e,...t){return new sf("string_concat",[this,...[e,...t].map(st)],"stringConcat")}stringIndexOf(e){return new sf("string_index_of",[this,st(e)],"stringIndexOf")}stringRepeat(e){return new sf("string_repeat",[this,st(e)],"stringRepeat")}stringReplaceAll(e,t){return new sf("string_replace_all",[this,st(e),st(t)],"stringReplaceAll")}stringReplaceOne(e,t){return new sf("string_replace_one",[this,st(e),st(t)],"stringReplaceOne")}concat(e,...t){return new sf("concat",[this,...[e,...t].map(st)],"concat")}reverse(){return new sf("reverse",[this],"reverse")}arrayFilter(e,t){return new sf("array_filter",[this,st(e),t],"arrayFilter")}arrayTransform(e,t){return new sf("array_transform",[this,st(e),t],"arrayTransform")}arrayTransformWithIndex(e,t,r){return new sf("array_transform",[this,st(e),st(t),r],"arrayTransformWithIndex")}arraySlice(e,t){let r=[this,st(e)];return void 0!==t&&r.push(st(t)),new sf("array_slice",r,"arraySlice")}arrayFirst(){return new sf("array_first",[this],"arrayFirst")}arrayFirstN(e){return new sf("array_first_n",[this,st(e)],"arrayFirstN")}arrayLast(){return new sf("array_last",[this],"arrayLast")}arrayLastN(e){return new sf("array_last_n",[this,st(e)],"arrayLastN")}arrayMaximum(){return new sf("maximum",[this],"arrayMaximum")}arrayMaximumN(e){return new sf("maximum_n",[this,st(e)],"arrayMaximumN")}arrayMinimum(){return new sf("minimum",[this],"arrayMinimum")}arrayMinimumN(e){return new sf("minimum_n",[this,st(e)],"arrayMinimumN")}arrayIndexOf(e){return new sf("array_index_of",[this,st(e),st("first")],"arrayIndexOf")}arrayLastIndexOf(e){return new sf("array_index_of",[this,st(e),st("last")],"arrayLastIndexOf")}arrayIndexOfAll(e){return new sf("array_index_of_all",[this,st(e)],"arrayIndexOfAll")}byteLength(){return new sf("byte_length",[this],"byteLength")}ceil(){return new sf("ceil",[this])}floor(){return new sf("floor",[this])}abs(){return new sf("abs",[this])}exp(){return new sf("exp",[this])}mapGet(e){return new sf("map_get",[this,sd(e)],"mapGet")}mapSet(e,t,...r){return new sf("map_set",[this,st(e),st(t),...r.map(st)],"mapSet")}mapKeys(){return new sf("map_keys",[this],"mapKeys")}mapValues(){return new sf("map_values",[this],"mapValues")}mapEntries(){return new sf("map_entries",[this],"mapEntries")}getField(e){return new sf("get_field",[this,st(e)],"get_field")}count(){return si._create("count",[this],"count")}sum(){return si._create("sum",[this],"sum")}average(){return si._create("average",[this],"average")}minimum(){return si._create("minimum",[this],"minimum")}maximum(){return si._create("maximum",[this],"maximum")}first(){return si._create("first",[this],"first")}last(){return si._create("last",[this],"last")}arrayAgg(){return si._create("array_agg",[this],"arrayAgg")}arrayAggDistinct(){return si._create("array_agg_distinct",[this],"arrayAggDistinct")}countDistinct(){return si._create("count_distinct",[this],"countDistinct")}logicalMaximum(e,...t){return new sf("maximum",[this,...[e,...t].map(st)],"logicalMaximum")}logicalMinimum(e,...t){return new sf("minimum",[this,...[e,...t].map(st)],"minimum")}vectorLength(){return new sf("vector_length",[this],"vectorLength")}cosineDistance(e){return new sf("cosine_distance",[this,sr(e)],"cosineDistance")}dotProduct(e){return new sf("dot_product",[this,sr(e)],"dotProduct")}euclideanDistance(e){return new sf("euclidean_distance",[this,sr(e)],"euclideanDistance")}unixMicrosToTimestamp(){return new sf("unix_micros_to_timestamp",[this],"unixMicrosToTimestamp")}timestampToUnixMicros(){return new sf("timestamp_to_unix_micros",[this],"timestampToUnixMicros")}unixMillisToTimestamp(){return new sf("unix_millis_to_timestamp",[this],"unixMillisToTimestamp")}timestampToUnixMillis(){return new sf("timestamp_to_unix_millis",[this],"timestampToUnixMillis")}unixSecondsToTimestamp(){return new sf("unix_seconds_to_timestamp",[this],"unixSecondsToTimestamp")}timestampToUnixSeconds(){return new sf("timestamp_to_unix_seconds",[this],"timestampToUnixSeconds")}timestampAdd(e,t){return new sf("timestamp_add",[this,st(e),st(t)],"timestampAdd")}timestampSubtract(e,t){return new sf("timestamp_subtract",[this,st(e),st(t)],"timestampSubtract")}timestampDiff(e,t){return new sf("timestamp_diff",[this,sn(e),st(t)],"timestampDiff")}timestampExtract(e,t){let r=[this,st(e)];return t&&r.push(st(t)),new sf("timestamp_extract",r,"timestampExtract")}documentId(){return new sf("document_id",[this],"documentId")}parent(){return new sf("parent",[this],"parent")}substring(e,t){let r=st(e);return new sf("substring",void 0===t?[this,r]:[this,r,st(t)],"substring")}arrayGet(e){return new sf("array_get",[this,st(e)],"arrayGet")}isError(){return new sf("is_error",[this],"isError").asBoolean()}ifError(e){let t=new sf("if_error",[this,st(e)],"ifError");return e instanceof sp?t.asBoolean():t}isAbsent(){return new sf("is_absent",[this],"isAbsent").asBoolean()}mapRemove(e){return new sf("map_remove",[this,st(e)],"mapRemove")}mapMerge(e,...t){return new sf("map_merge",[this,st(e),...t.map(st)],"mapMerge")}pow(e){return new sf("pow",[this,st(e)])}trunc(e){return void 0===e?new sf("trunc",[this]):new sf("trunc",[this,st(e)],"trunc")}round(e){return void 0===e?new sf("round",[this]):new sf("round",[this,st(e)],"round")}collectionId(){return new sf("collection_id",[this])}length(){return new sf("length",[this])}ln(){return new sf("ln",[this])}sqrt(){return new sf("sqrt",[this])}
3stringReverse(){return new sf("string_reverse",[this])}ifAbsent(e){return new sf("if_absent",[this,st(e)],"ifAbsent")}ifNull(e){return new sf("if_null",[this,st(e)],"ifNull")}coalesce(e,...t){return new sf("coalesce",[this,st(e),...t.map(st)],"coalesce")}join(e){return new sf("join",[this,st(e)],"join")}log10(){return new sf("log10",[this])}arraySum(){return new sf("sum",[this])}split(e){return new sf("split",[this,st(e)])}timestampTruncate(e,t){let r=[this,st(e)];return t&&r.push(st(t)),new sf("timestamp_trunc",r)}ascending(){var e;return e=this,new sv(sn(e),"ascending","ascending")}descending(){var e;return e=this,new sv(sn(e),"descending","descending")}as(e){return new so(this,e,"as")}}class si{constructor(e,t){this.name=e,this.params=t,this.exprType="AggregateFunction",this._protoValueType="ProtoValue"}static _create(e,t,r){let n=new si(e,t);return n._methodName=r,n}as(e){return new sa(this,e,"as")}_toProto(e){return{functionValue:{name:this.name,args:this.params.map(t=>t._toProto(e))}}}_readUserData(e){e=this._methodName?e.contextWith({methodName:this._methodName}):e,this.params.forEach(t=>t._readUserData(e))}}class sa{constructor(e,t,r){this.aggregate=e,this.alias=t,this._methodName=r}_readUserData(e){this.aggregate._readUserData(e)}}class so{constructor(e,t,r){this.expr=e,this.alias=t,this._methodName=r,this.exprType="AliasedExpression",this.selectable=!0}_readUserData(e){this.expr._readUserData(e)}}class sl extends ss{constructor(e,t){super(),this.Rr=e,this._methodName=t,this.expressionType="ListOfExpressions"}_toProto(e){return{arrayValue:{values:this.Rr.map(t=>t._toProto(e))}}}_readUserData(e){this.Rr.forEach(t=>t._readUserData(e))}}class su extends ss{constructor(e,t){super(),this.fieldPath=e,this._methodName=t,this.expressionType="Field",this.selectable=!0}get _fieldPath(){return this.fieldPath}get fieldName(){return this.fieldPath.canonicalString()}get alias(){return this.fieldName}get expr(){return this}geoDistance(e){return new sf("geo_distance",[this,st(e)],"geoDistance")}_toProto(e){return{fieldReferenceValue:this.fieldPath.canonicalString()}}_readUserData(e){}}function sc(e){var t,r;return r="field",new su("string"==typeof(t=e)?q===t?new r7(q)._internalPath:n2("field",t):t._internalPath,r)}class sh extends ss{constructor(e,t){super(),this.value=e,this._methodName=t,this.expressionType="Constant"}static _fromProto(e){let t=new sh(e,void 0);return t._protoValue=e,t}_toProto(e){return N(void 0!==this._protoValue,237),this._protoValue}_getValue(){return this._protoValue}_readUserData(e){var t,r,n,s,i,a,o;e=this._methodName?e.contextWith({methodName:this._methodName}):e,"object"==typeof(t=this._protoValue)&&null!==t&&("nullValue"in t&&(null===t.nullValue||"NULL_VALUE"===t.nullValue)||"booleanValue"in t&&(null===t.booleanValue||"boolean"==typeof t.booleanValue)||"integerValue"in t&&(null===t.integerValue||"number"==typeof t.integerValue||"string"==typeof t.integerValue)||"doubleValue"in t&&(null===t.doubleValue||"number"==typeof t.doubleValue)||"timestampValue"in t&&(null===t.timestampValue||"object"==typeof(r=t.timestampValue)&&null!==r&&"seconds"in r&&(null===r.seconds||"number"==typeof r.seconds||"string"==typeof r.seconds)&&"nanos"in r&&(null===r.nanos||"number"==typeof r.nanos))||"stringValue"in t&&(null===t.stringValue||"string"==typeof t.stringValue)||"bytesValue"in t&&(null===t.bytesValue||t.bytesValue instanceof Uint8Array)||"referenceValue"in t&&(null===t.referenceValue||"string"==typeof t.referenceValue)||"geoPointValue"in t&&(null===t.geoPointValue||"object"==typeof(n=t.geoPointValue)&&null!==n&&"latitude"in n&&(null===n.latitude||"number"==typeof n.latitude)&&"longitude"in n&&(null===n.longitude||"number"==typeof n.longitude))||"arrayValue"in t&&(null===t.arrayValue||"object"==typeof(s=t.arrayValue)&&null!==s&&!(!("values"in s)||null!==s.values&&!Array.isArray(s.values)))||"mapValue"in t&&(null===t.mapValue||"object"==typeof(i=t.mapValue)&&null!==i&&!(!("fields"in i)||null!==i.fields&&!J(i.fields)))||"fieldReferenceValue"in t&&(null===t.fieldReferenceValue||"string"==typeof t.fieldReferenceValue)||"functionValue"in t&&(null===t.functionValue||"object"==typeof(a=t.functionValue)&&null!==a&&!(!("name"in a)||null!==a.name&&"string"!=typeof a.name||!("args"in a)||null!==a.args&&!Array.isArray(a.args)))||"pipelineValue"in t&&(null===t.pipelineValue||"object"==typeof(o=t.pipelineValue)&&null!==o&&!(!("stages"in o)||null!==o.stages&&!Array.isArray(o.stages))))||(this._protoValue=nX(this.value,e))}}function sd(e,t){return sm(e,"constant")}function sm(e,t){let r=new sh(e,t);return"boolean"==typeof e?new sy(r):r}class sf extends ss{constructor(e,t,r,n){super(),this.name=e,this.params=t,this.expressionType="Function",this._optionsProto=void 0,void 0!==r&&(this._methodName=r),void 0!==n&&(this._options=n)}get _optionsUtil(){return new n9({})}_toProto(e){let t={functionValue:{name:this.name,args:this.params.map(t=>t._toProto(e))}};return this._optionsProto&&(t.functionValue.options=this._optionsProto),t}_readUserData(e){e=this._methodName?e.contextWith({methodName:this._methodName}
vendor: 5,103 bytes, line 3
3):e,this.params.forEach(t=>t._readUserData(e)),this._options&&(this._optionsProto=this._optionsUtil.getOptionsProto(e,this._options))}}class sp extends ss{get _methodName(){return this._expr._methodName}countIf(){return si._create("count_if",[this],"countIf")}not(){return new sf("not",[this],"not").asBoolean()}conditional(e,t){return new sf("conditional",[this,e,t],"conditional")}ifError(e){let t=st(e),r=new sf("if_error",[this,t],"ifError");return t instanceof sp?r.asBoolean():r}_toProto(e){return this._expr._toProto(e)}_readUserData(e){this._expr._readUserData(e)}}class sg extends sp{constructor(e){super(),this._expr=e,this.expressionType="Function"}}class sy extends sp{constructor(e){super(),this._expr=e,this.expressionType="Constant"}_getValue(){return this._expr._getValue()}}class sw extends sp{constructor(e){super(),this._expr=e,this.expressionType="Field"}}class sv{constructor(e,t,r){this.expr=e,this.direction=t,this._methodName=r,this._protoValueType="ProtoValue"}_toProto(e){return{mapValue:{fields:{direction:r5(this.direction),expression:this.expr._toProto(e)}}}}_readUserData(e){this.expr._readUserData(e)}}class s_{constructor(e){this.optionsProto=void 0,{rawOptions:this.rawOptions,...this.knownOptions}=e}_readUserData(e){this.optionsProto=this._optionsUtil.getOptionsProto(e,this.knownOptions,this.rawOptions)}_toProto(e){return{name:this._name,options:this.optionsProto}}}class sE extends s_{get _name(){return"add_fields"}get _optionsUtil(){return new n9({})}constructor(e,t){super(t),this.fields=e}_toProto(e){return{...super._toProto(e),args:[r6(e,this.fields)]}}_readUserData(e){super._readUserData(e),sL(this.fields,e)}}class sT extends s_{get _name(){return"aggregate"}get _optionsUtil(){return new n9({})}constructor(e,t,r){super(r),this.groups=e,this.accumulators=t}_toProto(e){return{...super._toProto(e),args:[r6(e,this.accumulators),r6(e,this.groups)]}}_readUserData(e){super._readUserData(e),sL(this.groups,e),sL(this.accumulators,e)}}class sx extends s_{get _name(){return"distinct"}get _optionsUtil(){return new n9({})}constructor(e,t){super(t),this.groups=e}_toProto(e){return{...super._toProto(e),args:[r6(e,this.groups)]}}_readUserData(e){super._readUserData(e),sL(this.groups,e)}}class sb extends s_{get _name(){return"collection"}get _optionsUtil(){return new n9({forceIndex:{serverName:"force_index"}})}constructor(e,t){super(t),this.Vr=e.startsWith("/")?e:"/"+e}_toProto(e){return{...super._toProto(e),args:[{referenceValue:this.Vr}]}}_readUserData(e){super._readUserData(e)}}class sN extends s_{get _name(){return"collection_group"}get _optionsUtil(){return new n9({forceIndex:{serverName:"force_index"}})}constructor(e,t){super(t),this.collectionId=e}_toProto(e){return{...super._toProto(e),args:[{referenceValue:""},{stringValue:this.collectionId}]}}_readUserData(e){super._readUserData(e)}}class sS extends s_{get _name(){return"database"}get _optionsUtil(){return new n9({})}_toProto(e){return{...super._toProto(e)}}_readUserData(e){super._readUserData(e)}}class sI extends s_{get _name(){return"documents"}get _optionsUtil(){return new n9({})}constructor(e,t){if(super(t),!e||0===e.length)throw new I(S.INVALID_ARGUMENT,"Empty document paths are not allowed in DocumentsSource");const r=e.map(e=>e.startsWith("/")?e:"/"+e),n=new Set(r);if(n.size!==r.length)throw new I(S.INVALID_ARGUMENT,"Duplicate document paths are not allowed in DocumentsSource");this.dr=r,this.mr=n}_toProto(e){return{...super._toProto(e),args:this.dr.map(e=>({referenceValue:e}))}}_readUserData(e){super._readUserData(e)}}class sV extends s_{get _name(){return"where"}get _optionsUtil(){return new n9({})}constructor(e,t){super(t),this.condition=e}_toProto(e){return{...super._toProto(e),args:[this.condition._toProto(e)]}}_readUserData(e){super._readUserData(e),sL(this.condition,e)}}class sC extends s_{get _name(){return"limit"}get _optionsUtil(){return new n9({})}constructor(e,t){N(!isNaN(e)&&e!==1/0&&e!==-1/0,34860),super(t),this.limit=e}_toProto(e){return{...super._toProto(e),args:[ti(e,this.limit)]}}}class sA extends s_{get _name(){return"offset"}get _optionsUtil(){return new n9({})}constructor(e,t){super(t),this.offset=e}_toProto(e){return{...super._toProto(e),args:[ti(e,this.offset)]}}}class sD extends s_{get _name(){return"select"}get _optionsUtil(){return new n9({})}constructor(e,t){super(t),this.selections=e}_toProto(e){return{...super._toProto(e),args:[r6(e,this.selections)]}}_readUserData(e){super._readUserData(e),sL(this.selections,e)}}class sk extends s_{get _name(){return"sort"}get _optionsUtil(){return new n9({})}constructor(e,t){super(t),this.orderings=e}_toProto(e){return{...super._toProto(e),args:this.orderings.map(t=>t._toProto(e))}}_readUserData(e){super._readUserData(e),sL(this.orderings,e)}}class sR extends s_{get _name(){return"replace_with"}get _optionsUtil(){return new n9({})}constructor(e,t){super(t),this.map=e}_toProto(e){return{...super._toProto(e),args:[this.map._toProto(e),r5(sR.pr)]}}_readUserData(e){super._readUserData(e),sL(this.map,e)}}function sL(e,t){return n8(e)?e._readUserData(t):Array.isArray(e)?e.forEach(e
3=>e._readUserData(t)):e instanceof Map?e.forEach(e=>e._readUserData(t)):Object.values(e).forEach(e=>e._readUserData(t)),e}sR.pr="full_replace";class sU{constructor(e,t,r){this.serializer=e,this.stages=t,this.listenOptions=r,this.isCorePipeline=!0}getPipelineCollection(){return sP(this)}getPipelineCollectionGroup(){return sM(this)}getPipelineCollectionId(){var e=this;switch(sO(e)){case"collection":return Q.fromString(sP(e)).lastSegment();case"collection_group":return sM(e);default:return}}getPipelineDocuments(){return sF(this)}getPipelineFlavor(){var e;let t;return e=this,t="exact",e.stages.forEach((r,n)=>{r._name!==sx.name&&r._name!==sT.name||(t="keyless"),r._name===sD.name&&"exact"===t&&(t="augmented"),r._name===sE.name&&n<e.stages.length-1&&"exact"===t&&(t="augmented")}),t}getPipelineSourceType(){return sO(this)}}function sO(e){let t=e.stages[0];return t instanceof sb||t instanceof sN||t instanceof sS||t instanceof sI?t._name:"unknown"}function sP(e){if("collection"===sO(e))return e.stages[0].Vr}function sM(e){if("collection_group"===sO(e))return e.stages[0].collectionId}function sF(e){if("documents"===sO(e))return e.stages[0].dr}class s${constructor(e,t,r,n){this._db=e,this.userDataReader=t,this._userDataWriter=r,this.stages=n}wr(e,t){let r=this.userDataReader.createContext(3,e);return n8(t)?t._readUserData(r):Array.isArray(t)?t.forEach(e=>e._readUserData(r)):t.forEach(e=>e._readUserData(r)),t}where(e){let t=this.stages.map(e=>e);return this.wr("where",e),t.push(new sV(e,{})),new s$(this._db,this.userDataReader,this._userDataWriter,t)}limit(e){let t=this.stages.map(e=>e);return t.push(new sC(e,{})),new s$(this._db,this.userDataReader,this._userDataWriter,t)}sort(e,...t){let r=this.stages.map(e=>e);return"orderings"in e?r.push(new sk(this.wr("sort",e.orderings),{})):r.push(new sk(this.wr("sort",[e,...t]),{})),new s$(this._db,this.userDataReader,this._userDataWriter,r)}br(e){return{pipeline:{stages:this.stages.map(t=>t._toProto(e))}}}}class sB{constructor(e,t){this.type=e,this.value=t}static vr(){return new sB("ERROR",void 0)}static Sr(){return new sB("UNSET",void 0)}static Dr(){return new sB("NULL",eQ)}static newValue(e){return e6(e)?new sB("NULL",eQ):e&&"booleanValue"in e?new sB("BOOLEAN",e):e1(e)?new sB("INT",e):e2(e)?new sB("DOUBLE",e):e&&"timestampValue"in e&&e.timestampValue?new sB("TIMESTAMP",e):e&&"stringValue"in e?new sB("STRING",e):e&&"bytesValue"in e?new sB("BYTES",e):e.referenceValue?new sB("REFERENCE",e):e.geoPointValue?new sB("GEO_POINT",e):e4(e)?new sB("ARRAY",e):e9(e)?new sB("VECTOR",e):e8(e)?new sB("MAP",e):new sB("ERROR",void 0)}Cr(){return"ERROR"===this.type||"UNSET"===this.type}Fr(){return"NULL"===this.type}}function sq(e){if(!e.Cr())return e.value}function sz(e){return e instanceof sp?e._expr:e}function sQ(e){if((e=sz(e))instanceof su)return new sj(e);if(e instanceof sh)return new sK(e);if(e instanceof sl)return new sG(e);if(e instanceof sf){if("add"===e.name)return new s0(e);if("subtract"===e.name)return new s1(e);if("multiply"===e.name)return new s2(e);if("divide"===e.name)return new s3(e);if("mod"===e.name)return new s4(e);if("and"===e.name)return new s6(e);if("equal"===e.name)return new id(e);if("not_equal"===e.name)return new im(e);if("less_than"===e.name)return new ip(e);if("less_than_or_equal"===e.name)return new ig(e);if("greater_than"===e.name)return new iy(e);if("greater_than_or_equal"===e.name)return new iw(e);if("array_concat"===e.name)return new iv(e);if("array_reverse"===e.name)return new i_(e);if("array_contains"===e.name)return new iE(e);if("array_contains_all"===e.name)return new iT(e);if("array_contains_any"===e.name)return new ix(e);if("array_length"===e.name)return new ib(e);if("array_element"===e.name)return new iN(e);if("equal_any"===e.name)return new s7(e);if("not_equal_any"===e.name)return new ie(e);if("is_nan"===e.name)return new it(e);if("is_not_nan"===e.name)return new ir(e);if("is_null"===e.name)return new is(e);if("is_not_null"===e.name)return new ii(e);if("is_error"===e.name)return new ia(e);if("exists"===e.name)return new io(e);if("not"===e.name)return new s5(e);if("or"===e.name)return new s8(e);if("xor"===e.name)return new s9(e);if("conditional"===e.name)return new il(e);if("maximum"===e.name)return new iu(e);if("minimum"===e.name)return new ic(e);if("reverse"===e.name)return new iS(e);if("replace_first"===e.name)return new iI(e);if("replace_all"===e.name)return new iV(e);if("char_length"===e.name)return new iC(e);if("byte_length"===e.name)return new iA(e);if("like"===e.name)return new ik(e);if("regex_contains"===e.name)return new iR(e);if("regex_match"===e.name)return new iL(e);if("string_contains"===e.name)return new iU(e);if("starts_with"===e.name)return new iO(e);if("ends_with"===e.name)return new iP(e);
3if("to_lower"===e.name)return new iM(e);if("to_upper"===e.name)return new iF(e);if("trim"===e.name)return new i$(e);if("string_concat"===e.name)return new iB(e);if("map_get"===e.name)return new iq(e);if("cosine_distance"===e.name)return new iQ(e);if("dot_product"===e.name)return new ij(e);if("euclidean_distance"===e.name)return new iK(e);if("vector_length"===e.name)return new iG(e);if("unix_micros_to_timestamp"===e.name)return new i8(e);if("timestamp_to_unix_micros"===e.name)return new at(e);if("unix_millis_to_timestamp"===e.name)return new i9(e);if("timestamp_to_unix_millis"===e.name)return new ar(e);if("unix_seconds_to_timestamp"===e.name)return new i7(e);if("timestamp_to_unix_seconds"===e.name)return new an(e);if("timestamp_add"===e.name)return new ai(e);if("timestamp_subtract"===e.name)return new aa(e)}throw Error(`Unknown Expr : ${e}`)}class sj{constructor(e){this.expr=e}evaluate(e,t){if(this.expr.fieldName===q)return sB.newValue({referenceValue:rW(e.serializer,t.key)});if("__update_time__"===this.expr.fieldName)return sB.newValue({timestampValue:rQ(e.serializer,t.version)});if("__create_time__"===this.expr.fieldName)return sB.newValue({timestampValue:rQ(e.serializer,t.createTime)});let r=t.data.field(this.expr._fieldPath);return r?ek(r)?sB.newValue(function(e,t){if("estimate"===e.serverTimestampBehavior)return{timestampValue:rQ(e.serializer,es.fromTimestamp(eL(t)))};if("previous"===e.serverTimestampBehavior){let e=eR(t);if(e)return e}return{nullValue:"NULL_VALUE"}}(e,r)):sB.newValue(r):sB.Sr()}}class sK{constructor(e){this.expr=e}evaluate(e,t){return sB.newValue(this.expr._getValue())}}class sG{constructor(e){this.expr=e}evaluate(e,t){let r=this.expr.Rr.map(r=>sQ(r).evaluate(e,t));return r.some(e=>e.Cr())?sB.vr():sB.newValue({arrayValue:{values:r.map(e=>e.value)}})}}function sH(e){return e2(e)?Number(e.doubleValue):Number(e.integerValue)}function sW(e){return BigInt(e.integerValue)}let sY=BigInt("0x7fffffffffffffff"),sJ=-BigInt("0x8000000000000000");class sX{constructor(e){this.expr=e}evaluate(e,t){N(this.expr.params.length>=2,24778);let r=sQ(this.expr.params[0]).evaluate(e,t),n=sQ(this.expr.params[1]).evaluate(e,t),s=this.Or(r,n);for(let r of this.expr.params.slice(2)){let n=sQ(r).evaluate(e,t);s=this.Or(s,n)}return s}Or(e,t){if(e.Cr()||t.Cr())return sB.vr();if(e.Fr()||t.Fr())return sB.Dr();let r=e.value,n=t.value;if(!e2(r)&&!e1(r)||!e2(n)&&!e1(n))return sB.vr();if(e2(r)||e2(n)){let e=this.Mr(r,n);return e?sB.newValue(e):sB.vr()}if(e1(r)&&e1(n)){let e=this.Nr(r,n);return void 0===e?sB.vr():"number"==typeof e?sB.newValue({doubleValue:e}):e<sJ||e>sY?sB.vr():sB.newValue({integerValue:`${e}`})}return sB.vr()}}function sZ(e,t){return eG(e)!==eG(t)?"TYPE_MISMATCH":e5(e)||e5(t)?"NOT_EQ":e6(e)&&e6(t)?"EQ":e6(e)||e6(t)?"NULL":e4(e)&&e4(t)?function(e,t){if(e.values?.length!==t.values?.length)return"NOT_EQ";let r=!1;for(let n=0;n<(e.values?.length??0);n++){let s=e.values[n],i=t.values[n];switch(sZ(s,i)){case"EQ":break;case"NOT_EQ":case"TYPE_MISMATCH":return"NOT_EQ";case"NULL":r=!0;break;default:x(44609,{Lr:s,Br:i})}}return r?"NULL":"EQ"}(e.arrayValue,t.arrayValue):e9(e)&&e9(t)||e8(e)&&e8(t)?function(e,t){let r=e.fields||{},n=t.fields||{};if(ev(r)!==ev(n))return"NOT_EQ";let s=!1;for(let e in r)if(r.hasOwnProperty(e)){if(void 0===n[e])return"NOT_EQ";switch(sZ(r[e],n[e])){case"NOT_EQ":case"TYPE_MISMATCH":return"NOT_EQ";case"NULL":s=!0}}return s?"NULL":"EQ"}(e.mapValue,t.mapValue):eH(e,t,{Te:!1,Ee:!0,he:!0})?"EQ":"NOT_EQ"}class s0 extends sX{Nr(e,t){return sW(e)+sW(t)}Mr(e,t){return{doubleValue:sH(e)+sH(t)}}}class s1 extends sX{constructor(e){super(e),this.expr=e}Nr(e,t){return sW(e)-sW(t)}Mr(e,t){return{doubleValue:sH(e)-sH(t)}}}class s2 extends sX{constructor(e){super(e),this.expr=e}Nr(e,t){return sW(e)*sW(t)}Mr(e,t){return{doubleValue:sH(e)*sH(t)}}}class s3 extends sX{constructor(e){super(e),this.expr=e}Nr(e,t){let r=sW(t);if(r!==BigInt(0))return sW(e)/r}Mr(e,t){let r=sH(t);return 0===r?{doubleValue:ed(r)?-1/0:1/0}:{doubleValue:sH(e)/r}}}class s4 extends sX{constructor(e){super(e),this.expr=e}Nr(e,t){let r=sW(t);if(r!==BigInt(0))return sW(e)%r}Mr(e,t){let r=sH(t);if(0!==r)return{doubleValue:sH(e)%r}}}class s6{constructor(e){this.expr=e}evaluate(e,t){let r=!1,n=!1;for(let s of this.expr.params){let i=sQ(s).evaluate(e,t);switch(i.type){case"BOOLEAN":if(!i.value?.booleanValue)return sB.newValue(eK);break;case"NULL":n=!0;break;default:r=!0}}return r?sB.vr():n?sB.Dr():sB.newValue(ej)}}class s5{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,9634);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"BOOLEAN":return sB.newValue({booleanValue:!r.value?.booleanValue});case"NULL":return sB.Dr();default:return sB.vr()}}}class s8{constructor(e){this.expr=e}evaluate(e,t){let r=!1,n=!1;for(let s of this.expr.params){let i=sQ(s).evaluate(e,t);switch(i.type){case"BOOLEAN":if(i.value?.booleanValue)return sB.newValue(ej);break;case"NULL":n=!0;break;default:r=!0}}return r?sB.vr():n?sB.Dr():sB.newValue(eK)}}class s9{constructor(e){this.expr=e}evaluate(e,t){let r=!1,n=!1;for(let s of this.expr.params){let i=sQ(s).evaluate(e,t);switch(i.type){case"BOOLEAN":r=s9.xor(r,!!i.value?.booleanValue);break;case"NULL":n=!0;break;default:return sB.vr()}}return n?sB.Dr():sB.newValue({booleanValue:r})}static xor(e,t){return(e||t)&&!(e&&t)}}class s7{constructor(e){this.expr=e}evaluate(e,t){N(2===this.expr.params.length,55094);let r=!1,n=sQ(this.expr.params[0]).evaluate(e,t);switch(n.type){case"NULL":r=!0;break;case"ERROR":case"UNSET":return sB.vr()}let s=sQ(this.expr.params[1]).evaluate(e,t);switch(s.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sB.vr()}if(r)return sB.Dr();for(let e of s.value?.arrayValue?.values??[])switch(e6(n.value)&&e6(e)?"EQ":sZ(n.value,e)){case"EQ":return sB.newValue(ej);case"NOT_EQ":case"TYPE_MISMATCH":break;case"NULL":r=!0;break;default:x(44608,{value:n.value,candidate:e})}return r?sB.Dr():sB.newValue(eK)}}class ie{constructor(e){this.expr=e}evaluate(e,t){return new s5(new sf("not",[new sf("equal_any",this.expr.params)])).evaluate(e,t)}}class it{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,23322);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"INT":return sB.newValue(eK);case"DOUBLE":return sB.newValue({booleanValue:isNaN(sH(r.value))});case"NULL":return sB.Dr();default:return sB.vr()}}}class ir{constructor(e){this.expr=e}evaluate(e,t){return N(1===this.expr.params.length,50406),new s5(new sf("not",[new sf("is_nan",this.expr.params)])).evaluate(e,t)}}class is{constructor(e){this.expr=e}evaluate(e,t){switch(N(1===this.expr.params.length,23123),sQ(this.expr.params[0]).evaluate(e,t).type){case"NULL":return sB.newValue(ej);case"UNSET":case"ERROR":return sB.vr();default:return sB.newValue(eK)}}}class ii{constructor(e){this.expr=e}evaluate(e,t){return N(1===this.expr.params.length,23167),new s5(new sf("not",[new sf("is_null",this.expr.params)])).evaluate(e,t)}}class ia{constructor(e){this.expr=e}evaluate(e,t){return N(1===this.expr.params.length,5228),"ERROR"===sQ(this.expr.params[0]).evaluate(e,t).type?sB.newValue(ej):sB.newValue(eK)}}class io{constructor(e){this.expr=e}evaluate(e,t){switch(N(1===this.expr.params.length,6877),sQ(this.expr.params[0]).evaluate(e,t).type){case"ERROR":return sB.vr();case"UNSET":return sB.newValue(eK);default:return sB.newValue(ej)}}}class il{constructor(e){this.expr=e}evaluate(e,t){N(3===this.expr.params.length,11706);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"BOOLEAN":return r.value?.booleanValue?sQ(this.expr.params[1]).evaluate(e,t):sQ(this.expr.params[2]).evaluate(e,t);case"NULL":return sQ(this.expr.params[2]).evaluate(e,t);default:return sB.vr()}}}class iu{constructor(e){this.expr=e}evaluate(e,t){let r;for(let n of this.expr.params.map(r=>sQ(r).evaluate(e,t)))switch(n.type){case"ERROR":case"UNSET":case"NULL":continue;default:r=void 0===r||eY(n.value,r.value)>0?n:r}return void 0===r?sB.Dr():r}}class ic{constructor(e){this.expr=e}evaluate(e,t){let r;for(let n of this.expr.params.map(r=>sQ(r).evaluate(e,t)))switch(n.type){case"ERROR":case"UNSET":case"NULL":continue;default:r=void 0===r||0>eY(n.value,r.value)?n:r}return void 0===r?sB.Dr():r}}class ih{constructor(e){this.expr=e}evaluate(e,t){N(2===this.expr.params.length,31033,`${this.expr.name}() function should have exactly 2 params`);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"ERROR":case"UNSET":return sB.vr()}let n=sQ(this.expr.params[1]).evaluate(e,t);switch(n.type){case"ERROR":case"UNSET":return sB.vr()}return this.Ur(r,n)}}
3class id extends ih{constructor(e){super(e),this.expr=e}Ur(e,t){if(e.Fr()&&t.Fr())return sB.newValue(ej);if(e.Fr()||t.Fr()||e5(e.value)||e5(t.value)||eG(e.value)!==eG(t.value))return sB.newValue(eK);switch(sZ(e.value,t.value)){case"EQ":return sB.newValue(ej);case"NOT_EQ":return sB.newValue(eK);case"NULL":return sB.Dr();default:x(44615,{left:e,right:t})}}}class im extends ih{constructor(e){super(e),this.expr=e}Ur(e,t){switch(sZ(e.value,t.value)){case"EQ":return sB.newValue(eK);case"NOT_EQ":case"TYPE_MISMATCH":return sB.newValue(ej);case"NULL":return sB.Dr();default:x(44614,{left:e,right:t})}}}class ip extends ih{constructor(e){super(e),this.expr=e}Ur(e,t){return eG(e.value)!==eG(t.value)||e5(e.value)||e5(t.value)?sB.newValue(eK):sB.newValue({booleanValue:0>eY(e.value,t.value)})}}class ig extends ih{constructor(e){super(e),this.expr=e}Ur(e,t){return eG(e.value)!==eG(t.value)||e5(e.value)||e5(t.value)?sB.newValue(eK):"EQ"===sZ(e.value,t.value)?sB.newValue(ej):sB.newValue({booleanValue:0>eY(e.value,t.value)})}}class iy extends ih{constructor(e){super(e),this.expr=e}Ur(e,t){return eG(e.value)!==eG(t.value)||e5(e.value)||e5(t.value)?sB.newValue(eK):sB.newValue({booleanValue:eY(e.value,t.value)>0})}}class iw extends ih{constructor(e){super(e),this.expr=e}Ur(e,t){return eG(e.value)!==eG(t.value)||e5(e.value)||e5(t.value)?sB.newValue(eK):"EQ"===sZ(e.value,t.value)?sB.newValue(ej):sB.newValue({booleanValue:eY(e.value,t.value)>0})}}class iv{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class i_{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,216);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sB.Dr();case"ARRAY":{let e=r.value.arrayValue?.values??[];return sB.newValue({arrayValue:{values:[...e].reverse()}})}default:return sB.vr()}}}class iE{constructor(e){this.expr=e}evaluate(e,t){return N(2===this.expr.params.length,52884),new s7(new sf("eq_any",[this.expr.params[1],this.expr.params[0]])).evaluate(e,t)}}class iT{constructor(e){this.expr=e}evaluate(e,t){N(2===this.expr.params.length,1392);let r=!1,n=sQ(this.expr.params[0]).evaluate(e,t);switch(n.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sB.vr()}let s=sQ(this.expr.params[1]).evaluate(e,t);switch(s.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sB.vr()}if(r)return sB.Dr();let i=s.value?.arrayValue?.values??[],a=n.value?.arrayValue?.values??[];for(let e of i){let t=!1;for(let n of(r=!1,a)){switch(e6(e)&&e6(n)?"EQ":sZ(e,n)){case"EQ":t=!0;break;case"NOT_EQ":case"TYPE_MISMATCH":break;case"NULL":r=!0;break;default:x(44613,{value:n,search:e})}if(t)break}if(!t)return sB.newValue(eK)}return sB.newValue(ej)}}class ix{constructor(e){this.expr=e}evaluate(e,t){N(2===this.expr.params.length,2680);let r=!1,n=sQ(this.expr.params[0]).evaluate(e,t);switch(n.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sB.vr()}let s=sQ(this.expr.params[1]).evaluate(e,t);switch(s.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sB.vr()}if(r)return sB.Dr();let i=s.value?.arrayValue?.values??[];for(let e of n.value?.arrayValue?.values??[])for(let t of i)switch(e6(e)&&e6(t)?"EQ":sZ(e,t)){case"EQ":return sB.newValue(ej);case"NOT_EQ":case"TYPE_MISMATCH":break;case"NULL":r=!0;break;default:x(44608,{value:e,search:t})}return r?sB.Dr():sB.newValue(eK)}}class ib{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,38605);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sB.Dr();case"ARRAY":return sB.newValue({integerValue:`${r.value?.arrayValue?.values?.length??0}`});default:return sB.vr()}}}class iN{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class iS{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,1508);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sB.Dr();case"BYTES":{let e=r.value?.bytesValue;if("string"==typeof e){let t=ex.fromBase64String(e).toUint8Array();return t.reverse(),sB.newValue({bytesValue:ex.fromUint8Array(t).toBase64()})}return sB.newValue({bytesValue:new Uint8Array(e).reverse()})}case"STRING":{let e=r.value?.stringValue,t=Array.from(new Intl.__PRIVATE_Segmenter(void 0,{granularity:"grapheme"}).segment(e),e=>e.segment).reverse();return sB.newValue({stringValue:t.join("")})}default:return sB.vr()}}}class iI{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class iV{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class iC{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,19400);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sB.Dr();case"STRING":{let e=function(e){let t=0;for(let r=0;r<e.length;r++){let n=e.codePointAt(r);if(void 0===n)return;if(n<=65535)if(n>=55296&&n<=57343)if(n<=56319){let n=e.codePointAt(r+1);void 0!==n&&n>=56320&&n<=57343?(t+=1,r++):t+=1}else t+=1;else t+=1;else{if(!(n<=1114111))return;t+=1,r++}}return t}(r.value.stringValue);return void 0===e?sB.vr():sB.newValue({integerValue:e})}default:return sB.vr()}}}class iA{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,8486);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"BYTES":{let e=r.value?.bytesValue;return"string"==typeof e?sB.newValue({integerValue:ex.fromBase64String(e).toUint8Array().length}):sB.newValue({integerValue:new Uint8Array(e).length})}case"STRING":{let e=function(e){let t=0;for(let r=0;r<e.length;r++){let n=e.codePointAt(r);if(void 0===n)return;if(n>=55296&&n<=57343){if(!(n<=56319))return;{let n=e.codePointAt(r+1);if(void 0===n||!(n>=56320&&n<=57343))return;t+=4,r++}}else if(n<=127)t+=1;else if(n<=2047)t+=2;else if(n<=65535)t+=3;else{if(!(n<=1114111))return;t+=4,r++}}return t}(r.value?.stringValue);return void 0===e?sB.vr():sB.newValue({integerValue:e})}case"NULL":return sB.Dr();default:return sB.vr()}}}class iD{constructor(e){this.expr=e}evaluate(e,t){N(2===this.expr.params.length,39773,`${this.expr.name}() function should have exactly two parameters`);let r=!1,n=sQ(this.expr.params[0]).evaluate(e,t);switch(n.type){case"STRING":break;case"NULL":r=!0;break;default:return sB.vr()}let s=sQ(this.expr.params[1]).evaluate(e,t);switch(s.type){case"STRING":break;case"NULL":r=!0;break;default:return sB.vr()}return r?sB.Dr():this.kr(n.value?.stringValue,s.value?.stringValue)}}class ik extends iD{kr(e,t){try{let r=function(e){let t="";for(let r=0;r<e.length;r++){let n=e.charAt(r);switch(n){case"_":t+=".";break;case"%":t+=".*";break;case"\\":case".":case"*":case"?":case"+":case"^":case"$":case"|":case"(":case")":case"[":case"]":case"{":case"}":t+="\\"+n;break;default:t+=n}}return"^"+t+"$"}(t),n=d.L3.compile(r);return sB.newValue({booleanValue:n.matches(e)})}catch(e){return E(`Invalid LIKE pattern converted to regex: ${t}, returning error. Error: ${e}`),sB.vr()}}}class iR extends iD{kr(e,t){try{let r=d.L3.compile(t);return sB.newValue({booleanValue:r.matcher(e).find()})}catch(e){return E(`Invalid regex pattern found in regex_contains: ${t}, returning error`),sB.vr()}}}class iL extends iD{kr(e,t){try{return sB.newValue({booleanValue:d.L3.compile(t).matches(e)})}catch(e){return E(`Invalid regex pattern found in regex_match: ${t}, returning error`),sB.vr()}}}class iU extends iD{kr(e,t){return sB.newValue({booleanValue:e.includes(t)})}}class iO extends iD{kr(e,t){return sB.newValue({booleanValue:e.startsWith(t)})}}class iP extends iD{kr(e,t){return sB.newValue({booleanValue:e.endsWith(t)})}}class iM{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,29079);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"STRING":return sB.newValue({stringValue:r.value?.stringValue?.toLowerCase()});case"NULL":return sB.Dr();default:return sB.vr()}}}class iF{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,60487);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"STRING":return sB.newValue({stringValue:r.value?.stringValue?.toUpperCase()});case"NULL":return sB.Dr();default:return sB.vr()}}}class i${constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,28544);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"STRING":return sB.newValue({stringValue:r.value?.stringValue?.trim()});case"NULL":return sB.Dr();default:return sB.vr()}}}class iB{constructor(e){this.expr=e}evaluate(e,t){let r=this.expr.params.map(r=>sQ(r).evaluate(e,t)),n="",s=!1;for(let e of r)switch(e.type){case"STRING":n+=e.value.stringValue;break;case"NULL":s=!0;break;default:return sB.vr()}return s?sB.Dr():sB.newValue({stringValue:n})}}class iq{constructor(e){this.expr=e}evaluate(e,t){N(2===this.expr.params.length,4483);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"UNSET":return sB.Sr();case"MAP":break;default:return sB.vr()}let n=sQ(this.expr.params[1]).evaluate(e,t);if("STRING"!==n.type)return sB.vr();let s=r.value?.mapValue?.fields?.[n.value?.stringValue];return void 0===s?sB.Sr():sB.newValue(s)}}class iz{constructor(e){this.expr=e}evaluate(e,t){N(2===this.expr.params.length,25231,`${this.expr.name}() function should have exactly 2 params`);let r=!1,n=sQ(this.expr.params[0]).evaluate(e,t);switch(n.type){case"VECTOR":break;case"NULL":r=!0;break;default:return sB.vr()}let s=sQ(this.expr.params[1]).evaluate(e,t);switch(s.type){case"VECTOR":break;case"NULL":r=!0;break;default:return sB.vr()}if(r)return sB.Dr();let i=e7(n.value),a=e7(s.value);if(void 0===i||void 0===a||i.values?.length!==a.values?.length)return sB.vr();let o=this.qr(i,a);return void 0===o||isNaN(o)?sB.vr():sB.newValue({doubleValue:o})}}class iQ extends iz{qr(e,t){let r=e?.values??[],n=t?.values??[];if(0===r.length)return;let s=0,i=0,a=0;for(let e=0;e<r.length;e++){if(!e3(r[e])||!e3(n[e]))return;let t=sH(r[e]),o=sH(n[e]);s+=t*o,i+=t*t,a+=o*o}let o=Math.sqrt(i)*Math.sqrt(a);if(0!==o)return 1-Math.max(-1,Math.min(1,s/o))}}class ij extends iz{qr(e,t){let r=e?.values??[],n=t?.values??[];if(0===r.length)return 0;let s=0;for(let e=0;e<r.length;e++){if(!e3(r[e])||!e3(n[e]))return;s+=sH(r[e])*sH(n[e])}return s}}class iK extends iz{qr(e,t){let r=e?.values??[],n=t?.values??[];if(0===r.length)return 0;let s=0;for(let e=0;e<r.length;e++){if(!e3(r[e])||!e3(n[e]))return;s+=Math.pow(sH(r[e])-sH(n[e]),2)}return Math.sqrt(s)}}class iG{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,39044);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"VECTOR":{let e=e7(r.value);return sB.newValue({integerValue:e?.values?.length??0})}case"NULL":return sB.Dr();default:return sB.vr()}}}let iH=BigInt(-0xe7791f700),iW=BigInt(0x3afff4417f),iY=BigInt(1e3),iJ=BigInt(1e6),iX=iH*iY,iZ=iW*iY+BigInt(999),i0=iH*iJ,i1=iW*iJ+BigInt(999999);function i2(e){return e>=i0&&e<=i1}function i3(e,t){let r=BigInt(e);return!(r<iH||r>iW)&&!(t<0||t>=1e9)&&(r!==iH||0===t)&&!(r===iW&&t>0x3b9ac9ff)}function i4(e,t){return t<0?{seconds:e-1,nanos:t+1e9}:{seconds:e,nanos:t}}function i6(e){return BigInt(e.seconds)*iJ+BigInt(Math.trunc(e.nanoseconds/1e3))}class i5{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,49262,`${this.expr.name}() function should have exactly one parameter`);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"INT":return this.toTimestamp(BigInt(r.value.integerValue));case"NULL":return sB.Dr();default:return sB.vr()}}}class i8 extends i5{toTimestamp(e){if(!i2(e))return sB.vr();let t=Number(e/iJ),r=Number(e%iJ*BigInt(1e3)),n=i4(t,r);return i3(t=n.seconds,r=n.nanos)?sB.newValue({timestampValue:{seconds:t,nanos:r}}):sB.vr()}}class i9 extends i5{toTimestamp(e){if(!(e>=iX&&e<=iZ))return sB.vr();let t=Number(e/iY),r=Number(e%iY*BigInt(1e6)),n=i4(t,r);return i3(t=n.seconds,r=n.nanos)?sB.newValue({timestampValue:{seconds:t,nanos:r}}):sB.vr()}}class i7 extends i5{toTimestamp(e){if(!(e>=iH&&e<=iW))return sB.vr();let t=Number(e);return sB.newValue({timestampValue:{seconds:t,nanos:0}})}}class ae{constructor(e){this.expr=e}evaluate(e,t){N(1===this.expr.params.length,1265,`${this.expr.name}() function should have exactly one parameter`);let r=sQ(this.expr.params[0]).evaluate(e,t);switch(r.type){case"TIMESTAMP":break;case"NULL":return sB.Dr();default:return sB.vr()}let n=rq(r.value.timestampValue);return i3(n.seconds,n.nanoseconds)?this.$r(n):sB.vr()}}class at extends ae{$r(e){let t=i6(e);return i2(t)?sB.newValue({integerValue:`${t.toString()}`}):sB.vr()}}class ar extends ae{$r(e){let t=i6(e),r=t/BigInt(1e3),n=t%BigInt(1e3);return r>BigInt(0)||n===BigInt(0)?sB.newValue({integerValue:r.toString()}):sB.newValue({integerValue:(r-BigInt(1)).toString()})}}class an extends ae{$r(e){let t=BigInt(e.seconds);return t>=iH&&t<=iW?sB.newValue({integerValue:t.toString()}):sB.vr()}}class as{constructor(e){this.expr=e}evaluate(e,t){let r,n;N(3===this.expr.params.length,2775,`${this.expr.name}() function should have exactly 3 parameters`);let s=!1,i=sQ(this.expr.params[0]).evaluate(e,t);switch(i.type){case"TIMESTAMP":break;case"NULL":s=!0;break;default:return sB.vr()}let a=sQ(this.expr.params[1]).evaluate(e,t);switch(a.type){case"STRING":if(void 0===(r=function(e){switch(e){case"microsecond":return"microsecond";case"millisecond":return"millisecond";case"second":return"second";case"minute":return"minute";case"hour":return"hour";case"day":return"day";default:return}}(a.value.stringValue)))return sB.vr();break;case"NULL":s=!0;break;default:return sB.vr()}let o=sQ(this.expr.params[2]).evaluate(e,t);switch(o.type){case"INT":break;case"NULL":s=!0;break;default:return sB.vr()}if(s)return sB.Dr();
3let l=BigInt(o.value.integerValue);try{switch(r){case"microsecond":n=l;break;case"millisecond":n=l*BigInt(1e3);break;case"second":n=l*BigInt(1e6);break;case"minute":n=l*BigInt(6e7);break;case"hour":n=l*BigInt(36e8);break;case"day":n=l*BigInt(864e8);break;default:return sB.vr()}if("microsecond"!==r&&l!==BigInt(0)&&n/l!==BigInt(this.Kr(r)))return sB.vr()}catch(e){return E(`Error during timestamp arithmetic: ${e}`),sB.vr()}let u=rq(i.value.timestampValue);if(!i3(u.seconds,u.nanoseconds))return sB.vr();let c=i6(u),h=this.Wr(c,n);if(!i2(h))return sB.vr();let d=Number(h/iJ),m=h%iJ,f=Number((m<0?m+iJ:m)*BigInt(1e3)),p=m<0?d-1:d;return i3(p,f)?sB.newValue({timestampValue:{seconds:p,nanos:f}}):sB.vr()}Kr(e){switch(e){case"millisecond":return 1e3;case"second":return 1e6;case"minute":return 6e7;case"hour":return 36e8;case"day":return 864e8;default:return 1}}}class ai extends as{Wr(e,t){return e+t}}class aa extends as{Wr(e,t){return e-t}}function ao(e){if((e=sz(e))instanceof su)return`fld(${e.fieldName})`;if(e instanceof sh){var t;return`cst(${null===(t=e.value)?"null":"number"==typeof t?t.toString():"string"==typeof t?`"${t}"`:t instanceof nL?`ref(${t.path})`:t instanceof nM?`vec(${JSON.stringify(t)})`:JSON.stringify(t)})`}if(e instanceof sf)return`fn(${e.name},[${e.params.map(ao).join(",")}])`;if("ListOfExpressions"===e.expressionType)return`list([${e.Rr.map(ao).join(",")}])`;throw Error(`Unrecognized expr ${JSON.stringify(e,null,2)}`)}function al(e){return`${Array.from(e.entries()).sort().map(([e,t])=>`${e}=${ao(t)}`).join(",")}`}function au(e){return e.stages.map(e=>(function(e){if(e instanceof sE)return`${e._name}(${al(e.fields)})`;if(e instanceof sT){let t=`${e._name}(${al(e.accumulators)})`;return e.groups.size>0&&(t+=`grouping(${al(e.groups)})`),t}if(e instanceof sx)return`${e._name}(${al(e.groups)})`;if(e instanceof sb)return`${e._name}(${e.Vr})`;if(e instanceof sN)return`${e._name}(${e.collectionId})`;if(e instanceof sS)return`${e._name}()`;if(e instanceof sI)return`${e._name}(${e.dr.sort()})`;if(e instanceof sV)return`${e._name}(${ao(e.condition)})`;if(e instanceof sC)return`${e._name}(${e.limit})`;if(e instanceof sk)return`${e._name}(${e.orderings.map(e=>`${ao(e.expr)}${e.direction}`).join(",")})`;throw Error(`Unrecognized stage ${e._name}`)})(e)).join("|")}function ac(e){return e instanceof sU}function ah(e){return ac(e)?au(e):ra(e)}function ad(e){return ac(e)?au(e):`${t1(re(e))}|lt:${e.limitType}`}function am(e,t){return e instanceof sU&&t instanceof sU?au(e)===au(t):!(e instanceof sU&&!(t instanceof sU)||!(e instanceof sU)&&t instanceof sU)&&t2(re(e),re(t))&&e.limitType===t.limitType}function af(e){return t3(e)?au(e):t1(e)}function ap(e,t){return e instanceof sU&&t instanceof sU?au(e)===au(t):!(e instanceof sU&&!(t instanceof sU)||!(e instanceof sU)&&t instanceof sU)&&t2(e,t)}class ag{constructor(e,t,r,n){this.batchId=e,this.localWriteTime=t,this.baseMutations=r,this.mutations=n}applyToRemoteDocument(e,t){let r=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let n=this.mutations[t];n.key.isEqual(e.key)&&function(e,t,r){let n,s;e instanceof tV?(n=e.value.clone(),s=tD(e.fieldTransforms,t,r.transformResults),n.setAll(s),t.convertToFoundDocument(r.version,n).setHasCommittedMutations()):e instanceof tC?function(e,t,r){if(!tx(e.precondition,t))return t.convertToUnknownDocument(r.version);let n=tD(e.fieldTransforms,t,r.transformResults),s=t.data;s.setAll(tA(e)),s.setAll(n),t.convertToFoundDocument(r.version,s).setHasCommittedMutations()}(e,t,r):t.convertToNoDocument(r.version).setHasCommittedMutations()}(n,e,r[t])}}applyToLocalView(e,t){for(let r of this.baseMutations)r.key.isEqual(e.key)&&(t=tS(r,e,t,this.localWriteTime));for(let r of this.mutations)r.key.isEqual(e.key)&&(t=tS(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let r=rg();return this.mutations.forEach(n=>{let s=e.get(n.key),i=s.overlayedDocument,a=this.applyToLocalView(i,s.mutatedFields),o=tN(i,a=t.has(n.key)?null:a);null!==o&&r.set(n.key,o),i.isValidDocument()||i.convertToNoDocument(es.min())}),r}keys(){return this.mutations.reduce((e,t)=>
3e.add(t.key),rv())}isEqual(e){return this.batchId===e.batchId&&B(this.mutations,e.mutations,(e,t)=>tI(e,t))&&B(this.baseMutations,e.baseMutations,(e,t)=>tI(e,t))}}class ay{constructor(e,t,r,n){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=n}static from(e,t,r){N(e.mutations.length===r.length,58842,{Qr:e.mutations.length,Gr:r.length});let n=ry,s=e.mutations;for(let e=0;e<s.length;e++)n=n.insert(s[e].key,r[e].version);return new ay(e,t,r,n)}}class aw{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{ 4 largestBatchId: ${this.largestBatchId}, 5 mutation: ${this.mutation.toString()} 6 }`}}class av{constructor(e,t,r,n,s=es.min(),i=es.min(),a=ex.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=n,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new av(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new av(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new av(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new av(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class a_{constructor(e){this.zr=e}}class aE{Yr(e,t){this.Zr(e,t),t.Xr()}Zr(e,t){if("nullValue"in e)this.ei(t,5);else if("booleanValue"in e)this.ei(t,10),t.ti(+!!e.booleanValue);else if("integerValue"in e)this.ei(t,15),t.ti(eS(e.integerValue));else if("doubleValue"in e){let r=eS(e.doubleValue);
6isNaN(r)?this.ei(t,13):(this.ei(t,15),ed(r)?t.ti(0):t.ti(r))}else if("timestampValue"in e){let r=e.timestampValue;this.ei(t,20),"string"==typeof r&&(r=eN(r)),t.ni(`${r.seconds||""}`),t.ti(r.nanos||0)}else if("stringValue"in e)this.ri(e.stringValue,t),this.ii(t);else if("bytesValue"in e)this.ei(t,30),t.si(eI(e.bytesValue)),this.ii(t);else if("referenceValue"in e)this._i(e.referenceValue,t);else if("geoPointValue"in e){let r=e.geoPointValue;this.ei(t,45),t.ti(r.latitude||0),t.ti(r.longitude||0)}else"mapValue"in e?tt(e)?this.ei(t,Number.MAX_SAFE_INTEGER):e9(e)?this.oi(e.mapValue,t):(this.ai(e.mapValue,t),this.ii(t)):"arrayValue"in e?(this.ui(e.arrayValue,t),this.ii(t)):x(19022,{ci:e})}ri(e,t){this.ei(t,25),this.li(e,t)}li(e,t){t.ni(e)}ai(e,t){let r=e.fields||{};for(let e of(this.ei(t,55),Object.keys(r)))this.ri(e,t),this.Zr(r[e],t)}oi(e,t){let r=e.fields||{};this.ei(t,53);let n=r[ez].arrayValue?.values?.length||0;this.ei(t,15),t.ti(eS(n)),this.ri(ez,t),this.Zr(r[ez],t)}ui(e,t){let r=e.values||[];for(let e of(this.ei(t,50),r))this.Zr(e,t)}_i(e,t){this.ei(t,37),G.fromName(e).path.forEach(e=>{this.ei(t,60),this.li(e,t)})}ei(e,t){e.ti(t)}ii(e){e.ti(2)}}aE.Ei=new aE;class aT{constructor(){this.Hi=new ax}addToCollectionParentIndex(e,t){return this.Hi.add(t),eu.resolve()}getCollectionParents(e,t){return eu.resolve(this.Hi.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(ea.min())}getMinOffsetFromCollectionGroup(e,t){return eu.resolve(ea.min())}updateCollectionGroup(e,t,r){return eu.resolve()}updateIndexEntries(e,t){return eu.resolve()}}class ax{constructor(){this.index={}}add(e){let t=e.lastSegment(),r=e.popLast(),n=this.index[t]||new eg(Q.comparator),s=!n.has(r);return this.index[t]=n.add(r),s}has(e){let t=e.lastSegment(),r=e.popLast(),n=this.index[t];return n&&n.has(r)}getEntries(e){return(this.index[e]||new eg(Q.comparator)).toArray()}}new Uint8Array(0);class ab{constructor(e){this.Ds=e}next(){return this.Ds+=2,this.Ds}static xs(){return new ab(0)}static Cs(){return new ab(-1)}}function aN(e,t){let r=t;for(let t of e.stages)r=function(e,t,r){if(t instanceof sb)return r.filter(e=>e.isFoundDocument()&&`/${e.key.getCollectionPath().canonicalString()}`===t.Vr);if(t instanceof sV)return r.filter(r=>{let n=sq(sQ(t.condition).evaluate(e,r));return void 0!==n&&eH(n,ej)});if(t instanceof sN)return r.filter(e=>e.isFoundDocument()&&e.key.getCollectionPath().lastSegment()===t.collectionId);if(t instanceof sS)return r.filter(e=>e.isFoundDocument());if(t instanceof sI)return r.filter(e=>e.isFoundDocument()&&t.mr.has(e.key.path.toStringWithLeadingSlash()));if(t instanceof sC)return r.slice(0,t.limit);if(t instanceof sk){let n;return n=t.orderings.map(e=>({ks:sQ(e.expr),direction:e.direction})),[...r].sort((t,r)=>{for(let{ks:s,direction:i}of n){let n=eY(sq(s.evaluate(e,t))??eQ,sq(s.evaluate(e,r))??eQ);if(0!==n)return"ascending"===i?n:-n}return 0})}throw Error(`Unknown stage: ${t._name}`)}({serializer:e.serializer,serverTimestampBehavior:e.listenOptions?.serverTimestampBehavior},t,r);return r}function aS(e,t){return aN(e,[t]).length>0}function aI(e){let t=function(e){for(let t=e.stages.length-1;t>=0;t--){let r=e.stages[t];if(r instanceof sk)return r.orderings}throw Error("Pipeline must contain at least one Sort stage")}(e);return(r,n)=>{for(let s of t){let t=eY(sq(sQ(s.expr).evaluate({serializer:e.serializer},r))||eQ,sq(sQ(s.expr).evaluate({serializer:e.serializer},n))||eQ);if(0!==t)return"ascending"===s.direction?t:-t}return 0}}function aV(e){for(let t=e.stages.length-1;t>=0;t--){let r=e.stages[t];if(r instanceof sC)return{limit:r.limit}}}class aC{constructor(){this.changes=new rh(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,tX.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let r=this.changes.get(t);return void 0!==r?eu.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}
6assertNotApplied(){}}class aA{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class aD{constructor(e,t,r,n){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=r,this.indexManager=n}getDocument(e,t){let r=null;return this.documentOverlayCache.getOverlay(e,t).next(n=>(r=n,this.remoteDocumentCache.getEntry(e,t))).next(e=>(null!==r&&tS(r.mutation,e,ew.empty(),en.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,rv()).next(()=>t))}getLocalViewOfDocuments(e,t,r=rv()){let n=rg();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,r).next(e=>{let t=rf();return e.forEach((e,r)=>{t=t.insert(e,r.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let r=rg();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,rv()))}populateOverlays(e,t,r){let n=[];return r.forEach(e=>{t.has(e)||n.push(e)}),this.documentOverlayCache.getOverlays(e,n).next(e=>{e.forEach((e,r)=>{t.set(e,r)})})}computeViews(e,t,r,n){let s=rd,i=rg(),a=rg();return t.forEach((e,t)=>{let a=r.get(t.key);n.has(t.key)&&(void 0===a||a.mutation instanceof tC)?s=s.insert(t.key,t):void 0!==a?(i.set(t.key,a.mutation.getFieldMask()),tS(a.mutation,t,a.mutation.getFieldMask(),en.now())):i.set(t.key,ew.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>i.set(e,t)),t.forEach((e,t)=>a.set(e,new aA(t,i.get(e)??null))),a))}recalculateAndSaveOverlays(e,t){let r=rg(),n=new em((e,t)=>e-t),s=rv();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let s of e)s.keys().forEach(e=>{let i=t.get(e);if(null===i)return;let a=r.get(e)||ew.empty();a=s.applyToLocalView(i,a),r.set(e,a);let o=(n.get(s.batchId)||rv()).add(e);n=n.insert(s.batchId,o)})}).next(()=>{let i=[],a=n.getReverseIterator();for(;a.hasNext();){let n=a.getNext(),o=n.key,l=n.value,u=rg();l.forEach(e=>{if(!s.has(e)){let n=tN(t.get(e),r.get(e));null!==n&&u.set(e,n),s=s.add(e)}}),i.push(this.documentOverlayCache.saveOverlays(e,o,u))}return eu.waitFor(i)}).next(()=>r)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,r,n){return ac(t)?this.getDocumentsMatchingPipeline(e,t,r,n):G.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):t9(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,r,n):this.getDocumentsMatchingCollectionQuery(e,t,r,n)}getNextDocuments(e,t,r,n){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,r,n).next(s=>{let i=n-s.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,r.largestBatchId,n-s.size):eu.resolve(rg()),a=-1,o=s;return i.next(t=>eu.forEach(t,(t,r)=>(a<r.largestBatchId&&(a=r.largestBatchId),s.get(t)?eu.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,s)).next(()=>this.computeViews(e,o,t,rv())).next(e=>({batchId:a,changes:rp(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new G(t)).next(e=>{let t=rf();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,r,n){let s=t.collectionGroup,i=rf();return this.indexManager.getCollectionParents(e,s).next(a=>eu.forEach(a,a=>{let o=new t6(a.child(s),null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(e,o,r,n).next(e=>{e.forEach((e,t)=>{i=i.insert(e,t)})})}).next(()=>i))}getDocumentsMatchingCollectionQuery(e,t,r,n){let s;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,r.largestBatchId).next(i=>(s=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,s,n))).next(e=>this.retrieveMatchingLocalDocuments(s,e,e=>ro(t,e)))}getDocumentsMatchingPipeline(e,t,r,n){if("collection_group"===sO(t)){let s=sM(t),i=rf();return this.indexManager.getCollectionParents(e,s).next(a=>eu.forEach(a,a=>{var o;let l,u=(o=a.child(s),l=t.stages.map(e=>e instanceof sN?new sb(o.canonicalString(),{}):e),new sU(t.serializer,l));return this.getDocumentsMatchingPipeline(e,u,r,n).next(e=>{e.forEach((e,t)=>{i=i.insert(e,t)})})}).next(()=>i))}{let s;return this.getOverlaysForPipeline(e,t,r.largestBatchId).next(i=>
6{switch(s=i,sO(t)){case"collection":return this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,s,n);case"documents":let a=rv();for(let e of sF(t))a=a.add(G.fromPath(e));return this.remoteDocumentCache.getEntries(e,a);case"database":return this.remoteDocumentCache.getAllEntries(e);default:throw new I("invalid-argument",`Invalid pipeline source to execute offline: ${au(t)}`)}}).next(e=>this.retrieveMatchingLocalDocuments(s,e,e=>aS(t,e)))}}retrieveMatchingLocalDocuments(e,t,r){e.forEach((e,r)=>{let n=r.getKey();null===t.get(n)&&(t=t.insert(n,tX.newInvalidDocument(n)))});let n=rf();return t.forEach((t,s)=>{let i=e.get(t);void 0!==i&&tS(i.mutation,s,ew.empty(),en.now()),r(s)&&(n=n.insert(t,s))}),n}getOverlaysForPipeline(e,t,r){switch(sO(t)){case"collection":return this.documentOverlayCache.getOverlaysForCollection(e,Q.fromString(sP(t)),r);case"collection_group":throw new I("invalid-argument",`Unexpected collection group pipeline: ${au(t)}`);case"documents":return this.documentOverlayCache.getOverlays(e,sF(t).map(e=>G.fromPath(e)));case"database":return this.documentOverlayCache.getAllOverlays(e,r);default:throw new I("invalid-argument",`Failed to get overlays for pipeline: ${au(t)}`)}}}class ak{constructor(e){this.serializer=e,this.Hs=new Map,this.Js=new Map}getBundleMetadata(e,t){return eu.resolve(this.Hs.get(t))}saveBundleMetadata(e,t){return this.Hs.set(t.id,{id:t.id,version:t.version,createTime:rj(t.createTime)}),eu.resolve()}getNamedQuery(e,t){return eu.resolve(this.Js.get(t))}saveNamedQuery(e,t){var r;let n;return this.Js.set(t.name,{name:t.name,query:(n=function(e){var t,r,n,s;let i,a,o,l,u,c=4===(i=rH(e.parent)).length?Q.emptyPath():rZ(i),h=e.structuredQuery,d=h.from?h.from.length:0,m=null;if(d>0){N(1===d,65062);let e=h.from[0];e.allDescendants?m=e.collectionId:c=c.child(e.collectionId)}let f=[];h.where&&(f=(a=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=r2(e.unaryFilter.field);return tF.create(t,"==",{doubleValue:NaN});case"IS_NULL":let r=r2(e.unaryFilter.field);return tF.create(r,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let n=r2(e.unaryFilter.field);return tF.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let s=r2(e.unaryFilter.field);return tF.create(s,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return x(61313);default:return x(60726)}}(t):void 0!==t.fieldFilter?tF.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 x(58110);default:return x(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?t$.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return x(1026)}}(t.compositeFilter.op)):x(30097,{filter:t})}(h.where))instanceof t$&&tq(t=a)&&tB(t)?a.getFilters():[a]);let p=[];h.orderBy&&(p=h.orderBy.map(e=>new tJ(r2(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let g=null;h.limit&&(g=null==(o="object"==typeof(r=h.limit)?r.value:r)?null:o);let y=null;h.startAt&&(l=!!(n=h.startAt).before,y=new tU(n.values||[],l));let w=null;return h.endAt&&(u=!(s=h.endAt).before,w=new tU(s.values||[],u)),new t6(c,m,p,f,g,"F",y,w)}({parent:(r=t.bundledQuery).parent,structuredQuery:r.structuredQuery}),"LAST"===r.limitType?rn(n,n.limit,"L"):n),readTime:rj(t.readTime)}),eu.resolve()}}class aR{constructor(){this.overlays=new em(G.comparator),this.Ys=new Map}getOverlay(e,t){return eu.resolve(this.overlays.get(t))}getOverlays(e,t){let r=rg();return eu.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&r.set(t,e)})).next(()=>r)}getAllOverlays(e,t){let r=rg();return this.overlays.forEach((e,n)=>{n.largestBatchId>t&&r.set(e,n)}),eu.resolve(r)}saveOverlays(e,t,r){return r.forEach((r,n)=>{this.Hr(e,t,n)}),eu.resolve()}removeOverlaysForBatchId(e,t,r){let n=this.Ys.get(r);
6return void 0!==n&&(n.forEach(e=>this.overlays=this.overlays.remove(e)),this.Ys.delete(r)),eu.resolve()}getOverlaysForCollection(e,t,r){let n=rg(),s=t.length+1,i=new G(t.child("")),a=this.overlays.getIteratorFrom(i);for(;a.hasNext();){let e=a.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>r&&n.set(e.getKey(),e)}return eu.resolve(n)}getOverlaysForCollectionGroup(e,t,r,n){let s=new em((e,t)=>e-t),i=this.overlays.getIterator();for(;i.hasNext();){let e=i.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>r){let t=s.get(e.largestBatchId);null===t&&(t=rg(),s=s.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=rg(),o=s.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=n)););return eu.resolve(a)}Hr(e,t,r){let n=this.overlays.get(r.key);if(null!==n){let e=this.Ys.get(n.largestBatchId).delete(r.key);this.Ys.set(n.largestBatchId,e)}this.overlays=this.overlays.insert(r.key,new aw(t,r));let s=this.Ys.get(t);void 0===s&&(s=rv(),this.Ys.set(t,s)),this.Ys.set(t,s.add(r.key))}}class aL{constructor(){this.sessionToken=ex.EMPTY_BYTE_STRING}getSessionToken(e){return eu.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,eu.resolve()}}class aU{constructor(){this.Zs=new eg(aO.Xs),this.e_=new eg(aO.t_)}isEmpty(){return this.Zs.isEmpty()}addReference(e,t){let r=new aO(e,t);this.Zs=this.Zs.add(r),this.e_=this.e_.add(r)}n_(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.r_(new aO(e,t))}i_(e,t){e.forEach(e=>this.removeReference(e,t))}s_(e){let t=new G(new Q([])),r=new aO(t,e),n=new aO(t,e+1),s=[];return this.e_.forEachInRange([r,n],e=>{this.r_(e),s.push(e.key)}),s}__(){this.Zs.forEach(e=>this.r_(e))}r_(e){this.Zs=this.Zs.delete(e),this.e_=this.e_.delete(e)}o_(e){let t=new G(new Q([])),r=new aO(t,e),n=new aO(t,e+1),s=rv();return this.e_.forEachInRange([r,n],e=>{s=s.add(e.key)}),s}containsKey(e){let t=new aO(e,0),r=this.Zs.firstAfterOrEqual(t);return null!==r&&e.isEqual(r.key)}}class aO{constructor(e,t){this.key=e,this.a_=t}static Xs(e,t){return G.comparator(e.key,t.key)||M(e.a_,t.a_)}static t_(e,t){return M(e.a_,t.a_)||G.comparator(e.key,t.key)}}class aP{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.gs=1,this.u_=new eg(aO.Xs)}checkEmpty(e){return eu.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,r,n){let s=this.gs;this.gs++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let i=new ag(s,t,r,n);for(let t of(this.mutationQueue.push(i),n))this.u_=this.u_.add(new aO(t.key,s)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return eu.resolve(i)}lookupMutationBatch(e,t){return eu.resolve(this.c_(t))}getNextMutationBatchAfterBatchId(e,t){let r=this.l_(t+1),n=r<0?0:r;return eu.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return eu.resolve(0===this.mutationQueue.length?-1:this.gs-1)}getAllMutationBatches(e){return eu.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let r=new aO(t,0),n=new aO(t,1/0),s=[];return this.u_.forEachInRange([r,n],e=>{let t=this.c_(e.a_);s.push(t)}),eu.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new eg(M);return t.forEach(e=>{let t=new aO(e,0),n=new aO(e,1/0);this.u_.forEachInRange([t,n],e=>{r=r.add(e.a_)})}),eu.resolve(this.E_(r))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,n=r.length+1,s=r;G.isDocumentKey(s)||(s=s.child(""));let i=new aO(new G(s),0),a=new eg(M);return this.u_.forEachWhile(e=>{let t=e.key.path;return!!r.isPrefixOf(t)&&(t.length===n&&(a=a.add(e.a_)),!0)},i),eu.resolve(this.E_(a))}E_(e){let t=[];return e.forEach(e=>{let r=this.c_(e);null!==r&&t.push(r)}),t}removeMutationBatch(e,t){N(0===this.h_(t.batchId,"removed"),55003),this.mutationQueue.shift();let r=this.u_;return eu.forEach(t.mutations,n=>{let s=new aO(n.key,t.batchId);return r=r.delete(s),this.referenceDelegate.markPotentiallyOrphaned(e,n.key)}).next(()=>{this.u_=r})}bs(e){}containsKey(e,t){let r=new aO(t,0),n=this.u_.firstAfterOrEqual(r);return eu.resolve(t.isEqual(n&&n.key))}
6performConsistencyCheck(e){return this.mutationQueue.length,eu.resolve()}h_(e,t){return this.l_(e)}l_(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}c_(e){let t=this.l_(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class aM{constructor(e){this.T_=e,this.docs=new em(G.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let r=t.key,n=this.docs.get(r),s=n?n.size:0,i=this.T_(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:i}),this.size+=i-s,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let r=this.docs.get(t);return eu.resolve(r?r.document.mutableCopy():tX.newInvalidDocument(t))}getEntries(e,t){let r=rd;return t.forEach(e=>{let t=this.docs.get(e);r=r.insert(e,t?t.document.mutableCopy():tX.newInvalidDocument(e))}),eu.resolve(r)}getAllEntries(e){let t=rd;return this.docs.forEach((e,r)=>{t=t.insert(e,r.document)}),eu.resolve(t)}getDocumentsMatchingQuery(e,t,r,n){let s,i;ac(t)?(s=Q.fromString(sP(t)),i=e=>aS(t,e)):(s=t.path,i=e=>ro(t,e));let a=rd,o=new G(s.child("__id-9223372036854775808__")),l=this.docs.getIteratorFrom(o);for(;l.hasNext();){let{key:e,value:{document:t}}=l.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||0>=function(e,t){let r=e.readTime.compareTo(t.readTime);return 0!==r||0!==(r=G.comparator(e.documentKey,t.documentKey))?r:M(e.largestBatchId,t.largestBatchId)}(new ea(t.readTime,t.key,-1),r)||(n.has(t.key)||i(t))&&(a=a.insert(t.key,t.mutableCopy()))}return eu.resolve(a)}getAllFromCollectionGroup(e,t,r,n){x(9500)}P_(e,t){return eu.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new aF(this)}getSize(e){return eu.resolve(this.size)}}class aF extends aC{constructor(e){super(),this.zs=e}applyChanges(e){let t=[];
6return this.changes.forEach((r,n)=>{n.isValidDocument()?t.push(this.zs.addEntry(e,n)):this.zs.removeEntry(r)}),eu.waitFor(t)}getFromCache(e,t){return this.zs.getEntry(e,t)}getAllFromCache(e,t){return this.zs.getEntries(e,t)}}class a${constructor(e){this.persistence=e,this.R_=new rh(e=>af(e),ap),this.lastRemoteSnapshotVersion=es.min(),this.highestTargetId=0,this.I_=0,this.A_=new aU,this.targetCount=0,this.V_=ab.xs()}forEachTarget(e,t){return this.R_.forEach((e,r)=>t(r)),eu.resolve()}getLastRemoteSnapshotVersion(e){return eu.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return eu.resolve(this.I_)}allocateTargetId(e){return this.highestTargetId=this.V_.next(),eu.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.I_&&(this.I_=t),eu.resolve()}Ms(e){this.R_.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.V_=new ab(t),this.highestTargetId=t),e.sequenceNumber>this.I_&&(this.I_=e.sequenceNumber)}addTargetData(e,t){return this.Ms(t),this.targetCount+=1,eu.resolve()}updateTargetData(e,t){return this.Ms(t),eu.resolve()}removeTargetData(e,t){return this.R_.delete(t.target),this.A_.s_(t.targetId),this.targetCount-=1,eu.resolve()}removeTargets(e,t,r){let n=0,s=[];return this.R_.forEach((i,a)=>{a.sequenceNumber<=t&&null===r.get(a.targetId)&&(this.R_.delete(i),s.push(this.removeMatchingKeysForTargetId(e,a.targetId)),n++)}),eu.waitFor(s).next(()=>n)}getTargetCount(e){return eu.resolve(this.targetCount)}getTargetData(e,t){let r=this.R_.get(t)||null;return eu.resolve(r)}addMatchingKeys(e,t,r){return this.A_.n_(t,r),eu.resolve()}removeMatchingKeys(e,t,r){this.A_.i_(t,r);let n=this.persistence.referenceDelegate,s=[];return n&&t.forEach(t=>{s.push(n.markPotentiallyOrphaned(e,t))}),eu.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.A_.s_(t),eu.resolve()}getMatchingKeysForTargetId(e,t){let r=this.A_.o_(t);return eu.resolve(r)}containsKey(e,t){return eu.resolve(this.A_.containsKey(t))}}class aB{constructor(e,t){this.d_={},this.overlays={},this.f_=new eh(0),this.m_=!1,this.m_=!0,this.p_=new aL,this.referenceDelegate=e(this),this.g_=new a$(this),this.indexManager=new aT,this.remoteDocumentCache=function(e){return new aM(e)}(e=>this.referenceDelegate.y_(e)),this.serializer=new a_(t),this.w_=new ak(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.m_=!1,Promise.resolve()}get started(){return this.m_}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new aR,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this.d_[e.toKey()];return r||(r=new aP(t,this.referenceDelegate),this.d_[e.toKey()]=r),r}getGlobalsCache(){return this.p_}getTargetCache(){return this.g_}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.w_}runTransaction(e,t,r){v("MemoryPersistence","Starting transaction:",e);let n=new aq(this.f_.next());return this.referenceDelegate.b_(),r(n).next(e=>this.referenceDelegate.v_(n).next(()=>e)).toPromise().then(e=>(n.raiseOnCommittedEvent(),e))}S_(e,t){return eu.or(Object.values(this.d_).map(r=>()=>r.containsKey(e,t)))}}class aq extends eo{constructor(e){super(),this.currentSequenceNumber=e}}class az{constructor(e){this.persistence=e,this.D_=new aU,this.x_=null}static C_(e){return new az(e)}get F_(){if(this.x_)return this.x_;throw x(60996)}addReference(e,t,r){return this.D_.addReference(r,t),this.F_.delete(r.toString()),eu.resolve()}removeReference(e,t,r){return this.D_.removeReference(r,t),this.F_.add(r.toString()),eu.resolve()}markPotentiallyOrphaned(e,t){return this.F_.add(t.toString()),eu.resolve()}removeTarget(e,t){this.D_.s_(t.targetId).forEach(e=>this.F_.add(e.toString()));let r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.F_.add(e.toString()))}).next(()=>r.removeTargetData(e,t))}b_(){this.x_=new Set}v_(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return eu.forEach(this.F_,r=>{let n=G.fromPath(r);return this.O_(e,n).next(e=>{e||t.removeEntry(n,es.min())})}).next(()=>(this.x_=null,t.apply(e)))}updateLimboDocument(e,t){return this.O_(e,t).next(e=>{e?this.F_.delete(t.toString()):this.F_.add(t.toString())})}y_(e){return 0}O_(e,t){return eu.or([()=>eu.resolve(this.D_.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.S_(e,t)])}}class aQ{constructor(e,t){this.persistence=e,this.M_=new rh(e=>(function(e){let t="";for(let r=0;r<e.length;r++)t.length>0&&(t+="\x01\x01"),t=function(e,t){let r=t,n=e.length;for(let t=0;t<n;t++){let n=e.charAt(t);switch(n){case"\0":r+="\x01\x10";break;case"\x01":r+="\x01\x11";break;default:r+=n}}return r}(e.get(r),t);return t+"\x01\x01"})(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=function(e,t){return new nC(e,t)}(this,t)}static C_(e,t){return new aQ(e,t)}b_(){}v_(e){return eu.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEac
6hTarget(e,t)}lr(e){let t=this.Ls(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}Ls(e){let t=0;return this.Er(e,e=>{t++}).next(()=>t)}Er(e,t){return eu.forEach(this.M_,(r,n)=>this.Us(e,r,n).next(e=>e?eu.resolve():t(n)))}removeTargets(e,t,r){return this.persistence.getTargetCache().removeTargets(e,t,r)}removeOrphanedDocuments(e,t){let r=0,n=this.persistence.getRemoteDocumentCache(),s=n.newChangeBuffer();return n.P_(e,n=>this.Us(e,n,t).next(e=>{e||(r++,s.removeEntry(n,es.min()))})).next(()=>s.apply(e)).next(()=>r)}markPotentiallyOrphaned(e,t){return this.M_.set(t,e.currentSequenceNumber),eu.resolve()}removeTarget(e,t){let r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.M_.set(r,e.currentSequenceNumber),eu.resolve()}removeReference(e,t,r){return this.M_.set(r,e.currentSequenceNumber),eu.resolve()}updateLimboDocument(e,t){return this.M_.set(t,e.currentSequenceNumber),eu.resolve()}y_(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(eG(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let r=eR(t);return r?16+e(r):16;case 5:return 2*t.stringValue.length;case 6:return eI(t.bytesValue).approximateByteSize();case 7:return t.referenceValue.length;case 9:return(t.arrayValue.values||[]).reduce((t,r)=>t+e(r),0);case 10:case 11:var n;let s;return n=t.mapValue,s=0,e_(n.fields,(t,r)=>{s+=t.length+e(r)}),s;default:throw x(13486,{value:t})}}(e.data.value)),t}Us(e,t,r){return eu.or([()=>this.persistence.S_(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.M_.get(t);return eu.resolve(void 0!==e&&e>r)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class aj{constructor(e,t,r,n){this.targetId=e,this.fromCache=t,this.wo=r,this.bo=n}static vo(e,t){let r=rv(),n=rv();for(let e of t.docChanges)switch(e.type){case 0:r=r.add(e.doc.key);break;case 1:n=n.add(e.doc.key)}return new aj(e,t.fromCache,r,n)}}function aK(e,t){return G.comparator(e.key,t.key)}class aG{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class aH{constructor(){this.So=!1,this.Do=!1,this.xo=100,this.Co=function(){let e;return(0,l.nr)()?8:Number((e=(0,l.ZQ)().match(/Android ([\d.]+)/i))?e[1].split(".").slice(0,2).join("."):"-1")>0?6:4}()}initialize(e,t){this.Fo=e,this.indexManager=t,this.So=!0}getDocumentsMatchingQuery(e,t,r,n){let s={result:null};return this.Oo(e,t).next(e=>{s.result=e}).next(()=>{if(!s.result)return this.Mo(e,t,n,r).next(e=>{s.result=e})}).next(()=>{if(s.result)return;let r=new aG;return this.No(e,t,r).next(n=>{if(s.result=n,this.Do)return this.Lo(e,t,r,n.size)})}).next(()=>s.result)}Lo(e,t,r,n){return ac(t)?eu.resolve():r.documentReadCount<this.xo?(w()<=c.$b.DEBUG&&v("QueryEngine","SDK will not create cache indexes for query:",ra(t),"since it only creates cache indexes for collection contains","more than or equal to",this.xo,"documents"),eu.resolve()):(w()<=c.$b.DEBUG&&v("QueryEngine","Query:",ra(t),"scans",r.documentReadCount,"local documents and returns",n,"documents as results."),r.documentReadCount>this.Co*n?(w()<=c.$b.DEBUG&&v("QueryEngine","The SDK decides to create cache indexes for query:",ra(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,re(t))):eu.resolve())}Oo(e,t){if(ac(t))return eu.resolve(null);let r=t;if(t8(r))return eu.resolve(null);let n=re(r);return this.indexManager.getIndexType(e,n).next(t=>0===t?null:(null!==r.limit&&1===t&&(n=re(r=rn(r,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(t=>{let s=rv(...t);return this.Fo.getDocuments(e,s).next(t=>this.indexManager.getMinOffset(e,n).next(n=>{let i=this.Bo(r,t);return this.Uo(r,i,s,n.readTime)?this.Oo(e,rn(r,null,"F")):this.ko(e,i,r,n)}))})))}Mo(e,t,r,n){return(ac(t)?function(e){for(let t of e.stages){if(t instanceof sC||t instanceof sA)return!1;if(t instanceof sV){if(t.condition instanceof sg&&"exists"===t.condition._expr.name&&t.condition._expr.params[0]instanceof su&&t.condition._expr.params[0].fieldName===q)continue;return!1}}return!0}(t):t8(t))||n.isEqual(es.min())?eu.resolve(null):this.Fo.getDocuments(e,r).next(s=>{let i,a,o=this.Bo(t,s);return this.Uo(t,o,r,n)?eu.resolve(null):(w()<=c.$b.DEBUG&&v("QueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),ah(t)),this.ko(e,o,t,(i=n.toTimestamp().seconds,a=n.toTimestamp().nanoseconds+1,new ea(es.fromTimestamp(1e9===a?new en(i+1,0):new en(i,a)),G.empty(),-1))
6).next(e=>e))})}Bo(e,t){let r,n;return ac(e)?(r=new eg(aK),n=t=>aS(e,t)):(r=new eg(rl(e)),n=t=>ro(e,t)),t.forEach((e,t)=>{n(t)&&(r=r.add(t))}),r}Uo(e,t,r,n){if(ac(e))return e.stages.some(e=>e instanceof sC||e instanceof sA);if(null===e.limit)return!1;if(r.size!==t.size)return!0;let s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||s.version.compareTo(n)>0)}No(e,t,r){return w()<=c.$b.DEBUG&&v("QueryEngine","Using full collection scan to execute query:",ah(t)),this.Fo.getDocumentsMatchingQuery(e,t,ea.min(),r)}ko(e,t,r,n){return this.Fo.getDocumentsMatchingQuery(e,r,n).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let aW="LocalStore";class aY{constructor(e,t,r,n){this.persistence=e,this.qo=t,this.serializer=n,this.$o=new em(M),this.Ko=new rh(e=>af(e),ap),this.Wo=new Map,this.Qo=e.getRemoteDocumentCache(),this.g_=e.getTargetCache(),this.w_=e.getBundleCache(),this.Go(r)}Go(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new aD(this.Qo,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Qo.setIndexManager(this.indexManager),this.qo.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.$o))}}async function aJ(e,t){return await e.persistence.runTransaction("Handle user change","readonly",r=>{let n;return e.mutationQueue.getAllMutationBatches(r).next(s=>(n=s,e.Go(t),e.mutationQueue.getAllMutationBatches(r))).next(t=>{let s=[],i=[],a=rv();for(let e of n)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(r,a).next(e=>({zo:e,removedBatchIds:s,addedBatchIds:i}))})})}function aX(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.g_.getLastRemoteSnapshotVersion(t))}async function aZ(e,t,r){let n=e.$o.get(t);try{r||await e.persistence.runTransaction("Release target",r?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,n))}catch(e){if(!ec(e))throw e;v(aW,`Failed to update sequence numbers for target ${t}: ${e}`)}e.$o=e.$o.remove(t),e.Ko.delete(n.target)}function a0(e,t,r){let n=es.min(),s=rv();return e.persistence.runTransaction("Execute query","readwrite",i=>{var a;let o;return(a=ac(t)?t:re(t),void 0!==(o=e.Ko.get(a))?eu.resolve(e.$o.get(o)):e.g_.getTargetData(i,a)).next(t=>{if(t)return n=t.lastLimboFreeSnapshotVersion,e.g_.getMatchingKeysForTargetId(i,t.targetId).next(e=>{s=e})}).next(()=>e.qo.getDocumentsMatchingQuery(i,t,r?n:es.min(),r?s:rv())).next(t=>{var r;return r=e,t.forEach((e,t)=>{let n=t.key.getCollectionGroup(),s=r.Wo.get(n)||es.min();t.readTime.compareTo(s)>0&&r.Wo.set(n,t.readTime)}),{documents:t,Jo:s}})})}class a1{constructor(){this.activeTargetIds=r_}na(e){this.activeTargetIds=this.activeTargetIds.add(e)}ra(e){this.activeTargetIds=this.activeTargetIds.delete(e)}ta(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class a2{constructor(){this.Ua=new a1,this.ka={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.Ua.na(e),this.ka[e]||"not-current"}updateQueryState(e,t,r){this.ka[e]=t}removeLocalQueryTarget(e){this.Ua.ra(e)}isLocalQueryTarget(e){return this.Ua.activeTargetIds.has(e)}clearQueryState(e){delete this.ka[e]}getAllActiveQueryTargets(){return this.Ua.activeTargetIds}isActiveQueryTarget(e){return this.Ua.activeTargetIds.has(e)}start(){return this.Ua=new a1,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}function a3(){return"u">typeof document?document:null}class a4{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.qa=0,this.$a=null,this.Ka=!0}Wa(){0===this.qa&&(this.Qa("Unknown"),this.$a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.$a=null,this.Ga("Backend didn't respond within 10 seconds."),this.Qa("Offline"),Promise.resolve())))}za(e){"Online"===this.state?this.Qa("Unknown"):(this.qa++,this.qa>=1&&(this.ja(),this.Ga(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Qa("Offline")))}set(e){this.ja(),this.qa=0,"Online"===e&&(this.Ka=!1),this.Qa(e)}Qa(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}Ga(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.Ka?(_(t),this.Ka=!1):v("OnlineStateTracker",t)}ja(){null!==this.$a&&(this.$a.cancel(),this.$a=null)}}let a6="RemoteStore";class a5{constructor(e,t,r,n,s){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.Ha=[],this.Ja=new Map,this.Ya=new Map,this.Za=new Map,this.Xa=new ab(1e3),this.eu=new ab(1001),this.tu=new Set,this.nu=[],this.ru=s,this.ru.bt(e=>{r.enqueueAndForget(async()=>
7{oa(this)&&(v(a6,"Restarting streams for network reachability change."),await async function(e){e.tu.add(4),await a9(e),e.iu.set("Unknown"),e.tu.delete(4),await a8(e)}(this))})}),this.iu=new a4(r,n)}}async function a8(e){if(oa(e))for(let t of e.nu)await t(!0)}async function a9(e){for(let t of e.nu)await t(!1)}function a7(e,t){return e.Ya.get(t)||void 0}function oe(e,t){var r;let n,s,i=a7(e,t.targetId);if(void 0!==i&&e.Ja.has(i))return;let a=(void 0!==(n=a7(e,r=t.targetId))&&e.Za.delete(n),s=r%2!=0?e.eu.next():e.Xa.next(),e.Ya.set(r,s),e.Za.set(s,r),s);v(a6,"remoteStoreListen mapping SDK target ID to remote",t.targetId,a);let o=new av(t.target,a,t.purpose,t.sequenceNumber,t.snapshotVersion,t.lastLimboFreeSnapshotVersion,t.resumeToken);e.Ja.set(a,o),oi(e)?os(e):oT(e).Fn()&&or(e,o)}function ot(e,t){let r=oT(e),n=a7(e,t);v(a6,"remoteStoreUnlisten removing mapping of SDK target ID to remote",t,n),e.Ja.delete(n),e.Ya.delete(t),e.Za.delete(n),r.Fn()&&on(e,n),0===e.Ja.size&&(r.Fn()?r.Nn():oa(e)&&e.iu.set("Unknown"))}function or(e,t){if(e.su.We(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(es.min())>0){let r=e.Za.get(t.targetId);if(void 0===r)return void v(a6,"SDK target ID not found for remote ID: "+t.targetId);let n=e.remoteSyncer.getRemoteKeysForTarget(r).size;t=t.withExpectedCount(n)}oT(e).jn(t)}function on(e,t){e.su.We(t),oT(e).Hn(t)}function os(e){e.su=new rR({getRemoteKeysForTarget:t=>{let r=e.Za.get(t);return void 0!==r?e.remoteSyncer.getRemoteKeysForTarget(r):rv()},dt:t=>e.Ja.get(t)||null,Tt:()=>e.datastore.serializer.databaseId}),oT(e).start(),e.iu.Wa()}function oi(e){return oa(e)&&!oT(e).Cn()&&e.Ja.size>0}function oa(e){return 0===e.tu.size}async function oo(e){e.iu.set("Online")}async function ol(e){e.Ja.forEach((t,r)=>{or(e,t)})}async function ou(e,t){e.su=void 0,oi(e)?(e.iu.za(t),os(e)):e.iu.set("Unknown")}async function oc(e,t,r){if(e.iu.set("Online"),t instanceof rA&&2===t.state&&t.cause)try{await async function(e,t){let r=t.cause;for(let n of t.targetIds){if(e.Ja.has(n)){let t=e.Za.get(n);void 0!==t&&(await e.remoteSyncer.rejectListen(t,r),e.Ya.delete(t),e.Za.delete(n)),e.Ja.delete(n)}e.su.removeTarget(n)}}(e,t)}catch(r){v(a6,"Failed to remove targets %s: %s ",t.targetIds.join(","),r),await oh(e,r)}else if(t instanceof rV?e.su.et(t):t instanceof rC?e.su.ot(t):e.su.rt(t),!r.isEqual(es.min()))try{let t,n,s,i,a=await aX(e.localStore);r.compareTo(a)>
7=0&&await ((t=e.su.Rt(r)).targetChanges.forEach((t,n)=>{if(t.resumeToken.approximateByteSize()>0){let s=e.Ja.get(n);s&&e.Ja.set(n,s.withResumeToken(t.resumeToken,r))}}),t.targetMismatches.forEach((t,r)=>{let n=e.Ja.get(t);if(!n)return;e.Ja.set(t,n.withResumeToken(ex.EMPTY_BYTE_STRING,n.snapshotVersion)),on(e,t);let s=new av(n.target,t,r,n.sequenceNumber);or(e,s)}),n=new Map,t.targetChanges.forEach((t,r)=>{let s=e.Za.get(r);void 0!==s&&n.set(s,t)}),s=new em(M),t.targetMismatches.forEach((t,r)=>{let n=e.Za.get(t);void 0!==n&&(s=s.insert(n,r))}),i=new rS(t.snapshotVersion,n,s,t.documentUpdates,t.augmentedDocumentUpdates,t.resolvedLimboDocuments),e.remoteSyncer.applyRemoteEvent(i))}catch(t){v(a6,"Failed to raise snapshot:",t),await oh(e,t)}}async function oh(e,t,r){if(!ec(t))throw t;e.tu.add(1),await a9(e),e.iu.set("Offline"),r||(r=()=>aX(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{v(a6,"Retrying IndexedDB access"),await r(),e.tu.delete(1),await a8(e)})}function od(e,t){return t().catch(r=>oh(e,r,t))}async function om(e){var t;let r=ox(e),n=e.Ha.length>0?e.Ha[e.Ha.length-1].batchId:-1;for(;oa(t=e)&&t.Ha.length<10;)try{let t=await function(e,t){return e.persistence.runTransaction("Get next mutation batch","readonly",r=>(void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(r,t)))}(e.localStore,n);if(null===t){0===e.Ha.length&&r.Nn();break}n=t.batchId,function(e,t){e.Ha.push(t);let r=ox(e);r.Fn()&&r.Jn&&r.Yn(t.mutations)}(e,t)}catch(t){await oh(e,t)}of(e)&&op(e)}function of(e){return oa(e)&&!ox(e).Cn()&&e.Ha.length>0}function op(e){ox(e).start()}async function og(e){ox(e).er()}async function oy(e){let t=ox(e);for(let r of e.Ha)t.Yn(r.mutations)}async function ow(e,t,r){let n=e.Ha.shift(),s=ay.from(n,t,r);await od(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await om(e)}async function ov(e,t){t&&ox(e).Jn&&await async function(e,t){var r;if(function(e){switch(e){case S.OK:return x(64938);case S.CANCELLED:case S.UNKNOWN:case S.DEADLINE_EXCEEDED:case S.RESOURCE_EXHAUSTED:case S.INTERNAL:case S.UNAVAILABLE:case S.UNAUTHENTICATED:return!1;case S.INVALID_ARGUMENT:case S.NOT_FOUND:case S.ALREADY_EXISTS:case S.PERMISSION_DENIED:case S.FAILED_PRECONDITION:case S.ABORTED:case S.OUT_OF_RANGE:case S.UNIMPLEMENTED:case S.DATA_LOSS:return!0;default:return x(15467,{code:e})}}(r=t.code)&&r!==S.ABORTED){let r=e.Ha.shift();ox(e).Mn(),await od(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await om(e)}}(e,t),of(e)&&op(e)}async function o_(e,t){e.asyncQueue.verifyOperationInProgress(),v(a6,"RemoteStore received new credentials");let r=oa(e);e.tu.add(3),await a9(e),r&&e.iu.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.tu.delete(3),await a8(e)}async function oE(e,t){t?(e.tu.delete(2),await a8(e)):t||(e.tu.add(2),await a9(e),e.iu.set("Unknown"))}function oT(e){var t,r,n;return e._u||(t=e.datastore,r=e.asyncQueue,n={Qt:oo.bind(null,e),zt:ol.bind(null,e),Ht:ou.bind(null,e),zn:oc.bind(null,e)},t.nr(),e._u=new nw(r,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,n),e.nu.push(async t=>{t?(e._u.Mn(),oi(e)?os(e):e.iu.set("Unknown")):(await e._u.stop(),e.su=void 0)})),e._u}function ox(e){var t,r,n;return e.ou||(t=e.datastore,r=e.asyncQueue,n={Qt:()=>Promise.resolve(),zt:og.bind(null,e),Ht:ov.bind(null,e),Zn:oy.bind(null,e),Xn:ow.bind(null,e)},t.nr(),e.ou=new nv(r,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,n),e.nu.push(async t=>{t?(e.ou.Mn(),await om(e)):(await e.ou.stop(),e.Ha.length>0&&(v(a6,`Stopping write stream with ${e.Ha.length} pending writes`),e.Ha=[]))})),e.ou}class ob{constructor(e,t,r,n,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=n,this.removalCallback=s,this.deferred=new V,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,r,n,s){let i=new ob(e,t,Date.now()+r,n,s);return i.start(r),i}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new I(S.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function oN(e,t){if(_("AsyncQueue",`${t}: ${e}`),ec(e))return new I(S.UNAVAILABLE,`${t}: ${e}`);throw e}class oS{static emptySet(e){return new oS(e.comparator)}constructor(e){this.comparator=e?(t,r)=>e(t,r)||G.comparator(t.key,r.key):(e,t)=>G.comparator(e.key,t.key),this.keyedMap=rf(),this.sortedSet=new em(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,r)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof oS)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();for(;t.hasNext();){let e=t.getNext().key,n=r.getNext().key;if(!e.isEqual(n))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 r=new oS;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}}class oI{constructor(){this.au=new em(G.comparator)}track(e){let t=e.doc.key,r=this.au.get(t);r?0!==e.type&&3===r.type?this.au=this.au.insert(t,e):3===e.type&&1!==r.type?this.au=this.au.insert(t,{type:r.type,doc:e.doc}):2===e.type&&2===r.type?this.au=this.au.insert(t,{type:2,doc:e.doc}):2===e.type&&0===r.type?this.au=this.au.insert(t,{type:0,doc:e.doc}):1===e.type&&0===r.type?this.au=this.au.remove(t):1===e.type&&2===r.type?this.au=this.au.insert(t,{type:1,doc:r.doc}):0===e.type&&1===r.type?this.au=this.au.insert(t,{type:2,doc:e.doc}):x(63341,{ft:e,uu:r}):this.au=this.au.insert(t,e)}cu(){let e=[];return this.au.inorderTraversal((t,r)=>{e.push(r)}),e}}class oV{constructor(e,t,r,n,s,i,a,o,l){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=n,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,r,n,s){let i=[];
7return t.forEach(e=>{i.push({type:0,doc:e})}),new oV(e,t,oS.emptySet(t),i,r,n,!0,!1,s)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&am(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,r=e.docChanges;if(t.length!==r.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==r[e].type||!t[e].doc.isEqual(r[e].doc))return!1;return!0}}class oC{constructor(){this.lu=void 0,this.Eu=[]}hu(){return this.Eu.some(e=>e.Tu())}}class oA{constructor(){this.queries=oD(),this.onlineState="Unknown",this.Pu=new Set}terminate(){var e;let t;e=new I(S.ABORTED,"Firestore shutting down"),t=this.queries,this.queries=oD(),t.forEach((t,r)=>{for(let t of r.Eu)t.onError(e)})}}function oD(){return new rh(e=>ad(e),am)}async function ok(e,t){let r=3,n=t.query,s=e.queries.get(n);s?!s.hu()&&t.Tu()&&(r=2):(s=new oC,r=+!t.Tu());try{switch(r){case 0:s.lu=await e.onListen(n,!0);break;case 1:s.lu=await e.onListen(n,!1);break;case 2:await e.onFirstRemoteStoreListen(n)}}catch(r){let e=oN(r,`Initialization of query '${ac(t.query)?au(t.query):ra(t.query)}' failed`);return void t.onError(e)}e.queries.set(n,s),s.Eu.push(t),t.Ru(e.onlineState),s.lu&&t.Iu(s.lu)&&oO(e)}async function oR(e,t){let r=t.query,n=3,s=e.queries.get(r);if(s){let e=s.Eu.indexOf(t);e>=0&&(s.Eu.splice(e,1),0===s.Eu.length?n=+!t.Tu():!s.hu()&&t.Tu()&&(n=2))}switch(n){case 0:return e.queries.delete(r),e.onUnlisten(r,!0);case 1:return e.queries.delete(r),e.onUnlisten(r,!1);case 2:return e.onLastRemoteStoreUnlisten(r);default:return}}function oL(e,t){let r=!1;for(let n of t){let t=n.query,s=e.queries.get(t);if(s){for(let e of s.Eu)e.Iu(n)&&(r=!0);s.lu=n}}r&&oO(e)}function oU(e,t,r){let n=e.queries.get(t);if(n)for(let e of n.Eu)e.onError(r);e.queries.delete(t)}function oO(e){e.Pu.forEach(e=>{e.next()})}(n=a||(a={})).Default="default",n.Cache="cache";class oP{constructor(e,t,r){this.query=e,this.Au=t,this.Vu=!1,this.du=null,this.onlineState="Unknown",this.options=r||{}}Iu(e){if(!this.options.includeMetadataChanges){let t=[];for(let r of e.docChanges)3!==r.type&&t.push(r);e=new oV(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Vu?this.fu(e)&&(this.Au.next(e),t=!0):this.mu(e,this.onlineState)&&(this.pu(e),t=!0),this.du=e,t}onError(e){this.Au.error(e)}Ru(e){this.onlineState=e;let t=!1;return this.du&&!this.Vu&&this.mu(this.du,e)&&(this.pu(this.du),t=!0),t}mu(e,t){return!(e.fromCache&&this.Tu())||(!this.options.waitForSyncWhenOnline||"Offline"===t)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}fu(e){if(e.docChanges.length>0)return!0;let t=this.du&&this.du.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}pu(e){e=oV.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Vu=!0,this.Au.next(e)}Tu(){return this.options.source!==a.Cache}}class oM{constructor(e){this.key=e}}class oF{constructor(e){this.key=e}}class o${constructor(e,t){this.query=e,this.Ou=t,this.Mu=null,this.hasCachedResults=!1,this.current=!1,this.Nu=rv(),this.mutatedKeys=rv(),this.Lu=ac(e)?aI(e):rl(e),this.Bu=new oS(this.Lu)}get Uu(){return this.Ou}ku(e,t){let r=t?t.qu:new oI,n=t?t.Bu:this.Bu,s=t?t.mutatedKeys:this.mutatedKeys,i=n,a=!1,[o,l]=this.$u(this.query,n);e.inorderTraversal((e,t)=>{var u;let c=n.get(e),h=(u=this.query,ac(u)?aS(u,t):ro(u,t))?t:null,d=!!c&&this.mutatedKeys.has(c.key),m=!!h&&(h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations),f=!1;c&&h?c.data.isEqual(h.data)?d!==m&&(r.track({type:3,doc:h}),f=!0):this.Ku(c,h)||(r.track({type:2,doc:h}),f=!0,(o&&this.Lu(h,o)>0||l&&0>this.Lu(h,l))&&(a=!0)):!c&&h?(r.track({type:0,doc:h}),f=!0):c&&!h&&(r.track({type:1,doc:c}),f=!0,(o||l)&&(a=!0)),f&&(h?(i=i.add(h),s=m?s.add(e):s.delete(e)):(i=i.delete(e),s=s.delete(e)))});let u=this.Wu(this.query);if(u)if(ac(this.query)){let e=[];
7i.forEach(t=>e.push(t));let t=aN(this.query,e),n=new oS(aI(this.query));for(let e of t)n=n.add(e);i.forEach(e=>{n.has(e.key)||(s=s.delete(e.key),r.track({type:1,doc:e}))}),i=n}else{let e=this.Qu(this.query);for(;i.size>u;){let t="F"===e?i.last():i.first();i=i.delete(t.key),s=s.delete(t.key),r.track({type:1,doc:t})}}return{Bu:i,qu:r,Uo:a,mutatedKeys:s}}Wu(e){return ac(e)?aV(e)?.limit:e.limit||void 0}Qu(e){if(ac(e)){let t=aV(e);return t&&t.limit<0?"L":"F"}return e.limitType}$u(e,t){if(ac(e)){let r=aV(e)?.limit;return[t.size===r?t.last():null,null]}return["F"===e.limitType&&t.size===this.Wu(this.query)?t.last():null,"L"===e.limitType&&t.size===this.Wu(this.query)?t.first():null]}Ku(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,n){let s=this.Bu;this.Bu=e.Bu,this.mutatedKeys=e.mutatedKeys;let i=e.qu.cu();i.sort((e,t)=>{var r,n;let s;return r=e.type,n=t.type,(s=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return x(20277,{ft:e})}})(r)-s(n)||this.Lu(e.doc,t.doc)}),this.Gu(r),n=n??!1;let a=t&&!n?this.zu():[],o=0===this.Nu.size&&this.current&&!n?1:0,l=o!==this.Mu;return(this.Mu=o,0!==i.length||l)?{snapshot:new oV(this.query,e.Bu,s,i,e.mutatedKeys,0===o,l,!1,!!r&&r.resumeToken.approximateByteSize()>0),ju:a}:{ju:a}}Ru(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Bu:this.Bu,qu:new oI,mutatedKeys:this.mutatedKeys,Uo:!1},!1)):{ju:[]}}Hu(e){return!this.Ou.has(e)&&!!this.Bu.has(e)&&!this.Bu.get(e).hasLocalMutations}Gu(e){e&&(e.addedDocuments.forEach(e=>this.Ou=this.Ou.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ou=this.Ou.delete(e)),this.current=e.current)}zu(){if(!this.current)return[];let e=this.Nu;this.Nu=rv(),this.Bu.forEach(e=>{this.Hu(e.key)&&(this.Nu=this.Nu.add(e.key))});let t=[];return e.forEach(e=>{this.Nu.has(e)||t.push(new oF(e))}),this.Nu.forEach(r=>{e.has(r)||t.push(new oM(r))}),t}Ju(e){this.Ou=e.Jo,this.Nu=rv();let t=this.ku(e.documents);return this.applyChanges(t,!0)}Yu(){return oV.fromInitialDocuments(this.query,this.Bu,this.mutatedKeys,0===this.Mu,this.hasCachedResults)}}let oB="SyncEngine";class oq{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}}class oz{constructor(e){this.key=e,this.Zu=!1}}class oQ{constructor(e,t,r,n,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedClientState=n,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.Xu={},this.ec=new rh(e=>ad(e),am),this.tc=new Map,this.nc=new Set,this.rc=new em(G.comparator),this.sc=new Map,this._c=new aU,this.oc={},this.ac=new Map,this.uc=ab.Cs(),this.onlineState="Unknown",this.cc=void 0}get isPrimaryClient(){return!0===this.cc}}async function oj(e,t,r=!0){let n,s=lr(e),i=s.ec.get(t);return i?(s.sharedClientState.addLocalQueryTarget(i.targetId),n=i.view.Yu()):n=await oG(s,t,r,!0),n}async function oK(e,t){let r=lr(e);await oG(r,t,!0,!1)}async function oG(e,t,r,n){var s,i;let a,o=await (s=e.localStore,i=ac(t)?t:re(t),s.persistence.runTransaction("Allocate target","readwrite",e=>{let t;return s.g_.getTargetData(e,i).next(r=>r?(t=r,eu.resolve(t)):s.g_.allocateTargetId(e).next(r=>(t=new av(i,r,"TargetPurposeListen",e.currentSequenceNumber),s.g_.addTargetData(e,t).next(()=>t))))}).then(e=>{let t=s.$o.get(e.targetId);return(null===t||e.snapshotVersion.compareTo(t.snapshotVersion)>0)&&(s.$o=s.$o.insert(e.targetId,e),s.Ko.set(i,e.targetId)),e})),l=o.targetId,u=e.sharedClientState.addLocalQueryTarget(l,r);return n&&(a=await oH(e,t,l,"current"===u,o.resumeToken)),e.isPrimaryClient&&r&&oe(e.remoteStore,o),a}async function oH(e,t,r,n,s){e.lc=(t,r,n)=>(async function(e,t,r,n){let s=t.view.ku(r);s.Uo&&(s=await a0(e.localStore,t.query,!1).then(({documents:e})=>t.view.ku(e,s)));let i=n&&n.targetChanges.get(t.targetId),a=n&&null!=n.targetMismatches.get(t.targetId),o=t.view.applyChanges(s,e.isPrimaryClient,i,a);return o8(e,t.targetId,o.ju),o.snapshot})(e,t,r,n);let i=await a0(e.localStore,t,!0),a=new o$(t,i.Jo),o=a.ku(i.documents),l=rI.createSynthesizedTargetChangeForCurrentChange(r,n&&"Offline"!==e.onlineState,s),u=a.applyChanges(o,e.isPrimaryClient,l);o8(e,r,u.ju);let c=new oq(t,r,a);return e.ec.set(t,c),e.tc.has(r)?e.tc.get(r).push(t):e.tc.set(r,[t]),u.snapshot}async function oW(e,t,r){let n=e.ec.get(t),s=e.tc.get(n.targetId);s.length>1?(e.tc.set(n.targetId,s.filter(e=>
7!am(e,t))),e.ec.delete(t)):e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(n.targetId),e.sharedClientState.isActiveQueryTarget(n.targetId)||await aZ(e.localStore,n.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(n.targetId),r&&ot(e.remoteStore,n.targetId),o6(e,n.targetId)}).catch(el)):(o6(e,n.targetId),await aZ(e.localStore,n.targetId,!0))}async function oY(e,t){let r=e.ec.get(t),n=e.tc.get(r.targetId);e.isPrimaryClient&&1===n.length&&(e.sharedClientState.removeLocalQueryTarget(r.targetId),ot(e.remoteStore,r.targetId))}async function oJ(e,t,r){var n,s,i;let a=((n=e).remoteStore.remoteSyncer.applySuccessfulWrite=o1.bind(null,n),n.remoteStore.remoteSyncer.rejectFailedWrite=o2.bind(null,n),n);try{let e,n,o,l,u,c=await (s=a.localStore,o=en.now(),l=t.reduce((e,t)=>e.add(t.key),rv()),s.persistence.runTransaction("Locally write mutations","readwrite",r=>{let i=rd,a=rv();return s.Qo.getEntries(r,l).next(e=>{(i=e).forEach((e,t)=>{t.isValidDocument()||(a=a.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(r,i)).next(n=>{e=n;let i=[];for(let r of t){let t=function(e,t){let r=null;for(let n of e.fieldTransforms){let e=t.data.field(n.field),s=to(n.transform,e||null);null!=s&&(null===r&&(r=tr.empty()),r.set(n.field,s))}return r||null}(r,e.get(r.key).overlayedDocument);null!=t&&i.push(new tC(r.key,t,function e(t){let r=[];return e_(t.fields,(t,n)=>{let s=new K([t]);if(e8(n)){let t=e(n.mapValue).fields;if(0===t.length)r.push(s);else for(let e of t)r.push(s.child(e))}else r.push(s)}),new ew(r)}(t.value.mapValue),tT.exists(!0)))}
7return s.mutationQueue.addMutationBatch(r,o,i,t)}).next(t=>{n=t;let i=t.applyToLocalDocumentSet(e,a);return s.documentOverlayCache.saveOverlays(r,t.batchId,i)})}).then(()=>({batchId:n.batchId,changes:rp(e)})));a.sharedClientState.addPendingMutation(c.batchId),i=c.batchId,(u=a.oc[a.currentUser.toKey()])||(u=new em(M)),u=u.insert(i,r),a.oc[a.currentUser.toKey()]=u,await o7(a,c.changes),await om(a.remoteStore)}catch(t){let e=oN(t,"Failed to persist write");r.reject(e)}}async function oX(e,t){try{var r,n;let s,i,a=await (r=e.localStore,s=(n=t).snapshotVersion,i=r.$o,r.persistence.runTransaction("Apply remote event","readwrite-primary",e=>{var t,a,o;let l,u,c=r.Qo.newChangeBuffer({trackRemovals:!0});i=r.$o;let h=[];n.targetChanges.forEach((t,a)=>{var o;let l=i.get(a);if(!l)return;h.push(r.g_.removeMatchingKeys(e,t.removedDocuments,a).next(()=>r.g_.addMatchingKeys(e,t.addedDocuments,a)));let u=l.withSequenceNumber(e.currentSequenceNumber);null!==n.targetMismatches.get(a)?u=u.withResumeToken(ex.EMPTY_BYTE_STRING,es.min()).withLastLimboFreeSnapshotVersion(es.min()):t.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(t.resumeToken,s)),i=i.insert(a,u),o=u,(0===l.resumeToken.approximateByteSize()||o.snapshotVersion.toMicroseconds()-l.snapshotVersion.toMicroseconds()>=3e8||t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size>0)&&h.push(r.g_.updateTargetData(e,u))});let d=rd,m=rv();if(n.documentUpdates.forEach(t=>{n.resolvedLimboDocuments.has(t)&&h.push(r.persistence.referenceDelegate.updateLimboDocument(e,t))}),h.push((t=e,a=c,o=n.documentUpdates,l=rv(),u=rv(),o.forEach(e=>l=l.add(e)),a.getEntries(t,l).next(e=>{let t=rd;return o.forEach((r,n)=>{let s=e.get(r);n.isFoundDocument()!==s.isFoundDocument()&&(u=u.add(r)),n.isNoDocument()&&n.version.isEqual(es.min())?(a.removeEntry(r,n.readTime),t=t.insert(r,n)):!s.isValidDocument()||n.version.compareTo(s.version)>0||0===n.version.compareTo(s.version)&&s.hasPendingWrites?(a.addEntry(n),t=t.insert(r,n)):v(aW,"Ignoring outdated watch update for ",r,". Current version:",s.version," Watch version:",n.version)}),{jo:t,Ho:u}})).next(e=>{d=e.jo,m=e.Ho})),!s.isEqual(es.min())){let t=r.g_.getLastRemoteSnapshotVersion(e).next(t=>r.g_.setTargetsMetadata(e,e.currentSequenceNumber,s));h.push(t)}return eu.waitFor(h).next(()=>c.apply(e)).next(()=>r.localDocuments.getLocalViewOfDocuments(e,d,m)).next(()=>d)}).then(e=>(r.$o=i,e)));
7t.targetChanges.forEach((t,r)=>{let n=e.sc.get(r);n&&(N(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?n.Zu=!0:t.modifiedDocuments.size>0?N(n.Zu,14607):t.removedDocuments.size>0&&(N(n.Zu,42227),n.Zu=!1))}),await o7(e,a,t)}catch(e){await el(e)}}function oZ(e,t,r){if(e.isPrimaryClient&&0===r||!e.isPrimaryClient&&1===r){var n;let r,s=[];e.ec.forEach((e,r)=>{let n=r.view.Ru(t);n.snapshot&&s.push(n.snapshot)}),(n=e.eventManager).onlineState=t,r=!1,n.queries.forEach((e,n)=>{for(let e of n.Eu)e.Ru(t)&&(r=!0)}),r&&oO(n),s.length&&e.Xu.zn(s),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function o0(e,t,r){e.sharedClientState.updateQueryState(t,"rejected",r);let n=e.sc.get(t),s=n&&n.key;if(s){let r=new em(G.comparator);r=r.insert(s,tX.newNoDocument(s,es.min()));let n=rv().add(s),i=new rS(es.min(),new Map,new em(M),r,rd,n);await oX(e,i),e.rc=e.rc.remove(s),e.sc.delete(t),o9(e)}else await aZ(e.localStore,t,!1).then(()=>o6(e,t,r)).catch(el)}async function o1(e,t){let r=t.batch.batchId;try{var n,s;let i=await (n=e.localStore,s=t,n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let t,r,i,a=s.batch.keys(),o=n.Qo.newChangeBuffer({trackRemovals:!0});
7return(r=(t=s.batch).keys(),i=eu.resolve(),r.forEach(r=>{i=i.next(()=>o.getEntry(e,r)).next(e=>{let n=s.docVersions.get(r);N(null!==n,48541),0>e.version.compareTo(n)&&(t.applyToRemoteDocument(e,s),e.isValidDocument()&&(e.setReadTime(s.commitVersion),o.addEntry(e)))})}),i.next(()=>n.mutationQueue.removeMutationBatch(e,t))).next(()=>o.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,a,s.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=rv();for(let r=0;r<e.mutationResults.length;++r)e.mutationResults[r].transformResults.length>0&&(t=t.add(e.batch.mutations[r].key));return t}(s))).next(()=>n.localDocuments.getDocuments(e,a))}));o4(e,r,null),o3(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await o7(e,i)}catch(e){await el(e)}}async function o2(e,t,r){try{var n;let s=await (n=e.localStore,n.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let r;return n.mutationQueue.lookupMutationBatch(e,t).next(t=>(N(null!==t,37113),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t))).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r)).next(()=>n.localDocuments.getDocuments(e,r))}));o4(e,t,r),o3(e,t),e.sharedClientState.updateMutationState(t,"rejected",r),await o7(e,s)}catch(e){await el(e)}}function o3(e,t){(e.ac.get(t)||[]).forEach(e=>{e.resolve()}),e.ac.delete(t)}function o4(e,t,r){let n=e.oc[e.currentUser.toKey()];if(n){let s=n.get(t);s&&(r?s.reject(r):s.resolve(),n=n.remove(t)),e.oc[e.currentUser.toKey()]=n}}function o6(e,t,r=null){for(let n of(e.sharedClientState.removeLocalQueryTarget(t),e.tc.get(t)))e.ec.delete(n),r&&e.Xu.Ec(n,r);e.tc.delete(t),e.isPrimaryClient&&e._c.s_(t).forEach(t=>{e._c.containsKey(t)||o5(e,t)})}function o5(e,t){e.nc.delete(t.path.canonicalString());let r=e.rc.get(t);null!==r&&(ot(e.remoteStore,r),e.rc=e.rc.remove(t),e.sc.delete(r),o9(e))}function o8(e,t,r){for(let n of r)n instanceof oM?(e._c.addReference(n.key,t),function(e,t){let r=t.key,n=r.path.canonicalString();e.rc.get(r)||e.nc.has(n)||(v(oB,"New document in limbo: "+r),e.nc.add(n),o9(e))}(e,n)):n instanceof oF?(v(oB,"Document no longer in limbo: "+n.key),e._c.removeReference(n.key,t),e._c.containsKey(n.key)||o5(e,n.key)):x(19791,{hc:n})}function o9(e){for(;e.nc.size>0&&e.rc.size<e.maxConcurrentLimboResolutions;){let t=e.nc.values().next().value;e.nc.delete(t);let r=new G(Q.fromString(t)),n=e.uc.next();e.sc.set(n,new oz(r)),e.rc=e.rc.insert(r,n),oe(e.remoteStore,new av(re(t5(r.path)),n,"TargetPurposeLimboResolution",eh.ce))}}async function o7(e,t,r){let n=[],s=[],i=[];e.ec.isEmpty()||(e.ec.forEach((a,o)=>{i.push(e.lc(o,t,r).then(t=>{if((t||r)&&e.isPrimaryClient){let n=t?!t.fromCache:r?.targetChanges.get(o.targetId)?.current;e.sharedClientState.updateQueryState(o.targetId,n?"current":"not-current")}if(t){n.push(t);let e=aj.vo(o.targetId,t);s.push(e)}}))}),await Promise.all(i),e.Xu.zn(n),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",r=>eu.forEach(t,t=>eu.forEach(t.wo,n=>e.persistence.referenceDelegate.addReference(r,t.targetId,n)).next(()=>eu.forEach(t.bo,n=>e.persistence.referenceDelegate.removeReference(r,t.targetId,n)))))}catch(e){if(!ec(e))throw e;v(aW,"Failed to update sequence numbers: "+e)}for(let r of t){let t=r.targetId;if(!r.fromCache){let r=e.$o.get(t),n=r.snapshotVersion,s=r.withLastLimboFreeSnapshotVersion(n);e.$o=e.$o.insert(t,s)}}}(e.localStore,s))}async function le(e,t){if(!e.currentUser.isEqual(t)){v(oB,"User change. New user:",t.toKey());let r=await aJ(e.localStore,t);e.currentUser=t,e.ac.forEach(e=>{e.forEach(e=>{e.reject(new I(S.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.ac.clear(),e.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await o7(e,r.zo)}}function lt(e,t){let r=e.sc.get(t);if(r&&r.Zu)return rv().add(r.key);{let r=rv(),n=e.tc.get(t);if(!n)return r;for(let t of n??[]){let n=e.ec.get(t);r=r.unionWith(n.view.Uu)}return r}}function lr(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=oX.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=lt.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=o0.bind(null,e),e.Xu.zn=oL.bind(null,e.eventManager),e.Xu.Ec=oU.bind(null,e.eventManager),e}class ln{constructor(){this.kind="memory",this.synchronizeTabs=!1}
7async initialize(e){this.serializer=r8(e.databaseInfo.databaseId),this.sharedClientState=this.Rc(e),this.persistence=this.Ic(e),await this.persistence.start(),this.localStore=this.Ac(e),this.gcScheduler=this.Vc(e,this.localStore),this.indexBackfillerScheduler=this.dc(e,this.localStore)}Vc(e,t){return null}dc(e,t){return null}Ac(e){var t,r;return t=this.persistence,r=new aH,new aY(t,r,e.initialUser,this.serializer)}Ic(e){return new aB(az.C_,this.serializer)}Rc(e){return new a2}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}ln.provider={build:()=>new ln};class ls extends ln{constructor(e){super(),this.cacheSizeBytes=e}Vc(e,t){return N(this.persistence.referenceDelegate instanceof aQ,46915),new nV(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Ic(e){let t=void 0!==this.cacheSizeBytes?nb.withCacheSize(this.cacheSizeBytes):nb.DEFAULT;return new aB(e=>aQ.C_(e,t),this.serializer)}}class li{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=>oZ(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=le.bind(null,this.syncEngine),await oE(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new oA}createDatastore(e){var t;let r=r8(e.databaseInfo.databaseId),n=new nf(e.databaseInfo);return t=e.authCredentials,new nE(t,e.appCheckCredentials,n,r)}createRemoteStore(e){var t,r;return t=this.localStore,r=this.datastore,new a5(t,r,e.asyncQueue,e=>oZ(this.syncEngine,e,0),ni.C()?new ni:new nn)}createSyncEngine(e,t){var r,n,s,i,a,o;let l;return r=this.localStore,n=this.remoteStore,s=this.eventManager,i=this.sharedClientState,a=e.initialUser,o=e.maxConcurrentLimboResolutions,l=new oQ(r,n,s,i,a,o),t&&(l.cc=!0),l}async terminate(){await async function(e){v(a6,"RemoteStore shutting down."),e.tu.add(5),await a9(e),e.ru.shutdown(),e.iu.set("Unknown")}(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}li.provider={build:()=>new li};class la{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.mc(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.mc(this.observer.error,e):_("Uncaught Error in snapshot listener:",e.toString()))}gc(){this.muted=!0}mc(e,t){setTimeout(()=>{this.muted||e(t)},0)}}let lo="FirestoreClient";class ll{constructor(e,t,r,n,s){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this._databaseInfo=n,this.user=f.UNAUTHENTICATED,this.clientId=P.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=s,this.authCredentials.start(r,async e=>{v(lo,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(r,e=>(v(lo,"Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this._databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new V;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(r){let t=oN(r,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function lu(e,t){e.asyncQueue.verifyOperationInProgress(),v(lo,"Initializing OfflineComponentProvider");let r=e.configuration;await t.initialize(r);let n=r.initialUser;e.setCredentialChangeListener(async e=>{n.isEqual(e)||(await aJ(t.localStore,e),n=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function lc(e,t){e.asyncQueue.verifyOperationInProgress();let r=await lh(e);v(lo,"Initializing OnlineComponentProvider"),await t.initialize(r,e.configuration),e.setCredentialChangeListener(e=>o_(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,r)=>o_(t.remoteStore,r)),e._onlineComponents=t}async function lh(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){v(lo,"Using user provided OfflineComponentProvider");try{await lu(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===S.FAILED_PRECONDITION||t.code===S.UNIMPLEMENT
7ED:!("u">typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code))throw t;E("Error using user provided cache. Falling back to memory cache: "+t),await lu(e,new ln)}}else v(lo,"Using default OfflineComponentProvider"),await lu(e,new ls(void 0));return e._offlineComponents}async function ld(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(v(lo,"Using user provided OnlineComponentProvider"),await lc(e,e._uninitializedComponentsProvider._online)):(v(lo,"Using default OnlineComponentProvider"),await lc(e,new li))),e._onlineComponents}async function lm(e){let t=await ld(e),r=t.eventManager;return r.onListen=oj.bind(null,t.syncEngine),r.onUnlisten=oW.bind(null,t.syncEngine),r.onFirstRemoteStoreListen=oK.bind(null,t.syncEngine),r.onLastRemoteStoreUnlisten=oY.bind(null,t.syncEngine),r}function lf(e,t,r,n){let s=new la(n),i=new oP(t,s,r);return e.asyncQueue.enqueueAndForget(async()=>ok(await lm(e),i)),()=>{s.gc(),e.asyncQueue.enqueueAndForget(async()=>oR(await lm(e),i))}}function lp(e,t,r={}){let n=new V;return e.asyncQueue.enqueueAndForget(async()=>{var s,i;let a,o;return s=await lm(e),i=e.asyncQueue,a=new la({next:e=>{a.gc(),i.enqueueAndForget(()=>oR(s,o));let l=e.docs.has(t);!l&&e.fromCache?n.reject(new I(S.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&e.fromCache&&r&&"server"===r.source?n.reject(new I(S.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):n.resolve(e)},error:e=>n.reject(e)}),ok(s,o=new oP(t5(t.path),a,{includeMetadataChanges:!0,waitForSyncWhenOnline:!0}))}),n.promise}function lg(e,t,r={}){let n=new V;return e.asyncQueue.enqueueAndForget(async()=>{var s,i;let a,o;return s=await lm(e),i=e.asyncQueue,a=new la({next:e=>{a.gc(),i.enqueueAndForget(()=>oR(s,o)),e.fromCache&&"server"===r.source?n.reject(new I(S.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):n.resolve(e)},error:e=>n.reject(e)}),ok(s,o=new oP(t instanceof s$?function(e){let t=function(e){let t=!1,r=[];for(let n of e)if(n instanceof sk)if(t=!0,n.orderings.some(e=>e.expr instanceof su&&e.expr.fieldName===q))r.push(n);else{let e=n.orderings.map(e=>e);e.push(sc(q).ascending()),r.push(new sk(e,{}))}else n instanceof sC&&(t||(r.push(new sk([sc(q).ascending()],{})),t=!0)),r.push(n);return t||r.push(new sk([sc(q).ascending()],{})),r}(e.stages);if(e.userDataReader){let r=e.userDataReader.createContext(3,"toCorePipeline");t.forEach(e=>e._readUserData(r))}return new sU(e.userDataReader.serializer,t,void 0)}(t):t,a,{includeMetadataChanges:!0,waitForSyncWhenOnline:!0}))}),n.promise}function ly(e,t){let r=new V;return e.asyncQueue.enqueueAndForget(async()=>oJ(await ld(e).then(e=>e.syncEngine),t,r)),r.promise}let lw="AsyncQueue";class lv{constructor(e=Promise.resolve()){this.qc=[],this.$c=!1,this.Kc=[],this.Wc=null,this.Qc=!1,this.Gc=!1,this.zc=[],this.xn=new np(this,"async_queue_retry"),this.jc=()=>{let e=a3();e&&v(lw,"Visibility state changed to "+e.visibilityState),this.xn.gn()},this.Hc=e;const t=a3();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.jc)}get isShuttingDown(){return this.$c}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Jc(),this.Yc(e)}enterRestrictedMode(e){if(!this.$c){this.$c=!0,this.Gc=e||!1;let t=a3();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.jc)}}enqueue(e){if(this.Jc(),this.$c)return new Promise(()=>{});let t=new V;return this.Yc(()=>this.$c&&this.Gc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.qc.push(e),this.Zc()))}async Zc(){if(0!==this.qc.length){try{await this.qc[0](),this.qc.shift(),this.xn.reset()}catch(e){if(!ec(e))throw e;v(lw,"Operation failed with retryable error: "+e)}this.qc.length>0&&this.xn.mn(()=>this.Zc())}}Yc(e){let t=this.Hc.then(()=>(this.Qc=!0,e().catch(e=>{throw this.Wc=e,this.Qc=!1,_("INTERNAL UNHANDLED ERROR: ",l_(e)),e}).then(e=>(this.Qc=!1,e))));return this.Hc=t,t}enqueueAfterDelay(e,t,r){this.Jc(),this.zc.indexOf(e)>-1&&(t=0);let n=ob.createAndSchedule(this,e,t,r,e=>this.Xc(e));return this.Kc.push(n),n}Jc(){this.Wc&&x(47125,{el:l_(this.Wc)})}verifyOperationInProgress(){}async tl(){let e;do e=this.Hc,await e;while(e!==this.Hc)}nl(e){for(let t of this.Kc)if(t.timerId===e)return!0;return!1}rl(e){return this.tl().then(()=>{for(let t of(this.Kc.sort((e,t)=>
7e.targetTimeMs-t.targetTimeMs),this.Kc))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.tl()})}il(e){this.zc.push(e)}Xc(e){let t=this.Kc.indexOf(e);this.Kc.splice(t,1)}}function l_(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}class lE extends nk{constructor(e,t,r,n){super(e,t,r,n),this.type="firestore",this._queue=new lv,this._persistenceKey=n?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new lv(e),this._firestoreClient=void 0,await e}}}function lT(e,t){let r="object"==typeof e?e:(0,o.getApp)(),n=(0,o._getProvider)(r,"firestore").getImmediate({identifier:"string"==typeof e?e:t||eO});if(!n._initialized){let e=(0,l.yU)("firestore");e&&function(e,t,r,n={}){e=Z(e,nk);let s=(0,l.zJ)(t),i=e._getSettings(),a={...i,emulatorOptions:e._getEmulatorOptions()},o=`${t}:${r}`;s&&(0,l.gE)(`https://${o}`),i.host!==nA&&i.host!==o&&E("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let u={...i,host:o,ssl:s,emulatorOptions:n};if(!(0,l.bD)(u,a)&&(e._setSettings(u),n.mockUserToken)){let t,r;if("string"==typeof n.mockUserToken)t=n.mockUserToken,r=f.MOCK_USER;else{t=(0,l.Fy)(n.mockUserToken,e._app?.options.projectId);let s=n.mockUserToken.sub||n.mockUserToken.user_id;if(!s)throw new I(S.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");r=new f(s)}e._authCredentials=new D(new C(t,r))}}(n,...e)}return n}function lx(e){if(e._terminated)throw new I(S.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||function(e){var t,r,n,s,i;let a,o=e._freezeSettings(),l=(t=e._databaseId,r=e._app?.options.appId||"",n=e._persistenceKey,s=e._app?.options.apiKey,new eU(t,r,n,o.host,o.ssl,o.experimentalForceLongPolling,o.experimentalAutoDetectLongPolling,nr(o.experimentalLongPollingOptions),o.useFetchStreams,o.isUsingEmulator,s));e._componentsProvider||o.localCache?._offlineComponentProvider&&o.localCache?._onlineComponentProvider&&(e._componentsProvider={_offline:o.localCache._offlineComponentProvider,_online:o.localCache._onlineComponentProvider}),e._firestoreClient=new ll(e._authCredentials,e._appCheckCredentials,e._queue,l,e._componentsProvider&&(i=e._componentsProvider,a=i?._online.build(),{_offline:i?._offline.build(a),_online:a}))}(e),e._firestoreClient}class lb{convertValue(e,t="none"){switch(eG(e)){case 0:return null;case 1:return e.booleanValue;case 2:return eS(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(eI(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw x(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let r={};return e_(e,(e,n)=>{r[e]=this.convertValue(n,t)}),r}convertVectorValue(e){return new nM(e.fields?.[ez].arrayValue?.values?.map(e=>eS(e.doubleValue)))}convertGeoPoint(e){return new nt(eS(e.latitude),eS(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let r=eR(e);return null==r?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(eL(e));default:return null}}convertTimestamp(e){let t=eN(e);return new en(t.seconds,t.nanos)}convertDocumentKey(e,t){let r=Q.fromString(e);N(r3(r),9688,{name:e});let n=new eP(r.get(1),r.get(3)),s=new G(r.popFirst(5));return n.isEqual(t)||_(`Document ${s} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}class lN extends lb{constructor(e){super(),this.firestore=e}convertBytes(e){return new r9(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);
7return new nL(this.firestore,null,t)}}}}]);
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.