1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[226],{8286:(e,t,r)=>{r.d(t,{A:()=>io,C:()=>tI,D:()=>cW,F:()=>tT,N:()=>Q,P:()=>to,Q:()=>ir,R:()=>B,S:()=>cz,W:()=>cB,X:()=>ii,Z:()=>cq,_:()=>nm,a:()=>nw,a1:()=>t5,a2:()=>cU,aR:()=>ia,aX:()=>cY,a_:()=>cQ,ag:()=>t7,ah:()=>eO,ai:()=>ef,aj:()=>t_,ak:()=>t9,al:()=>J,am:()=>E,ap:()=>cX,aq:()=>ns,aw:()=>p,b:()=>ev,b4:()=>iL,c:()=>O,d:()=>cG,e:()=>rt,f:()=>rs,g:()=>iE,h:()=>rn,i:()=>tU,j:()=>rr,k:()=>az,l:()=>ig,m:()=>lO,n:()=>rl,o:()=>I,p:()=>ee,q:()=>ri,r:()=>iy,s:()=>F,t:()=>iN,u:()=>cJ,v:()=>na,w:()=>ix,x:()=>i_,z:()=>Z});var n,i,s,a=r(5488),o=r(2846),l=r(916),u=r(395),c=r(4052),h=r(8816),d=r(5376).Buffer,f=r(5704);let m="12.17.0";function p(e){m=e}let g=new u.Vy("@firebase/firestore");function y(){return g.logLevel}function w(e,...t){if(g.logLevel<=u.$b.DEBUG){let r=t.map(x);g.debug(`Firestore (${m}): ${e}`,...r)}}function v(e,...t){if(g.logLevel<=u.$b.ERROR){let r=t.map(x);g.error(`Firestore (${m}): ${e}`,...r)}}function _(e,...t){if(g.logLevel<=u.$b.WARN){let r=t.map(x);g.warn(`Firestore (${m}): ${e}`,...r)}}function x(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function E(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 (${m}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==r)try{n+=" CONTEXT: "+JSON.stringify(r)}catch(e){n+=" CONTEXT: "+r}throw v(n),Error(n)}function T(e,t,r,n){let i="Unexpected state";"string"==typeof r?i=r:n=r,e||b(t,i,n)}class I{static newId(){let e=62*Math.floor(256/62),t="";for(;t.length<20;){let r=function(e){let t="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(40);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(r);else for(let e=0;e<40;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let n=0;n<r.length;++n)t.length<20&&r[n]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(r[n]%62))}return t}}function S(e,t){return e<t?-1:+(e>t)}function N(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++){let r=e.charAt(n),i=t.charAt(n);if(r!==i)return D(r)===D(i)?S(r,i):D(r)?1:-1}return S(e.length,t.length)}function D(e){let t=e.charCodeAt(0);return t>=55296&&t<=57343}function C(e,t,r){return e.length===t.length&&e.every((e,n)=>r(e,t[n]))}class A{constructor(e,t){this.comparator=e,this.root=t||k.EMPTY}insert(e,t){return new A(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,k.BLACK,null,null))}remove(e){return new A(this.comparator,this.root.remove(e,this.comparator).copy(null,null,k.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 V(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new V(this.root,e,this.comparator,!1)}getReverseIterator(){return new V(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new V(this.root,e,this.comparator,!0)}}class V{constructor(e,t,r,n){this.isReverse=n,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&n&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class k{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:k.RED,this.left=null!=n?n:k.EMPTY,this.right=null!=i?i:k.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,i){return new k(null!=e?e:this.key,null!=t?t:this.value,
1null!=r?r:this.color,null!=n?n:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,r){let n=this,i=r(e,n.key);return(n=i<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===i?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 k.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 k.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,k.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,k.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 E(43730,{key:this.key,value:this.value});if(this.right.isRed())throw E(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw E(27949);return e+ +!this.isRed()}}
1k.EMPTY=null,k.RED=!0,k.BLACK=!1,k.EMPTY=new class{constructor(){this.size=0}get key(){throw E(57766)}get value(){throw E(16141)}get color(){throw E(16727)}get left(){throw E(29726)}get right(){throw E(36894)}copy(e,t,r,n,i){return this}insert(e,t,r){return new k(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 R{constructor(e){this.comparator=e,this.data=new A(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 L(this.data.getIterator())}getIteratorFrom(e){return new L(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 R)||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 R(this.comparator);return t.data=e,t}}class L{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function P(e){return e.hasNext()?e.getNext():void 0}let O={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 F extends o.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}let M="__name__";class U{constructor(e,t,r){void 0===t?t=0:t>e.length&&E(637,{offset:t,range:e.length}),void 0===r?r=e.length-t:r>e.length-t&&E(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===U.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof U?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=U.compareSegments(e.get(n),t.get(n));if(0!==r)return r}return S(e.length,t.length)}static compareSegments(e,t){let r=U.isNumericId(e),n=U.isNumericId(t);return r&&!n?-1:!r&&n?1:r&&n?U.extractNumericId(e).compare(U.extractNumericId(t)):N(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return l.jz.fromString(e.substring(4,e.length-2))}}class B extends U{construct(e,t,r){return new B(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toStringWithLeadingSlash(){return`/${this.canonicalString()}`}
1toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let r of e){if(r.indexOf("//")>=0)throw new F(O.INVALID_ARGUMENT,`Invalid segment (${r}). Paths must not contain // in them.`);t.push(...r.split("/").filter(e=>e.length>0))}return new B(t)}static emptyPath(){return new B([])}}let q=/^[_a-zA-Z][_a-zA-Z0-9]*$/,z=class e extends U{construct(t,r,n){return new e(t,r,n)}static isValidIdentifier(e){return q.test(e)}canonicalString(){return this.toArray().map(t=>(t=t.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===M}static keyField(){return new e([M])}static fromServerFormat(t){let r=[],n="",i=0,s=()=>{if(0===n.length)throw new F(O.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);r.push(n),n=""},a=!1;for(;i<t.length;){let e=t[i];if("\\"===e){if(i+1===t.length)throw new F(O.INVALID_ARGUMENT,"Path has trailing escape character: "+t);let e=t[i+1];if("\\"!==e&&"."!==e&&"`"!==e)throw new F(O.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);n+=e,i+=2}else"`"===e?a=!a:"."!==e||a?n+=e:s(),i++}if(s(),a)throw new F(O.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new e(r)}static emptyPath(){return new e([])}};class ${constructor(e){this.fields=e,e.sort(z.comparator)}static empty(){return new $([])}unionWith(e){let t=new R(z.comparator);for(let e of this.fields)t=t.add(e);for(let r of e)t=t.add(r);return new $(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return C(this.fields,e.fields,(e,t)=>e.isEqual(t))}}function j(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function K(e,t){for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}function G(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class Q{constructor(e){this.path=e}static fromPath(e){return new Q(B.fromString(e))}static fromName(e){return new Q(B.fromString(e).popFirst(5))}static empty(){return new Q(B.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===B.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return B.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new Q(new B(e.slice()))}}function W(e,t,r){if(!r)throw new F(O.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function H(e){if(!Q.isDocumentKey(e))throw new F(O.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Y(e){if(Q.isDocumentKey(e))throw new F(O.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function X(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function J(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":E(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 F(O.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let r=J(e);throw new F(O.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${r}`)}}return e}function ee(e,t){let r={typeString:e};return t&&(r.value=t),r}function et(e,t){let r;if(!X(e))throw new F(O.INVALID_ARGUMENT,"JSON must be an object");for(let n in t)if(t[n]){let i=t[n].typeString,s="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(i&&typeof a!==i){r=`JSON field '${n}' must be a ${i}.`;break}if(void 0!==s&&a!==s.value){r=`Expected '${n}' field to equal '${s.value}'`;break}}if(r)throw new F(O.INVALID_ARGUMENT,r);return!0}class er{static now(){return er.fromMillis(Date.now())}static fromDate(e){return er.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),r=Math.floor((e-1e3*t)*1e6);return new er(t,r)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new F(O.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new F(O.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?S(this.nanoseconds,e.nanoseconds):S(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:er._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(et(e,er._jsonSchema))return new er(e.seconds,e.nanoseconds)}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}
1}er._jsonSchemaVersion="firestore/timestamp/1.0",er._jsonSchema={type:ee("string",er._jsonSchemaVersion),seconds:ee("number"),nanoseconds:ee("number")};class en extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ei{constructor(e){this.binaryString=e}static fromBase64String(e){return new ei(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new en("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new ei(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 S(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ei.EMPTY_BYTE_STRING=new ei("");let es=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ea(e){if(T(!!e,39018),"string"==typeof e){let t=0,r=es.exec(e);if(T(!!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:eo(e.seconds),nanos:eo(e.nanos)}}function eo(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function el(e){return"string"==typeof e?ei.fromBase64String(e):ei.fromUint8Array(e)}let eu="server_timestamp",ec="__type__",eh="__previous_value__",ed="__local_write_time__";function ef(e){return(e?.mapValue?.fields||{})[ec]?.stringValue===eu}function em(e){let t=e.mapValue.fields[eh];return ef(t)?em(t):t}function ep(e){let t=ea(e.mapValue.fields[ed].timestampValue);return new er(t.seconds,t.nanos)}class eg{constructor(e,t,r,n,i,s,a,o,l,u,c,h,d){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=n,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=u,this.apiKey=c,this._customHeaders=h,this.grpcFlowControlWindow=d}}let ey="(default)";class ew{constructor(e,t){this.projectId=e,this.database=t||ey}static empty(){return new ew("","")}get isDefaultDatabase(){return this.database===ey}isEqual(e){return e instanceof ew&&e.projectId===this.projectId&&e.database===this.database}}function ev(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new F(O.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new ew(e.options.projectId,t)}function e_(e){return 0===e&&1/e==-1/0}let ex="__type__",eE="__max__",eb={mapValue:{fields:{__type__:{stringValue:eE}}}},eT="__vector__",eI="value",eS={nullValue:"NULL_VALUE"},eN={booleanValue:!0},eD={booleanValue:!1};function eC(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?ef(e)?4:eQ(e)?0x1fffffffffffff:ej(e)?10:11:E(28295,{value:e})}function eA(e,t,r){if(e===t)return!0;let n=eC(e);if(n!==eC(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return ep(e).isEqual(ep(t));case 3:if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let i=ea(e.timestampValue),s=ea(t.timestampValue);return i.seconds===s.seconds&&i.nanos===s.nanos;case 5:return e.stringValue===t.stringValue;case 6:return el(e.bytesValue).isEqual(el(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return eo(e.geoPointValue.latitude)===eo(t.geoPointValue.latitude)&&eo(e.geoPointValue.longitude)===eo(t.geoPointValue.longitude);case 2:let a,o;if("integerValue"in e&&"integerValue"in t)return eo(e.integerValue)===eo(t.integerValue);if("doubleValue"in e&&"doubleValue"in t)a=eo(e.doubleValue),o=eo(t.doubleValue);else{if(!r?.t)return!1;a=eo(e.integerValue??e.doubleValue),o=eo(t.integerValue??t.doubleValue)}return a===o?!!r?.i||e_(a)===e_(o):!!(void 0===r||r.o)&&isNaN(a)&&isNaN(o);case 9:return C(e.arrayValue.values||[],t.arrayValue.values||[],(e,t)=>eA(e,t,r));case 10:case 11:let l=e.mapValue.fields||{},u=t.mapValue.fields||{};if(j(l)!==j(u))return!1;for(let e in l)if(l.hasOwnProperty(e)&&(void 0===u[e]||!eA(l[e],u[e],r)))return!1;return!0;default:return E(52216,{left:e})}}function eV(e,t){return void 0!==(e.values||[]).find(e=>eA(e,t))}function ek(e,t){if(e===t)return 0;let r=eC(e),n=eC(t);if(r!==n)return S(r,n);switch(r){case 0:case 0x1fffffffffffff:return 0;case 1:return S(e.booleanValue,t.booleanValue);case 2:let i=eo(e.integerValue||e.doubleValue),s=eo(t.integerValue||t.doubleValue);return i<s?-1:i>s?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return eR(e.timestampValue,t.timestampValue);case 4:return eR(ep(e),ep(t));case 5:return N(e.stringValue,t.stringValue);case 6:return function(e,t){let r=el(e),n=el(t);return r.compareTo(n)}(e.bytesValue,t.bytesValue);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=S(r[e],n[e]);if(0!==t)return t}return S(r.length,n.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){let r=S(eo(e.latitude),eo(t.latitude));return 0!==r?r:S(eo(e.longitude),eo(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return eL(e.arrayValue,t.arrayValue);case 10:return function(e,t){let r=e.fields||{},n=t.fields||{},i=r[eI]?.arrayValue,s=n[eI]?.arrayValue,a=S(i?.values?.length||0,s?.values?.length||0);return 0!==a?a:eL(i,s)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===eb.mapValue&&t===eb.mapValue)return 0;if(e===eb.mapValue)return 1;if(t===eb.mapValue)return -1;let r=e.fields||{},n=Object.keys(r),i=t.fields||{},s=Object.keys(i);n.sort(),s.sort();for(let e=0;e<n.length&&e<s.length;++e){let t=N(n[e],s[e]);if(0!==t)return t;let a=ek(r[n[e]],i[s[e]]);if(0!==a)return a}return S(n.length,s.length)}(e.mapValue,t.mapValue);default:throw E(23264,{u:r})}}function eR(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return S(e,t);let r=ea(e),n=ea(t),i=S(r.seconds,n.seconds);return 0!==i?i:S(r.nanos,n.nanos)}function eL(e,t){let r=e.values||[],n=t.values||[];for(let e=0;e<r.length&&e<n.length;++e){let t=ek(r[e],n[e]);if(void 0!==t&&0!==t)return t}return S(r.length,n.length)}function eP(e){var t,r;return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){let t=ea(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?el(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,Q.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+=eP(n);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),r="{",n=!0;for(let i of t)n?n=!1:r+=",",r+=`${i}:${eP(e.fields[i])}`;return r+"}"}(e.mapValue):E(61005,{value:e})}function eO(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function eF(e){return!!e&&"integerValue"in e}function eM(e){return!!e&&"doubleValue"in e}function eU(e){return eF(e)||eM(e)}function eB(e){return!!e&&"arrayValue"in e}function eq(e){return!!e&&"nullValue"in e}function ez(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function e$(e){return!!e&&"mapValue"in e}function ej(e){return(e?.mapValue?.fields||{})[ex]?.stringValue===eT}function eK(e){return(e?.mapValue?.fields||{})[eI]?.arrayValue}function eG(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 K(e.mapValue.fields,(e,r)=>t.mapValue.fields[e]=eG(r)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let r=0;r<(e.arrayValue.values||[]).length;++r)t.arrayValue.values[r]=eG(e.arrayValue.values[r]);return t}return{...e}}function eQ(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===eE}let eW={mapValue:{fields:{[ex]:{stringValue:eT},[eI]:{arrayValue:{}}}}};function eH(e,t){let r=ek(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function eY(e,t){let r=ek(e.value,t.value);return 0!==r?r:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class eX{constructor(e){this.value=e}static empty(){return new eX({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let r=0;r<e.length-1;++r)if(!e$(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()]=eG(t)}setAll(e){let t=z.emptyPath(),r={},n=[];e.forEach((e,i)=>{if(!t.isImmediateParentOf(i)){let e=this.getFieldsMap(t);this.applyChanges(e,r,n),r={},n=[],t=i.popLast()}e?r[i.lastSegment()]=eG(e):n.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,r,n)}delete(e){let t=this.field(e.popLast());e$(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return eA(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)];e$(n)&&n.mapValue.fields||(n={mapValue:{fields:{}}},t.mapValue.fields[e.get(r)]=n),t=n}return t.mapValue.fields}
1applyChanges(e,t,r){for(let n of(K(t,(t,r)=>e[t]=r),r))delete e[n]}clone(){return new eX(eG(this.value))}}function eJ(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:e_(t)?"-0":t}}function eZ(e){return{integerValue:""+e}}function e0(e,t,r){return"number"==typeof t&&Number.isInteger(t)&&!e_(t)&&t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?eZ(t):eJ(e,t)}class e1{constructor(){this._=void 0}}function e2(e,t){return e instanceof e7?eU(t)?t:{integerValue:0}:null}class e4 extends e1{}class e3 extends e1{constructor(e){super(),this.elements=e}}function e6(e,t){let r=ti(t);for(let t of e.elements)r.some(e=>eA(e,t))||r.push(t);return{arrayValue:{values:r}}}class e5 extends e1{constructor(e){super(),this.elements=e}}function e8(e,t){let r=ti(t);for(let t of e.elements)r=r.filter(e=>!eA(e,t));return{arrayValue:{values:r}}}class e9 extends e1{constructor(e,t){super(),this.serializer=e,this.l=t}}class e7 extends e9{}class te extends e9{}class tt extends e9{}function tr(e,t,r){if(!eU(t))return e.l;let n=r(tn(t),tn(e.l));return eF(t)&&eF(e.l)?eZ(n):eJ(e.serializer,n)}function tn(e){return eo(e.integerValue||e.doubleValue)}function ti(e){return eB(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class ts{constructor(e,t){this.field=e,this.transform=t}}class ta{constructor(e,t){this.version=e,this.transformResults=t}}class to{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new to}static exists(e){return new to(void 0,e)}static updateTime(e){return new to(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 tl(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class tu{}function tc(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new tw(e.key,to.none()):new tf(e.key,e.data,to.none());{let r=e.data,n=eX.empty(),i=new R(z.comparator);for(let e of t.fields)if(!i.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),i=i.add(e)}return new tm(e.key,n,new $(i.toArray()),to.none())}}function th(e,t,r,n){return e instanceof tf?function(e,t,r,n){if(!tl(e.precondition,t))return r;let i=e.value.clone(),s=ty(e.fieldTransforms,n,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,r,n):e instanceof tm?function(e,t,r,n){if(!tl(e.precondition,t))return r;let i=ty(e.fieldTransforms,n,t),s=t.data;return(s.setAll(tp(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===r)?null:r.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,r,n):tl(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):r}function td(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)&&C(r,n,(e,t)=>{var r,n;return e.field.isEqual(t.field)&&(r=e.transform,n=t.transform,r instanceof e3&&n instanceof e3||r instanceof e5&&n instanceof e5?C(r.elements,n.elements,eA):r instanceof e7&&n instanceof e7||r instanceof te&&n instanceof te||r instanceof tt&&n instanceof tt?eA(r.l,n.l):r instanceof e4&&n instanceof e4)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class tf extends tu{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 tm extends tu{constructor(e,t,r,n,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=n,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function tp(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 tg(e,t,r){let n=new Map;T(e.length===r.length,32656,{h:r.length,T:e.length});for(let s=0;s<r.length;s++){var i;let a=e[s],o=a.transform,l=t.data.field(a.field);
1n.set(a.field,(i=r[s],o instanceof e3?e6(o,l):o instanceof e5?e8(o,l):i))}return n}function ty(e,t,r){let n=new Map;for(let o of e){var i,s,a;let e=o.transform,l=r.data.field(o.field);n.set(o.field,(i=e,s=l,a=t,i instanceof e4?function(e,t){let r={fields:{[ec]:{stringValue:eu},[ed]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&ef(t)&&(t=em(t)),t&&(r.fields[eh]=t),{mapValue:r}}(a,s):i instanceof e3?e6(i,s):i instanceof e5?e8(i,s):i instanceof e7?function(e,t){let r=e2(e,t),n=tn(r)+tn(e.l);return eF(r)&&eF(e.l)?eZ(n):eJ(e.serializer,n)}(i,s):i instanceof te?tr(i,s,Math.min):i instanceof tt?tr(i,s,Math.max):void 0))}return n}class tw extends tu{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class tv extends tu{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class t_{constructor(e,t){this.position=e,this.inclusive=t}}function tx(e,t,r){let n=0;for(let i=0;i<e.position.length;i++){let s=t[i],a=e.position[i];if(n=s.field.isKeyField()?Q.comparator(Q.fromName(a.referenceValue),r.key):ek(a,r.data.field(s.field)),"desc"===s.dir&&(n*=-1),0!==n)break}return n}function tE(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(!eA(e.position[r],t.position[r]))return!1;return!0}class tb{}class tT extends tb{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 tV(e,t,r):"array-contains"===t?new tP(e,r):"in"===t?new tO(e,r):"not-in"===t?new tF(e,r):"array-contains-any"===t?new tM(e,r):new tT(e,t,r)}static createKeyFieldInFilter(e,t,r){return"in"===t?new tk(e,r):new tR(e,r)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(ek(t,this.value)):null!==t&&eC(this.value)===eC(t)&&this.matchesComparison(ek(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 E(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class tI extends tb{constructor(e,t){super(),this.filters=e,this.op=t,this.P=null}static create(e,t){return new tI(e,t)}matches(e){return tS(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.P||(this.P=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.P}getFilters(){return Object.assign([],this.filters)}}function tS(e){return"and"===e.op}function tN(e){return"or"===e.op}function tD(e){return tC(e)&&tS(e)}function tC(e){for(let t of e.filters)if(t instanceof tI)return!1;return!0}function tA(e,t){let r=e.filters.concat(t);return tI.create(r,e.op)}class tV extends tT{constructor(e,t,r){super(e,t,r),this.key=Q.fromName(r.referenceValue)}matches(e){let t=Q.comparator(e.key,this.key);return this.matchesComparison(t)}}class tk extends tT{constructor(e,t){super(e,"in",t),this.keys=tL("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class tR extends tT{constructor(e,t){super(e,"not-in",t),this.keys=tL("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function tL(e,t){return(t.arrayValue?.values||[]).map(e=>Q.fromName(e.referenceValue))}class tP extends tT{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return eB(t)&&eV(t.arrayValue,this.value)}}class tO extends tT{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&eV(this.value.arrayValue,t)}}class tF extends tT{constructor(e,t){super(e,"not-in",t)}matches(e){if(eV(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!eV(this.value.arrayValue,t)}}class tM extends tT{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!eB(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>eV(this.value.arrayValue,e))}}class tU{constructor(e,t="asc"){this.field=e,this.dir=t}}class tB{static fromTimestamp(e){return new tB(e)}static min(){return new tB(new er(0,0))}static max(){return new tB(new er(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 tq{constructor(e,t,r,n,i,s,a){this.key=e,this.documentType=t,this.version=r,this.readTime=n,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new tq(e,0,tB.min(),tB.min(),tB.min(),eX.empty(),0)}static newFoundDocument(e,t,r,n){return new tq(e,1,t,tB.min(),r,n,0)}static newNoDocument(e,t){return new tq(e,2,t,tB.min(),tB.min(),eX.empty(),0)}static newUnknownDocument(e,t){return new tq(e,3,t,tB.min(),tB.min(),eX.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(tB.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=eX.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=eX.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=tB.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 tq&&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 tq(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}})`}}
1class tz{constructor(e,t,r,n){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=n}}function t$(e){return e.fields.find(e=>2===e.kind)}function tj(e){return e.fields.filter(e=>2!==e.kind)}tz.UNKNOWN_ID=-1;class tK{constructor(e,t){this.fieldPath=e,this.kind=t}}class tG{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new tG(0,tW.min())}}function tQ(e){return new tW(e.readTime,e.key,-1)}class tW{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new tW(tB.min(),Q.empty(),-1)}static max(){return new tW(tB.max(),Q.empty(),-1)}}function tH(e,t){let r=e.readTime.compareTo(t.readTime);return 0!==r||0!==(r=Q.comparator(e.documentKey,t.documentKey))?r:S(e.largestBatchId,t.largestBatchId)}class tY{constructor(e,t=null,r=[],n=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=n,this.limit=i,this.startAt=s,this.endAt=a,this.R=null}}function tX(e,t=null,r=[],n=[],i=null,s=null,a=null){return new tY(e,t,r,n,i,s,a)}function tJ(e){if(null===e.R){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 tT)return t.field.canonicalString()+t.op.toString()+eP(t.value);if(tD(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=>eP(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>eP(e)).join(",")),e.R=t}return e.R}function tZ(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++){var r,n;if(r=e.orderBy[i],n=t.orderBy[i],!(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 tT?r instanceof tT&&t.op===r.op&&t.field.isEqual(r.field)&&eA(t.value,r.value):t instanceof tI?r instanceof tI&&t.op===r.op&&t.filters.length===r.filters.length&&t.filters.reduce((t,n,i)=>t&&e(n,r.filters[i]),!0):void E(19439)}(e.filters[r],t.filters[r]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!tE(e.startAt,t.startAt)&&tE(e.endAt,t.endAt)}function t0(e){return!!e.isCorePipeline}function t1(e){return!!e.path&&Q.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function t2(e,t){return e.filters.filter(e=>e instanceof tT&&e.field.isEqual(t))}function t4(e,t,r){let n=eS,i=!0;for(let r of t2(e,t)){let e=eS,t=!0;switch(r.op){case"<":case"<=":var s;e="nullValue"in(s=r.value)?eS:"booleanValue"in s?{booleanValue:!1}:"integerValue"in s||"doubleValue"in s?{doubleValue:NaN}:"timestampValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in s?{stringValue:""}:"bytesValue"in s?{bytesValue:""}:"referenceValue"in s?eO(ew.empty(),Q.empty()):"geoPointValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in s?{arrayValue:{}}:"mapValue"in s?ej(s)?eW:{mapValue:{}}:E(35942,{value:s});break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=eS}0>eH({value:n,inclusive:i},{value:e,inclusive:t})&&(n=e,i=t)}if(null!==r){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=r.position[s];0>eH({value:n,inclusive:i},{value:e,inclusive:r.inclusive})&&(n=e,i=r.inclusive);break}}return{value:n,inclusive:i}}function t3(e,t,r){let n=eb,i=!0;for(let r of t2(e,t)){let e=eb,t=!0;switch(r.op){case">=":case">":var s;e="nullValue"in(s=r.value)?{booleanValue:!1}:"booleanValue"in s?{doubleValue:NaN}:"integerValue"in s||"doubleValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in s?{stringValue:""}:"stringValue"in s?{bytesValue:""}:"bytesValue"in s?eO(ew.empty(),Q.empty()):"referenceValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in s?{arrayValue:{}}:"arrayValue"in s?eW:"mapValue"in s?ej(s)?{mapValue:{}}:eb:E(61959,{value:s}),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=eb}eY({value:n,inclusive:i},{value:e,inclusive:t})>0&&(n=e,i=t)}if(null!==r){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=r.position[s];eY({value:n,inclusive:i},{value:e,inclusive:r.inclusive})>0&&(n=e,i=r.inclusive);break}}return{value:n,inclusive:i}}class t6{constructor(e,t=null,r=[],n=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=n,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.I=null,this.A=null,this.V=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.I){let t;e.I=[];let r=new Set;for(let t of e.explicitOrderBy)e.I.push(t),r.add(t.field.canonicalString());let n=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";
1(t=new R(z.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.I.push(new tU(t,n))}),r.has(z.keyField().canonicalString())||e.I.push(new tU(z.keyField(),n))}return e.I}function re(e){return e.A||(e.A=function(e,t){if("F"===e.limitType)return tX(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 tU(e.field,t)});let r=e.endAt?new t_(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new t_(e.startAt.position,e.startAt.inclusive):null;return tX(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)}}(e,t7(e))),e.A}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 ri(e,t){return new t6(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}function rs(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 tT?`${t.field.canonicalString()} ${t.op} ${eP(t.value)}`:t instanceof tI?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=>eP(e)).join(",")),t.endAt&&(r+=", endAt: ",r+=t.endAt.inclusive?"a:":"b:",r+=t.endAt.position.map(e=>eP(e)).join(",")),`Target(${r})`}; limitType=${e.limitType})`}function ro(e,t){return t.isFoundDocument()&&function(e,t){let r=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(r):Q.isDocumentKey(e.path)?e.path.isEqual(r):e.path.isImmediateParentOf(r)}(e,t)&&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)&&(!e.startAt||!!function(e,t,r){let n=tx(e,t,r);return e.inclusive?n<=0:n<0}(e.startAt,t7(e),t))&&(!e.endAt||!!function(e,t,r){let n=tx(e,t,r);return e.inclusive?n>=0:n>0}(e.endAt,t7(e),t))}function rl(e){return(t,r)=>{let n=!1;for(let i of t7(e)){let e=function(e,t,r){let n=e.field.isKeyField()?Q.comparator(t.key,r.key):function(e,t,r){let n=t.data.field(e),i=r.data.field(e);return null!==n&&null!==i?ek(n,i):E(42886)}(e.field,t,r);switch(e.dir){case"asc":return n;case"desc":return -1*n;default:return E(19790,{direction:e.dir})}}(i,t,r);if(0!==e)return e;n=n||i.field.isKeyField()}return 0}}class ru{constructor(e,t){this.count=e,this.unchangedNames=t}}function rc(e){if(void 0===e)return v("GRPC error has no .code"),O.UNKNOWN;switch(e){case n.OK:return O.OK;case n.CANCELLED:return O.CANCELLED;case n.UNKNOWN:return O.UNKNOWN;case n.DEADLINE_EXCEEDED:return O.DEADLINE_EXCEEDED;case n.RESOURCE_EXHAUSTED:return O.RESOURCE_EXHAUSTED;case n.INTERNAL:return O.INTERNAL;case n.UNAVAILABLE:return O.UNAVAILABLE;case n.UNAUTHENTICATED:return O.UNAUTHENTICATED;case n.INVALID_ARGUMENT:return O.INVALID_ARGUMENT;case n.NOT_FOUND:return O.NOT_FOUND;case n.ALREADY_EXISTS:return O.ALREADY_EXISTS;case n.PERMISSION_DENIED:return O.PERMISSION_DENIED;case n.FAILED_PRECONDITION:return O.FAILED_PRECONDITION;case n.ABORTED:return O.ABORTED;case n.OUT_OF_RANGE:return O.OUT_OF_RANGE;case n.UNIMPLEMENTED:return O.UNIMPLEMENTED;case n.DATA_LOSS:return O.DATA_LOSS;default:return E(39323,{code:e})}}(i=n||(n={}))[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){K(this.inner,(t,r)=>{for(let[t,n]of r)e(t,n)})}isEmpty(){return G(this.inner)}size(){return this.innerSize}}let rd=new A(Q.comparator),rf=new A(Q.comparator);function rm(...e){let t=rf;for(let r of e)t=t.insert(r.key,r);return t}function rp(e){let t=rf;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 A(Q.comparator),rw=new R(Q.comparator);function rv(...e){let t=rw;for(let r of e)t=t.add(r);return t}let r_=new R(S),rx=new l.jz([0xffffffff,0xffffffff],0);function rE(e){let t=(new TextEncoder).encode(e),r=new l.VV;return r.update(t),new Uint8Array(r.digest())}function rb(e){let t=new DataView(e.buffer),r=t.getUint32(0,!0),n=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new l.jz([r,n],0),new l.jz([i,s],0)]}class rT{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||t>=8)throw new rI(`Invalid padding: ${t}`);if(r<0||e.length>0&&0===this.hashCount)throw new rI(`Invalid hash count: ${r}`);if(0===e.length&&0!==t)throw new rI(`Invalid padding when bitmap length is 0: ${t}`);this.m=8*e.length-t,this.p=l.jz.fromNumber(this.m)}v(e,t,r){let n=e.add(t.multiply(l.jz.fromNumber(r)));return 1===n.compare(rx)&&(n=new l.jz([n.getBits(0),n.getBits(1)],0)),n.modulo(this.p).toNumber()}S(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.m)return!1;let[t,r]=rb(rE(e));for(let e=0;e<this.hashCount;e++){let n=this.v(t,r,e);if(!this.S(n))return!1}return!0}static create(e,t,r){let n=new rT(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.m)return;let[t,r]=rb(rE(e));for(let e=0;e<this.hashCount;e++){let n=this.v(t,r,e);this.D(n)}}D(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class rI extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class rS{constructor(e,t,r,n,i,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=r,this.documentUpdates=n,this.augmentedDocumentUpdates=i,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t,r){let n=new Map;return n.set(e,rN.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new rS(tB.min(),n,new A(S),rd,rd,rv())}}class rN{constructor(e,t,r,n,i){this.resumeToken=e,this.current=t,this.addedDocuments=r,this.modifiedDocuments=n,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,r){return new rN(r,t,rv(),rv(),rv())}}class rD{constructor(e,t,r,n){this.C=e,this.removedTargetIds=t,this.key=r,this.F=n}}class rC{constructor(e,t){this.targetId=e,this.O=t}}class rA{constructor(e,t,r=ei.EMPTY_BYTE_STRING,n=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=n}}class rV{constructor(e){this.targetId=e,this.M=0,this.N=rP(),this.L=ei.EMPTY_BYTE_STRING,this.B=!1,this.U=!0}get current(){return this.B}get resumeToken(){return this.L}get k(){return 0!==this.M}get q(){return this.U}$(e){e.approximateByteSize()>0&&(this.U=!0,this.L=e)}K(){let e=rv(),t=rv(),r=rv();return this.N.forEach((n,i)=>{switch(i){case 0:e=e.add(n);break;case 2:t=t.add(n);break;case 1:r=r.add(n);break;default:E(38017,{changeType:i})}}),new rN(this.L,this.B,e,t,r)}W(){this.U=!1,this.N=rP()}G(e,t){this.U=!0,this.N=this.N.insert(e,t)}j(e){this.U=!0,this.N=this.N.remove(e)}H(){this.M+=1}J(){this.M-=1,T(this.M>=0,3241,{M:this.M,targetId:this.targetId})}Y(){this.U=!0,this.B=!0}}let rk="WatchChangeAggregator";class rR{constructor(e){this.Z=e,this.X=new Map,this.ee=rd,this.te=rL(),this.ne=rd,this.re=rL(),this.ie=new A(S)}se(e){for(let t of e.C)e.F&&e.F.isFoundDocument()?this._e(t,e.F):this.oe(t,e.key,e.F);for(let t of e.removedTargetIds)this.oe(t,e.key,e.F)}ae(e){this.forEachTarget(e,t=>{let r=this.X.get(t);if(r)switch(e.state){case 0:this.ue(t)&&r.$(e.resumeToken);break;case 1:r.J(),r.k||r.W(),r.$(e.resumeToken);break;case 2:r.J(),r.k||this.removeTarget(t);break;case 3:this.ue(t)&&(r.Y(),r.$(e.resumeToken));break;case 4:this.ue(t)&&(this.ce(t),r.$(e.resumeToken));break;default:E(56790,{state:e.state})}else w(rk,`handleTargetChange received targetChange for untracked target ID (${t}) with state (${e.state})`)})}forEachTarget(e,t){e.targetIds.length>
10?e.targetIds.forEach(t):this.X.forEach((e,r)=>{this.ue(r)&&t(r)})}le(e){return t0(e)?"documents"===e.getPipelineSourceType()&&1===e.getPipelineDocuments()?.length:t1(e)}Ee(e){let t=e.targetId,r=e.O.count,n=this.he(t);if(n){let i=n.target;if(this.le(i))if(0===r){let e=new Q(t0(i)?B.fromString(i.getPipelineDocuments()[0]):i.path);this.oe(t,e,tq.newNoDocument(e,tB.min()))}else T(1===r,20013,"Single document existence filter with count: "+r);else{let n=this.Te(t);if(n!==r){let r=this.Pe(e),i=r?this.Re(r,e,n):1;0!==i&&(this.ce(t),this.ie=this.ie.insert(t,2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}Pe(e){let t,r,n=e.O.unchangedNames;if(!n||!n.bits)return null;let{bits:{bitmap:i="",padding:s=0},hashCount:a=0}=n;try{t=el(i).toUint8Array()}catch(e){if(e instanceof en)return _("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 rT(t,s,a)}catch(e){return _(e instanceof rI?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===r.m?null:r}Re(e,t,r){return 2*(t.O.count!==r-this.Ve(e,t.targetId))}Ve(e,t){let r=this.Z.getRemoteKeysForTarget(t),n=0;return r.forEach(r=>{let i=this.Z.Ae(),s=`projects/${i.projectId}/databases/${i.database}/documents/${r.path.canonicalString()}`;e.mightContain(s)||(this.oe(t,r,null),n++)}),n}de(e){let t=new Map;this.X.forEach((r,n)=>{let i=this.he(n);if(i){if(r.current&&this.le(i.target)){let t=new Q(t0(i.target)?B.fromString(i.target.getPipelineDocuments()[0]):i.target.path);this.fe(t).has(n)||this.me(n,t)||this.oe(n,t,tq.newNoDocument(t,e))}r.q&&(t.set(n,r.K()),r.W())}});let r=rv();this.re.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{let t=this.he(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1,!1)}),n&&(r=r.add(e))}),this.ee.forEach((t,r)=>r.setReadTime(e)),this.ne.forEach((t,r)=>r.setReadTime(e));let n=new rS(e,t,this.ie,this.ee,this.ne,r);return this.ee=rd,this.te=rL(),this.ne=rd,this.re=rL(),this.ie=new A(S),n}_e(e,t){let r=this.X.get(e);if(!r||!this.ue(e))return void w(rk,`addDocumentToTarget received document for unknown inactive target (${e})`);let n=2*!!this.me(e,t.key);r.G(t.key,n),t0(this.he(e).target)&&"exact"!==this.he(e).target.getPipelineFlavor()?this.ne=this.ne.insert(t.key,t):this.ee=this.ee.insert(t.key,t),this.te=this.te.insert(t.key,this.fe(t.key).add(e)),this.re=this.re.insert(t.key,this.pe(t.key).add(e))}oe(e,t,r){let n=this.X.get(e);n&&this.ue(e)?(this.me(e,t)?n.G(t,1):n.j(t),this.re=this.re.insert(t,this.pe(t).delete(e)),this.re=this.re.insert(t,this.pe(t).add(e)),r&&(t0(this.he(e).target)&&"exact"!==this.he(e).target.getPipelineFlavor()?this.ne=this.ne.insert(t,r):this.ee=this.ee.insert(t,r))):w(rk,`removeDocumentFromTarget received document for unknown or inactive target (${e})`)}removeTarget(e){this.X.delete(e)}Te(e){let t=this.X.get(e);if(!t)return 0;let r=t.K();return this.Z.getRemoteKeysForTarget(e).size+r.addedDocuments.size-r.removedDocuments.size}H(e){let t=this.X.get(e);t||(w(rk,`recordPendingTargetRequest set up tracking for target ID ${e}`),t=new rV(e),this.X.set(e,t)),t.H()}pe(e){let t=this.re.get(e);return t||(t=new R(S),this.re=this.re.insert(e,t)),t}fe(e){let t=this.te.get(e);return t||(t=new R(S),this.te=this.te.insert(e,t)),t}ue(e){let t=null!==this.he(e);return t||w(rk,"Detected inactive target",e),t}he(e){let t=this.X.get(e);return void 0===t||t.k?null:this.Z.ge(e)}ce(e){this.X.set(e,new rV(e)),this.Z.getRemoteKeysForTarget(e).forEach(t=>{this.oe(e,t,null)})}me(e,t){return this.Z.getRemoteKeysForTarget(e).has(t)}}function rL(){return new A(Q.comparator)}function rP(){return new A(Q.comparator)}let rO={asc:"ASCENDING",desc:"DESCENDING"},rF={"<":"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 rU{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function rB(e,t){return e.useProto3Json||null==t?t:{value:t}}function rq(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 rz(e){let t=ea(e);return new er(t.seconds,t.nanos)}function r$(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function rj(e,t){return rq(e,t.toTimestamp())}function rK(e){return T(!!e,49232),tB.fromTimestamp(rz(e))}function rG(e,t){return rQ(e,t).canonicalString()}function rQ(e,t){let r=new B(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?r:r.child(t)}function rW(e){let t=B.fromString(e);return T(ne(t),10190,{key:t.toString()}),t}function rH(e,t){return rG(e.databaseId,t.path)}function rY(e,t){let r=rW(t);if(r.get(1)!==e.databaseId.projectId)throw new F(O.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 F(O.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+r.get(3)+" vs "+e.databaseId.database);return new Q(r0(r))}function rX(e,t){return rG(e.databaseId,t)}function rJ(e){let t=rW(e);return 4===t.length?B.emptyPath():r0(t)}function rZ(e){return new B(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function r0(e){return T(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function r1(e,t,r){return{name:rH(e,t),fields:r.value.mapValue.fields}}function r2(e,t){var r;let n;if(t instanceof tf)n={update:r1(e,t.key,t.value)};else if(t instanceof tw)n={delete:rH(e,t.key)};else if(t instanceof tm)n={update:r1(e,t.key,t.data),updateMask:function(e){let t=[];
1return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof tv))return E(16599,{we:t.type});n={verify:rH(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let r=t.transform;if(r instanceof e4)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(r instanceof e3)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:r.elements}};if(r instanceof e5)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:r.elements}};if(r instanceof e7)return{fieldPath:t.field.canonicalString(),increment:r.l};if(r instanceof te)return{fieldPath:t.field.canonicalString(),minimum:r.l};if(r instanceof tt)return{fieldPath:t.field.canonicalString(),maximum:r.l};throw E(20930,{transform:t.transform})})(0,e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:rj(e,r.updateTime)}:void 0!==r.exists?{exists:r.exists}:E(27497)),n}function r4(e,t){var r;let n=t.currentDocument?void 0!==(r=t.currentDocument).updateTime?to.updateTime(rK(r.updateTime)):void 0!==r.exists?to.exists(r.exists):to.none():to.none(),i=t.updateTransforms?t.updateTransforms.map(t=>{let r;return r=null,"setToServerValue"in t?(T("REQUEST_TIME"===t.setToServerValue,16630,{proto:t}),r=new e4):"appendMissingElements"in t?r=new e3(t.appendMissingElements.values||[]):"removeAllFromArray"in t?r=new e5(t.removeAllFromArray.values||[]):"increment"in t?r=new e7(e,t.increment):"minimum"in t?r=new te(e,t.minimum):"maximum"in t?r=new tt(e,t.maximum):E(16584,{proto:t}),new ts(z.fromServerFormat(t.fieldPath),r)}):[];if(t.update){t.update.name;let r=rY(e,t.update.name),s=new eX({mapValue:{fields:t.update.fields}});return t.updateMask?new tm(r,s,new $((t.updateMask.fieldPaths||[]).map(e=>z.fromServerFormat(e))),n,i):new tf(r,s,n,i)}return t.delete?new tw(rY(e,t.delete),n):t.verify?new tv(rY(e,t.verify),n):E(1463,{proto:t})}function r3(e,t){return{documents:[rX(e,t.path)]}}function r6(e,t){var r,n;let i,s={structuredQuery:{}},a=t.path;null!==t.collectionGroup?(i=a,s.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=a.popLast(),s.structuredQuery.from=[{collectionId:a.lastSegment()}]),s.parent=rX(e,i);let o=function(e){if(0!==e.length)return function e(t){return t instanceof tT?function(e){if("=="===e.op){if(ez(e.value))return{unaryFilter:{field:r9(e.field),op:"IS_NAN"}};if(eq(e.value))return{unaryFilter:{field:r9(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(ez(e.value))return{unaryFilter:{field:r9(e.field),op:"IS_NOT_NAN"}};if(eq(e.value))return{unaryFilter:{field:r9(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:r9(e.field),op:rF[e.op],value:e.value}}}(t):t instanceof tI?function(t){let r=t.getFilters().map(t=>e(t));return 1===r.length?r[0]:{compositeFilter:{op:rM[t.op],filters:r}}}(t):E(54877,{filter:t})}(tI.create(e,"and"))}(t.filters);o&&(s.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:r9(e.field),direction:rO[e.dir]}))}(t.orderBy);l&&(s.structuredQuery.orderBy=l);let u=rB(e,t.limit);return null!==u&&(s.structuredQuery.limit=u),t.startAt&&(s.structuredQuery.startAt={before:(r=t.startAt).inclusive,values:r.position}),t.endAt&&(s.structuredQuery.endAt={before:!(n=t.endAt).inclusive,values:n.position}),{be:s,parent:i}}function r5(e){var t;let r,n=rJ(e.parent),i=e.structuredQuery,s=i.from?i.from.length:0,a=null;if(s>0){T(1===s,65062);let e=i.from[0];e.allDescendants?a=e.collectionId:n=n.child(e.collectionId)}let o=[];i.where&&(o=function(e){let t=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=r7(e.unaryFilter.field);return tT.create(t,"==",{doubleValue:NaN});case"IS_NULL":let r=r7(e.unaryFilter.field);return tT.create(r,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let n=r7(e.unaryFilter.field);return tT.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=r7(e.unaryFilter.field);return tT.create(i,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return E(61313);default:return E(60726)}}(t):void 0!==t.fieldFilter?tT.create(r7(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 E(58110);default:return E(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?tI.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return E(1026)}}(t.compositeFilter.op)):E(30097,{filter:t})}(e);return t instanceof tI&&tD(t)?t.getFilters():[t]}(i.where));let l=[];i.orderBy&&(l=i.orderBy.map(e=>new tU(r7(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;i.limit&&(u=null==(r="object"==typeof(t=i.limit)?t.value:t)?null:r);let c=null;i.startAt&&(c=function(e){let t=!!e.before;return new t_(e.values||[],t)}(i.startAt));let h=null;return i.endAt&&(h=function(e){let t=!e.before;return new t_(e.values||[],t)}(i.endAt)),new t6(n,a,l,o,u,"F",c,h)}function r8(e,t){return{structuredPipeline:{pipeline:{stages:t.stages.map(t=>t._toProto(e))}}}}function r9(e){return{fieldPath:e.canonicalString()}}function r7(e){return z.fromServerFormat(e.fieldPath)}function ne(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function nt(e){return!!e&&"function"==typeof e._toProto&&"ProtoValue"===e._protoValueType}function nr(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 nn(e){return{stringValue:e}}function ni(e){return new rU(e,!0)}class ns{constructor(e){this._byteString=e}static fromBase64String(e){try{return new ns(ei.fromBase64String(e))}catch(e){throw new F(O.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new ns(ei.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:ns._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(et(e,ns._jsonSchema))return ns.fromBase64String(e.bytes)}}
1ns._jsonSchemaVersion="firestore/bytes/1.0",ns._jsonSchema={type:ee("string",ns._jsonSchemaVersion),bytes:ee("string")};class na{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new F(O.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new z(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class no{constructor(e){this._methodName=e}}class nl{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new F(O.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new F(O.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 S(this._lat,e._lat)||S(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:nl._jsonSchemaVersion}}static fromJSON(e){if(et(e,nl._jsonSchema))return new nl(e.latitude,e.longitude)}}nl._jsonSchemaVersion="firestore/geoPoint/1.0",nl._jsonSchema={type:ee("string",nl._jsonSchemaVersion),latitude:ee("number"),longitude:ee("number")};class nu{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}}nu.UNAUTHENTICATED=new nu(null),nu.GOOGLE_CREDENTIALS=new nu("google-credentials-uid"),nu.FIRST_PARTY=new nu("first-party-uid"),nu.MOCK_USER=new nu("mock-user");class nc{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class nh{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class nd{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(nu.UNAUTHENTICATED))}shutdown(){}}class nf{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 nm{constructor(e){this.Se=e,this.currentUser=nu.UNAUTHENTICATED,this.De=0,this.forceRefresh=!1,this.auth=null}start(e,t){T(void 0===this.xe,42304);let r=this.De,n=e=>this.De!==r?(r=this.De,t(e)):Promise.resolve(),i=new nc;this.xe=()=>{this.De++,this.currentUser=this.Ce(),i.resolve(),i=new nc,e.enqueueRetryable(()=>n(this.currentUser))};let s=()=>{let t=i;e.enqueueRetryable(async()=>{await t.promise,await n(this.currentUser)})},a=e=>{w("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.xe&&(this.auth.addAuthTokenListener(this.xe),s())};this.Se.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.Se.getImmediate({optional:!0});e?a(e):(w("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new nc)}},0),s()}getToken(){let e=this.De,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.De!==e?(w("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(T("string"==typeof t.accessToken,31837,{Fe:t}),new nh(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.xe&&this.auth.removeAuthTokenListener(this.xe),this.xe=void 0}Ce(){let e=this.auth&&this.auth.getUid();return T(null===e||"string"==typeof e,2055,{Oe:e}),new nu(e)}}class np{constructor(e,t,r){this.Me=e,this.Ne=t,this.Le=r,this.type="FirstParty",this.user=nu.FIRST_PARTY,this.Be=new Map}Ue(){return this.Le?this.Le():null}get headers(){this.Be.set("X-Goog-AuthUser",this.Me);let e=this.Ue();return e&&this.Be.set("Authorization",e),this.Ne&&this.Be.set("X-Goog-Iam-Authorization-Token",this.Ne),this.Be}}class ng{constructor(e,t,r){this.Me=e,this.Ne=t,this.Le=r}getToken(){return Promise.resolve(new np(this.Me,this.Ne,this.Le))}start(e,t){e.enqueueRetryable(()=>t(nu.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class ny{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 nw{constructor(e,t){this.ke=t,this.forceRefresh=!1,this.appCheck=null,this.qe=null,this.$e=null,(0,a.xZ)(e)&&e.settings.appCheckToken&&(this.$e=e.settings.appCheckToken)}start(e,t){T(void 0===this.xe,3512);let r=e=>{null!=e.error&&w("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let r=e.token!==this.qe;return this.qe=e.token,w("FirebaseAppCheckTokenProvider",`Received ${r?"new":"existing"} token.`),r?t(e.token):Promise.resolve()};this.xe=t=>{e.enqueueRetryable(()=>r(t))};let n=e=>{w("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.xe&&this.appCheck.addTokenListener(this.xe)};this.ke.onInit(e=>n(e)),setTimeout(()=>{if(!this.appCheck){let e=this.ke.getImmediate({optional:!0});e?n(e):w("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.$e)return Promise.resolve(new ny(this.$e));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(T("string"==typeof e.token,44558,{tokenResult:e}),this.qe=e.token,new ny(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.xe&&this.appCheck.removeTokenListener(this.xe),this.xe=void 0}}function nv(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}class n_{Ke(e){}shutdown(){}}let nx="ConnectivityMonitor";class nE{constructor(){this.We=()=>this.Qe(),this.Ge=()=>this.ze(),this.je=[],this.He()}Ke(e){this.je.push(e)}shutdown(){window.removeEventListener("online",this.We),window.removeEventListener("offline",this.Ge)}He(){window.addEventListener("online",this.We),window.addEventListener("offline",this.Ge)}Qe(){for(let e of(w(nx,"Network connectivity changed: AVAILABLE"),this.je))e(0)}ze(){for(let e of(w(nx,"Network connectivity changed: UNAVAILABLE"),this.je))e(1)}static Je(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let nb=null;function nT(){return null===nb?nb=0x10000000+Math.round(0x80000000*Math.random()):nb++,"0x"+nb.toString(16)}let nI="RestConnection",nS={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
1Query:"runAggregationQuery",ExecutePipeline:"executePipeline"};class nN{get Ye(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),n=encodeURIComponent(this.databaseId.database);this.Ze=t+"://"+e.host,this.Xe=`projects/${r}/databases/${n}`,this.et=this.databaseId.database===ey?`project_id=${r}`:`project_id=${r}&database_id=${n}`}tt(e,t,r,n,i){let s=nT(),a=this.nt(e,t.toUriEncodedString());w(nI,`Sending RPC '${e}' ${s}:`,a,r);let l={"google-cloud-resource-prefix":this.Xe,"x-goog-request-params":this.et};this.rt(l,n,i);let{host:u}=new URL(a),c=(0,o.zJ)(u);return this.it(e,a,l,r,c).then(t=>(w(nI,`Received RPC '${e}' ${s}: `,t),t),t=>{throw _(nI,`RPC '${e}' ${s} failed with error: `,t,"url: ",a,"request:",r),t})}st(e,t,r,n,i,s){return this.tt(e,t,r,n,i)}rt(e,t,r){if(e["X-Goog-Api-Client"]="gl-js/ fire/"+m,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),this.databaseInfo._customHeaders)for(let t of Object.keys(this.databaseInfo._customHeaders))e[t]=this.databaseInfo._customHeaders[t]}nt(e,t){let r=nS[e],n=`${this.Ze}/v1/${t}:${r}`;return this.databaseInfo.apiKey&&(n=`${n}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),n}terminate(){}}class nD{constructor(e){this._t=e._t,this.ot=e.ot}ut(e){this.ct=e}lt(e){this.Et=e}ht(e){this.Tt=e}onMessage(e){this.Pt=e}close(){this.ot()}send(e){this._t(e)}Rt(){this.ct()}It(){this.Et()}At(e){this.Tt(e)}Vt(e){this.Pt(e)}}let nC="WebChannelConnection",nA=(e,t,r)=>{e.listen(t,e=>{try{r(e)}catch(e){setTimeout(()=>{throw e},0)}})};class nV extends nN{constructor(e){super(e),this.dt=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}static ft(){nV.gt||(nA((0,c.Ao)(),c.Jh.STAT_EVENT,e=>{e.stat===c.ro.PROXY?w(nC,"STAT_EVENT: detected buffering proxy"):e.stat===c.ro.NOPROXY&&w(nC,"STAT_EVENT: detected no buffering proxy")}),nV.gt=!0)}it(e,t,r,n,i){let s=nT();return new Promise((i,a)=>{let o=new c.ZS;o.setWithCredentials(!0),o.listenOnce(c.Bx.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case c.O4.NO_ERROR:let t=o.getResponseJson();w(nC,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case c.O4.TIMEOUT:w(nC,`RPC '${e}' ${s} timed out`),a(new F(O.DEADLINE_EXCEEDED,"Request time out"));break;case c.O4.HTTP_ERROR:let r=o.getStatus();if(w(nC,`RPC '${e}' ${s} 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=function(e){let t=e.toLowerCase().replace(/_/g,"-");return Object.values(O).indexOf(t)>=0?t:O.UNKNOWN}(t.status);a(new F(e,t.message))}else a(new F(O.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new F(O.UNAVAILABLE,"Connection failed."));break;default:E(9055,{yt:e,streamId:s,wt:o.getLastErrorCode(),bt:o.getLastError()})}}finally{w(nC,`RPC '${e}' ${s} completed.`)}});let l=JSON.stringify(n);w(nC,`RPC '${e}' ${s} sending request:`,n),o.send(t,"POST",l,r,15)})}vt(e,t,r){let i=nT(),s=[this.Ze,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=this.createWebChannelTransport(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(o.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(o.useFetchStreams=!0),this.rt(o.initMessageHeaders,t,r),o.encodeInitMessageHeaders=!0;let u=s.join("");w(nC,`Creating RPC '${e}' stream ${i}: ${u}`,o);let h=a.createWebChannel(u,o);this.St(h);let d=!1,f=!1,m=new nD({_t:t=>{f?w(nC,`Not sending because RPC '${e}' stream ${i} is closed:`,t):(d||(w(nC,`Opening RPC '${e}' stream ${i} transport.`),h.open(),d=!0),w(nC,`RPC '${e}' stream ${i} sending:`,t),h.send(t))},ot:()=>h.close()});return nA(h,c.iO.EventType.OPEN,()=>{f||(w(nC,`RPC '${e}' stream ${i} transport opened.`),m.Rt())}),nA(h,c.iO.EventType.CLOSE,()=>{f||(f=!0,w(nC,`RPC '${e}' stream ${i} transport closed`),m.At(),this.Dt(h))}
1),nA(h,c.iO.EventType.ERROR,t=>{f||(f=!0,_(nC,`RPC '${e}' stream ${i} transport errored. Name:`,t.name,"Message:",t.message),m.At(new F(O.UNAVAILABLE,"The operation could not be completed")))}),nA(h,c.iO.EventType.MESSAGE,t=>{if(!f){let r=t.data[0];T(!!r,16349);let s=r?.error||r[0]?.error;if(s){w(nC,`RPC '${e}' stream ${i} received error:`,s);let t=s.status,r=function(e){let t=n[e];if(void 0!==t)return rc(t)}(t),a=s.message;"NOT_FOUND"===t&&a.includes("database")&&a.includes("does not exist")&&a.includes(this.databaseId.database)&&_(`Database '${this.databaseId.database}' not found. Please check your project configuration.`),void 0===r&&(r=O.INTERNAL,a="Unknown error status: "+t+" with message "+s.message),f=!0,m.At(new F(r,a)),h.close()}else w(nC,`RPC '${e}' stream ${i} received:`,r),m.Vt(r)}}),nV.ft(),setTimeout(()=>{m.It()},0),m}terminate(){this.dt.forEach(e=>e.close()),this.dt=[]}St(e){this.dt.push(e)}Dt(e){this.dt=this.dt.filter(t=>t===e)}rt(e,t,r){super.rt(e,t,r),this.databaseInfo.apiKey&&(e["x-goog-api-key"]=this.databaseInfo.apiKey)}createWebChannelTransport(){return(0,c.fF)()}}nV.gt=!1;class nk{constructor(e,t,r=1e3,n=1.5,i=6e4){this.xt=e,this.timerId=t,this.Ct=r,this.Ft=n,this.Ot=i,this.Mt=0,this.Nt=null,this.Lt=Date.now(),this.reset()}reset(){this.Mt=0}Bt(){this.Mt=this.Ot}Ut(e){this.cancel();let t=Math.floor(this.Mt+this.kt()),r=Math.max(0,Date.now()-this.Lt),n=Math.max(0,t-r);n>0&&w("ExponentialBackoff",`Backing off for ${n} ms (base delay: ${this.Mt} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.Nt=this.xt.enqueueAfterDelay(this.timerId,n,()=>(this.Lt=Date.now(),e())),this.Mt*=this.Ft,this.Mt<this.Ct&&(this.Mt=this.Ct),this.Mt>this.Ot&&(this.Mt=this.Ot)}qt(){null!==this.Nt&&(this.Nt.skipDelay(),this.Nt=null)}cancel(){null!==this.Nt&&(this.Nt.cancel(),this.Nt=null)}kt(){return(Math.random()-.5)*this.Mt}}let nR="PersistentStream";class nL{constructor(e,t,r,n,i,s,a,o){this.xt=e,this.$t=r,this.Kt=n,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Wt=0,this.Qt=null,this.Gt=null,this.stream=null,this.zt=0,this.jt=new nk(e,t)}Ht(){return 1===this.state||5===this.state||this.Jt()}Jt(){return 2===this.state||3===this.state}start(){this.zt=0,4!==this.state?this.auth():this.Yt()}async stop(){this.Ht()&&await this.close(0)}Zt(){this.state=0,this.jt.reset()}Xt(){this.Jt()&&null===this.Qt&&(this.Qt=this.xt.enqueueAfterDelay(this.$t,6e4,()=>this.en()))}tn(e){this.nn(),this.stream.send(e)}async en(){if(this.Jt())return this.close(0)}nn(){this.Qt&&(this.Qt.cancel(),this.Qt=null)}rn(){this.Gt&&(this.Gt.cancel(),this.Gt=null)}async close(e,t){this.nn(),this.rn(),this.jt.cancel(),this.Wt++,4!==e?this.jt.reset():t&&t.code===O.RESOURCE_EXHAUSTED?(v(t.toString()),v("Using maximum backoff delay to prevent overloading the backend."),this.jt.Bt()):t&&t.code===O.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.sn(),this.stream.close(),this.stream=null),this.state=e,await this.listener.ht(t)}sn(){}auth(){this.state=1;let e=this._n(this.Wt),t=this.Wt;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,r])=>{this.Wt===t&&this.an(e,r)},t=>{e(()=>{let e=new F(O.UNKNOWN,"Fetching auth token failed: "+t.message);return this.un(e)})})}an(e,t){let r=this._n(this.Wt);this.stream=this.cn(e,t),this.stream.ut(()=>{r(()=>this.listener.ut())}),this.stream.lt(()=>{r(()=>(this.state=2,this.Gt=this.xt.enqueueAfterDelay(this.Kt,1e4,()=>(this.Jt()&&(this.state=3),Promise.resolve())),this.listener.lt()))}),this.stream.ht(e=>{r(()=>this.un(e))}),this.stream.onMessage(e=>{r(()=>1==++this.zt?this.En(e):this.onNext(e))})}Yt(){this.state=5,this.jt.Ut(async()=>{this.state=0,this.start()})}un(e){return w(nR,`close with error: ${e}`),this.stream=null,this.close(4,e)}_n(e){return t=>{this.xt.enqueueAndForget(()=>this.Wt===e?t():(w(nR,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class nP extends nL{constructor(e,t,r,n,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,n,s),this.serializer
1=i}cn(e,t){return this.connection.vt("Listen",e,t)}En(e){return this.onNext(e)}onNext(e){this.jt.reset();let t=function(e,t){let r;if("targetChange"in t){var n,i;t.targetChange;let s="NO_CHANGE"===(n=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===n?1:"REMOVE"===n?2:"CURRENT"===n?3:"RESET"===n?4:E(39313,{state:n}),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(T(void 0===i||"string"==typeof i,58123),ei.fromBase64String(i||"")):(T(void 0===i||i instanceof d||i instanceof Uint8Array,16193),ei.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;r=new rA(s,a,o,l&&new F(void 0===l.code?O.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 i=rY(e,n.document.name),s=rK(n.document.updateTime),a=n.document.createTime?rK(n.document.createTime):tB.min(),o=new eX({mapValue:{fields:n.document.fields}}),l=tq.newFoundDocument(i,s,a,o);r=new rD(n.targetIds||[],n.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let n=t.documentDelete;n.document;let i=rY(e,n.document),s=n.readTime?rK(n.readTime):tB.min(),a=tq.newNoDocument(i,s);r=new rD([],n.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let n=t.documentRemove;n.document;let i=rY(e,n.document);r=new rD([],n.removedTargetIds||[],i,null)}else{if(!("filter"in t))return E(11601,{ye:t});{t.filter;let e=t.filter;e.targetId;let{count:n=0,unchangedNames:i}=e,s=new ru(n,i);r=new rC(e.targetId,s)}}return r}(this.serializer,e),r=function(e){if(!("targetChange"in e))return tB.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?tB.min():t.readTime?rK(t.readTime):tB.min()}(e);return this.listener.hn(t,r)}Tn(e){let t={};t.database=rZ(this.serializer),t.addTarget=function(e,t){let r,n=t.target;if((r=t0(n)?{pipelineQuery:r8(e,n)}:t1(n)?{documents:r3(e,n)}:{query:r6(e,n).be}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){r.resumeToken=r$(e,t.resumeToken);let n=rB(e,t.expectedCount);null!==n&&(r.expectedCount=n)}else if(t.snapshotVersion.compareTo(tB.min())>0){r.readTime=rq(e,t.snapshotVersion.toTimestamp());let n=rB(e,t.expectedCount);null!==n&&(r.expectedCount=n)}return r}(this.serializer,e);let r=function(e,t){let r=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 E(28987,{purpose:e})}}(t.purpose);return null==r?null:{"goog-listen-tags":r}}(this.serializer,e);r&&(t.labels=r),this.tn(t)}Pn(e){let t={};t.database=rZ(this.serializer),t.removeTarget=e,this.tn(t)}}class nO extends nL{constructor(e,t,r,n,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,n,s),this.serializer=i}get Rn(){return this.zt>0}start(){this.lastStreamToken=void 0,super.start()}sn(){this.Rn&&this.In([])}cn(e,t){return this.connection.vt("Write",e,t)}En(e){return T(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,T(!e.writeResults||0===e.writeResults.length,55816),this.listener.An()}onNext(e){var t,r;T(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.jt.reset();let n=(t=e.writeResults,r=e.commitTime,t&&t.length>0?(T(void 0!==r,14353),t.map(e=>{let t;return(t=e.updateTime?rK(e.updateTime):rK(r)).isEqual(tB.min())&&(t=rK(r)),new ta(t,e.transformResults||[])})):[]),i=rK(e.commitTime);return this.listener.Vn(i,n)}dn(){let e={};e.database=rZ(this.serializer),this.tn(e)}In(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>r2(this.serializer,e))};this.tn(t)}}class nF{}class nM extends nF{constructor(e,t,r,n){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=n,this.fn=!1}mn(){if(this.fn)throw new F(O.FAILED_PRECONDITION,"The client has already been terminated.")}tt(e,t,r,n){return this.mn(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.tt(e,rQ(t,r),n,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===O.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new F(O.UNKNOWN,e.toString())})}st(e,t,r,n,i){return this.mn(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,a])=>this.connection.st(e,rQ(t,r),n,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===O.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new F(O.UNKNOWN,e.toString())})}terminate(){this.fn=!0,this.connection.terminate()}}let nU=new Map,nB={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};
1class nq{static withCacheSize(e){return new nq(e,nq.DEFAULT_COLLECTION_PERCENTILE,nq.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}nq.DEFAULT_COLLECTION_PERCENTILE=10,nq.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,nq.DEFAULT=new nq(0x2800000,nq.DEFAULT_COLLECTION_PERCENTILE,nq.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),nq.DISABLED=new nq(-1,0,0);class nz{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.pn(e),this.gn=e=>t.writeSequenceNumber(e))}pn(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.gn&&this.gn(e),e}}nz.yn=-1;let n$="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class nj{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function nK(e){if(e.code!==O.FAILED_PRECONDITION||e.message!==n$)throw e;w("LocalStore","Unexpectedly lost primary lease")}class nG{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&&E(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new nG((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 nG?t:nG.resolve(t)}catch(e){return nG.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):nG.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):nG.reject(t)}static resolve(e){return new nG((t,r)=>{t(e)})}static reject(e){return new nG((t,r)=>{r(e)})}static waitFor(e){return new nG((t,r)=>{let n=0,i=0,s=!1;e.forEach(e=>{++n,e.next(()=>{++i,s&&i===n&&t()},e=>r(e))}),s=!0,i===n&&t()})}static or(e){let t=nG.resolve(!1);for(let r of e)t=t.next(e=>e?nG.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 nG((r,n)=>{let i=e.length,s=Array(i),a=0;for(let o=0;o<i;o++){let l=o;t(e[l]).next(e=>{s[l]=e,++a===i&&r(s)},e=>n(e))}})}static doWhile(e,t){return new nG((r,n)=>{let i=()=>{!0===e()?t().next(()=>{i()},n):r()};i()})}}let nQ="SimpleDb";class nW{static open(e,t,r,n){try{return new nW(t,e.transaction(n,r))}catch(e){throw new nJ(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.wn=new nc,this.transaction.oncomplete=()=>{this.wn.resolve()},this.transaction.onabort=()=>{t.error?this.wn.reject(new nJ(e,t.error)):this.wn.resolve()},this.transaction.onerror=t=>{let r=n4(t.target.error);this.wn.reject(new nJ(e,r))}}get bn(){return this.wn.promise}abort(e){e&&this.wn.reject(e),this.aborted||(w(nQ,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}vn(){let e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){return new n0(this.transaction.objectStore(e))}}class nH{static delete(e){return w(nQ,"Removing database:",e),n1((0,o.mS)().indexedDB.deleteDatabase(e)).toPromise()}static Je(){if(!(0,o.zW)())return!1;if(nH.Sn())return!0;let e=(0,o.ZQ)(),t=nH.Dn(e),r=nY(e);return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||0<t&&t<10||0<r&&r<4.5)}static Sn(){return void 0!==f&&"YES"===f.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE}static xn(e,t){return e.store(t)}static Dn(e){let t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i);return Number(t?t[1].split("_").slice(0,2).join("."):"-1")}constructor(e,t,r){this.name=e,this.version=t,this.Cn=r,this.Fn=null,12.2===nH.Dn((0,o.ZQ)())&&v("Firestore persistence suffers from a bug in
1iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async On(e){return this.db||(w(nQ,"Opening database:",this.name),this.db=await new Promise((t,r)=>{let n=indexedDB.open(this.name,this.version);n.onsuccess=e=>{t(e.target.result)},n.onblocked=()=>{r(new nJ(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},n.onerror=t=>{let n=t.target.error;"VersionError"===n.name?r(new F(O.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===n.name?r(new F(O.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+n)):r(new nJ(e,n))},n.onupgradeneeded=e=>{w(nQ,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);let t=e.target.result;this.Cn.Mn(t,n.transaction,e.oldVersion,this.version).next(()=>{w(nQ,"Database upgrade to version "+this.version+" complete")})}})),this.Nn&&(this.db.onversionchange=e=>this.Nn(e)),this.db}Ln(e){this.Nn=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,r,n){let i="readonly"===t,s=0;for(;;){++s;try{this.db=await this.On(e);let t=nW.open(this.db,e,i?"readonly":"readwrite",r),s=n(t).next(e=>(t.vn(),e)).catch(e=>(t.abort(e),nG.reject(e))).toPromise();return s.catch(()=>{}),await t.bn,s}catch(t){let e="FirebaseError"!==t.name&&s<3;if(w(nQ,"Transaction failed with error:",t.message,"Retrying:",e),this.close(),!e)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function nY(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}class nX{constructor(e){this.Bn=e,this.Un=!1,this.kn=null}get isDone(){return this.Un}get qn(){return this.kn}set cursor(e){this.Bn=e}done(){this.Un=!0}$n(e){this.kn=e}delete(){return n1(this.Bn.delete())}}class nJ extends F{constructor(e,t){super(O.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function nZ(e){return"IndexedDbTransactionError"===e.name}class n0{constructor(e){this.store=e}put(e,t){let r;return void 0!==t?(w(nQ,"PUT",this.store.name,e,t),r=this.store.put(t,e)):(w(nQ,"PUT",this.store.name,"<auto-key>",e),r=this.store.put(e)),n1(r)}add(e){return w(nQ,"ADD",this.store.name,e,e),n1(this.store.add(e))}get(e){return n1(this.store.get(e)).next(t=>(void 0===t&&(t=null),w(nQ,"GET",this.store.name,e,t),t))}
1delete(e){return w(nQ,"DELETE",this.store.name,e),n1(this.store.delete(e))}count(){return w(nQ,"COUNT",this.store.name),n1(this.store.count())}Kn(e,t){let r=this.options(e,t),n=r.index?this.store.index(r.index):this.store;if("function"==typeof n.getAll){let e=n.getAll(r.range);return new nG((t,r)=>{e.onerror=e=>{r(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(r),t=[];return this.Wn(e,(e,r)=>{t.push(r)}).next(()=>t)}}Qn(e,t){let r=this.store.getAll(e,null===t?void 0:t);return new nG((e,t)=>{r.onerror=e=>{t(e.target.error)},r.onsuccess=t=>{e(t.target.result)}})}Gn(e,t){w(nQ,"DELETE ALL",this.store.name);let r=this.options(e,t);r.zn=!1;let n=this.cursor(r);return this.Wn(n,(e,t,r)=>r.delete())}jn(e,t){let r;t?r=e:(r={},t=e);let n=this.cursor(r);return this.Wn(n,t)}Hn(e){let t=this.cursor({});return new nG((r,n)=>{t.onerror=e=>{n(n4(e.target.error))},t.onsuccess=t=>{let n=t.target.result;n?e(n.primaryKey,n.value).next(e=>{e?n.continue():r()}):r()}})}Wn(e,t){let r=[];return new nG((n,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{let i=e.target.result;if(!i)return void n();let s=new nX(i),a=t(i.primaryKey,i.value,s);if(a instanceof nG){let e=a.catch(e=>(s.done(),nG.reject(e)));r.push(e)}s.isDone?n():null===s.qn?i.continue():i.continue(s.qn)}}).next(()=>nG.waitFor(r))}options(e,t){let r;return void 0!==e&&("string"==typeof e?r=e:t=e),{index:r,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){let r=this.store.index(e.index);return e.zn?r.openKeyCursor(e.range,t):r.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function n1(e){return new nG((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{r(n4(e.target.error))}})}let n2=!1;function n4(e){let t=nH.Dn((0,o.ZQ)());if(t>=12.2&&t<13){let t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){let e=new F("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return n2||(n2=!0,setTimeout(()=>{throw e},0)),e}}return e}let n3="LruGarbageCollector";function n6([e,t],[r,n]){let i=S(e,r);return 0===i?S(t,n):i}class n5{constructor(e){this.Jn=e,this.buffer=new R(n6),this.Yn=0}Zn(){return++this.Yn}Xn(e){let t=[e,this.Zn()];if(this.buffer.size<this.Jn)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>n6(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class n8{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.er=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.tr(6e4)}stop(){this.er&&(this.er.cancel(),this.er=null)}get started(){return null!==this.er}tr(e){w(n3,`Garbage collection scheduled in ${e}ms`),this.er=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.er=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){nZ(e)?w(n3,"Ignoring IndexedDB error during garbage collection: ",e):await nK(e)}await this.tr(3e5)})}}class n9{constructor(e,t){this.nr=e,this.params=t}calculateTargetCount(e,t){return this.nr.rr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return nG.resolve(nz.yn);let r=new n5(t);return this.nr.forEachTarget(e,e=>r.Xn(e.sequenceNumber)).next(()=>this.nr.ir(e,e=>r.Xn(e))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.nr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.nr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(w("LruGarbageCollector","Garbage collection skipped; disabled"),nG.resolve(nB)):this.getCacheSize(e).next(r=>r<this.params.cacheSizeCollectionThreshold?(w("LruGarbageCollector",`Garbage collection skipped; Cache size ${r} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),nB):this.sr(e,t))}getCacheSize(e){return this.nr.getCacheSize(e)}sr(e,t){let r,n,i,s,a,o,l,c=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(w("LruGarbageCollector",`C
1apping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),n=this.params.maximumSequenceNumbersToCollect):n=t,s=Date.now(),this.nthSequenceNumber(e,n))).next(n=>(r=n,a=Date.now(),this.removeTargets(e,r,t))).next(t=>(i=t,o=Date.now(),this.removeOrphanedDocuments(e,r))).next(e=>(l=Date.now(),y()<=u.$b.DEBUG&&w("LruGarbageCollector",`LRU Garbage Collection 2 Counted targets in ${s-c}ms 3 Determined least recently used ${n} in `+(a-s)+"ms\n"+` Removed ${i} targets in `+(o-a)+"ms\n"+` Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-c}ms`),nG.resolve({didRun:!0,sequenceNumbersCollected:n,targetsRemoved:i,documentsRemoved:e})))}}let n7="firestore.googleapis.com";class ie{constructor(e){if(void 0===e.host){if(void 0!==e.ssl)throw new F(O.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=n7,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,e._customHeaders&&(this._customHeaders={...e._customHeaders}),void 0===e.cacheSizeBytes)this.cacheSizeBytes=0x2800000;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new F(O.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}if(function(e,t,r,n){if(!0===t&&!0===n)throw new F(O.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=nv(e.experimentalLongPollingOptions??{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new F(O.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new F(O.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new F(O.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams,void 0!==e.grpcFlowControlWindow){if("number"!=typeof e.grpcFlowControlWindow||e.grpcFlowControlWindow<=0||e.grpcFlowControlWindow>0x7fffffff||!Number.isInteger(e.grpcFlowControlWindow))throw new F(O.INVALID_ARGUMENT,"grpcFlowControlWindow must be a positive integer and cannot exceed 2147483647");this.grpcFlowControlWindow=e.grpcFlowControlWindow}}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&&this.grpcFlowControlWindow===e.grpcFlowControlWindow&&function(e,t){if(e===t)return!0;if(!e||!t)return!1;let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let n of r)if(e[n]!==t[n])return!1;return!0}(this._customHeaders,e._customHeaders)}}let it=class{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 ie({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new F(O.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 F(O.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 ie(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new nd;switch(e.type){case"firstParty":return new ng(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new F(O.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(){return function(e){let t=nU.get(e);t&&(w("ComponentProvider","Removing Datastore"),nU.delete(e),t.terminate())}(this),Promise.resolve()}};class ir{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new ir(this.firestore,e,this._query)}}class ii{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 is(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new ii(this.firestore,e,this._key)}toJSON(){return{type:ii._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,r){if(et(t,ii._jsonSchema))return new ii(e,r||null,new Q(B.fromString(t.referencePath)))}}ii._jsonSchemaVersion="firestore/documentReference/1.0",ii._jsonSchema={type:ee("string",ii._jsonSchemaVersion),referencePath:ee("string")};class is extends ir{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 ii(this.firestore,null,new Q(e))}withConverter(e){return new is(this.firestore,e,this._path)}}function ia(e,t,...r){if(e=(0,o.Ku)(e),W("collection","path",t),e instanceof it){let n=B.fromString(t,...r);return Y(n),new is(e,null,n)}{if(!(e instanceof ii||e instanceof is))throw new F(O.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=e._path.child(B.fromString(t,...r));return Y(n),new is(e.firestore,null,n)}}function io(e,t,...r){if(e=(0,o.Ku)(e),1==arguments.length&&(t=I.newId()),W("doc","path",t),e instanceof it){let n=B.fromString(t,...r);return H(n),new ii(e,null,new Q(n))}{if(!(e instanceof ii||e instanceof is))throw new F(O.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=e._path.child(B.fromString(t,...r));return H(n),new ii(e.firestore,e instanceof is?e.converter:null,new Q(n))}}class il{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:il._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(et(e,il._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(e=>"number"==typeof e))return new il(e.vectorValues);throw new F(O.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}il._jsonSchemaVersion="firestore/vectorValue/1.0",il._jsonSchema={type:ee("string",il._jsonSchemaVersion),vectorValues:ee("object")};let iu=/^__.*__$/;class ic{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return null!==this.fieldMask?new tm(e,this.data,this.fieldMask,t,this.fieldTransforms):new tf(e,this.data,t,this.fieldTransforms)}}class ih{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new tm(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function id(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw E(40011,{dataSource:e})}}class im{constructor(e,t,r,n,i,s){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=n,void 0===i&&this.validatePath(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(e){return new im({...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 iA(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(id(this.dataSource)&&iu.test(e))throw this.createError('Document fields cannot begin and end with "__"')}}class ip{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer
3=r||ni(e)}createContext(e,t,r,n=!1){return new im({dataSource:e,methodName:t,targetDoc:r,path:z.emptyPath(),arrayElement:!1,hasConverter:n},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ig(e){let t=e._freezeSettings(),r=ni(e._databaseId);return new ip(e._databaseId,!!t.ignoreUndefinedProperties,r)}function iy(e,t,r,n,i,s={}){let a,o,l=e.createContext(s.merge||s.mergeFields?2:0,t,r,i);iS("Data must be an object, but it was:",l,n);let u=iT(n,l);if(s.merge)a=new $(l.fieldMask),o=l.fieldTransforms;else if(s.mergeFields){let e=[];for(let n of s.mergeFields){let i=iN(t,n,r);if(!l.contains(i))throw new F(O.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);iV(e,i)||e.push(i)}a=new $(e),o=l.fieldTransforms.filter(e=>a.covers(e.field))}else a=null,o=l.fieldTransforms;return new ic(new eX(u),a,o)}class iw extends no{_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 iw}}class iv extends no{_toFieldTransform(e){return new ts(e.path,new e4)}isEqual(e){return e instanceof iv}}function i_(e,t,r,n){let i=e.createContext(1,t,r);iS("Data must be an object, but it was:",i,n);let s=[],a=eX.empty();return K(n,(e,n)=>{let l=iC(t,e,r);n=(0,o.Ku)(n);let u=i.childContextForFieldPath(l);if(n instanceof iw)s.push(l);else{let e=ib(n,u);null!=e&&(s.push(l),a.set(l,e))}}),new ih(a,new $(s),i.fieldTransforms)}function ix(e,t,r,n,i,s){let a=e.createContext(1,t,r),l=[iN(t,n,r)],u=[i];if(s.length%2!=0)throw new F(O.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<s.length;e+=2)l.push(iN(t,s[e])),u.push(s[e+1]);let c=[],h=eX.empty();for(let e=l.length-1;e>=0;--e)if(!iV(c,l[e])){let t=l[e],r=u[e];r=(0,o.Ku)(r);let n=a.childContextForFieldPath(t);if(r instanceof iw)c.push(t);else{let e=ib(r,n);null!=e&&(c.push(t),h.set(t,e))}}return new ih(h,new $(c),a.fieldTransforms)}function iE(e,t,r,n=!1){return ib(r,e.createContext(n?4:3,t))}function ib(e,t,r){if(iI(e=(0,o.Ku)(e)))return iS("Unsupported field value:",t,e),iT(e,t);if(e instanceof no)return function(e,t){if(!id(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 i of e){let e=ib(i,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,o.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return e0(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let r=er.fromDate(e);return{timestampValue:rq(t.serializer,r)}}if(e instanceof er){let r=new er(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:rq(t.serializer,r)}}if(e instanceof nl)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof ns)return{bytesValue:r$(t.serializer,e._byteString)};if(e instanceof ii){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:rG(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof il){var n;return{mapValue:{fields:{[ex]:{stringValue:eT},[eI]:{arrayValue:{values:((n=e)instanceof il?n.toArray():n).map(e=>{if("number"!=typeof e)throw t.createError("VectorValues must only contain numeric values.");return eJ(t.serializer,e)})}}}}}}if(nt(e))return e._toProto(t.serializer);throw t.createError(`Unsupported field value: ${J(e)}`)}(e,t)}function iT(e,t){let r={};return G(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):K(e,(e,n)=>{let i=ib(n,t.childContextForField(e));null!=i&&(r[e]=i)}),{mapValue:{fields:r}}}function iI(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof er||e instanceof nl||e instanceof ns||e instanceof ii||e instanceof no||e instanceof il||nt(e))}function iS(e,t,r){if(!iI(r)||!X(r)){let n=J(r);throw"an object"===n?t.createError(e+" a custom object"):t.createError(e+" "+n)}}function iN(e,t,r){if((t=(0,o.Ku)(t))instanceof na)return t._internalPath;if("string"==typeof t)return iC(e,t);throw iA("Field path arguments must be of type string or ",e,!1,void 0,r)}let iD=RegExp("[~\\*/\\[\\]]");function iC(e,t,r){if(t.search(iD)>=0)throw iA(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,r);try{return new na(...t.split("."))._internalPath}catch(n){throw iA(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,r)}}function iA(e,t,r,n,i){let s=n&&!n.isEmpty(),a=void 0!==i,o=`Function ${t}
3() called with invalid data`;r&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=` in field ${n}`),a&&(l+=` in document ${i}`),l+=")"),new F(O.INVALID_ARGUMENT,o+e+l)}function iV(e,t){return e.some(e=>e.isEqual(t))}function ik(e){return"function"==typeof e._readUserData}class iR{constructor(e){this.optionDefinitions=e}_getKnownOptions(e,t){let r=eX.empty();for(let n in this.optionDefinitions)if(this.optionDefinitions.hasOwnProperty(n)){let i=this.optionDefinitions[n];if(n in e){let s,a=e[n];i.nestedOptions&&X(a)?s={mapValue:{fields:new iR(i.nestedOptions).getOptionsProto(t,a)}}:a&&(s=ib(a,t)??void 0),s&&r.set(z.fromServerFormat(i.serverName),s)}}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)=>[z.fromServerFormat(r),void 0!==t?ib(t,e):null]));n.setAll(t)}return n.value.mapValue.fields??{}}}function iL(){return new iv("serverTimestamp")}function iP(e){return e instanceof iM?e:X(e)?function(e,t){let r=[];for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];r.push(iG(t)),r.push(iP(n))}return new iW("map",r,"map")}(e):e instanceof Array?function(e){return new iW("array",e.map(e=>iP(e)),"array")}(e):iQ(e,void 0)}function iO(e){if(e instanceof iM)return e;if(e instanceof il)return iG(e);if(Array.isArray(e))return iG(new il(e));throw Error("Unsupported value: "+typeof e)}function iF(e){return"string"==typeof e?ij(e):iP(e)}class iM{constructor(){this._protoValueType="ProtoValue"}add(e){return new iW("add",[this,iP(e)],"add")}asBoolean(){if(this instanceof iH)return this;if(this instanceof iK)return new iX(this);if(this instanceof i$)return new iJ(this);if(this instanceof iW)return new iY(this);throw new F("invalid-argument",`Conversion of type ${typeof this} to BooleanExpression not supported.`)}subtract(e){return new iW("subtract",[this,iP(e)],"subtract")}multiply(e){return new iW("multiply",[this,iP(e)],"multiply")}divide(e){return new iW("divide",[this,iP(e)],"divide")}mod(e){return new iW("mod",[this,iP(e)],"mod")}equal(e){return new iW("equal",[this,iP(e)],"equal").asBoolean()}notEqual(e){return new iW("not_equal",[this,iP(e)],"notEqual").asBoolean()}lessThan(e){return new iW("less_than",[this,iP(e)],"lessThan").asBoolean()}lessThanOrEqual(e){return new iW("less_than_or_equal",[this,iP(e)],"lessThanOrEqual").asBoolean()}greaterThan(e){return new iW("greater_than",[this,iP(e)],"greaterThan").asBoolean()}greaterThanOrEqual(e){return new iW("greater_than_or_equal",[this,iP(e)],"greaterThanOrEqual").asBoolean()}arrayConcat(e,...t){return new iW("array_concat",[this,...[e,...t].map(e=>iP(e))],"arrayConcat")}arrayContains(e){return new iW("array_contains",[this,iP(e)],"arrayContains").asBoolean()}arrayContainsAll(e){return new iW("array_contains_all",[this,Array.isArray(e)?new iz(e.map(iP),"arrayContainsAll"):e],"arrayContainsAll").asBoolean()}arrayContainsAny(e){return new iW("array_contains_any",[this,Array.isArray(e)?new iz(e.map(iP),"arrayContainsAny"):e],"arrayContainsAny").asBoolean()}arrayReverse(){return new iW("array_reverse",[this])}arrayLength(){return new iW("array_length",[this],"arrayLength")}equalAny(e){return new iW("equal_any",[this,Array.isArray(e)?new iz(e.map(iP),"equalAny"):e],"equalAny").asBoolean()}notEqualAny(e){return new iW("not_equal_any",[this,Array.isArray(e)?new iz(e.map(iP),"notEqualAny"):e],"notEqualAny").asBoolean()}exists(){return new iW("exists",[this],"exists").asBoolean()}charLength(){return new iW("char_length",[this],"charLength")}like(e){return new iW("like",[this,iP(e)],"like").asBoolean()}regexContains(e){return new iW("regex_contains",[this,iP(e)],"regexContains").asBoolean()}regexFind(e){return new iW("regex_find",[this,iP(e)],"regexFind")}regexFindAll(e){return new iW("regex_find_all",[this,iP(e)],"regexFindAll")}regexMatch(e){return new iW("regex_match",[this,iP(e)],"regexMatch").asBoolean()}stringContains(e){return new iW("string_contains",[this,iP(e)],"stringContains").asBoolean()}startsWith(e){return new iW("starts_with",[this,iP(e)],"startsWith").asBoolean()}endsWith(e){return new iW("ends_with",[this,iP(e)],"endsWith").asBoolean()}toLower(){return new iW("to_lower",[this],"toLower")}toUpper(){return new iW("to_upper",[this],"toUpper")}trim(e){let t=[this];return e&&t.push(iP(e)),new iW("trim",t,"trim")}ltrim(e){let t=[this];return e&&t.push(iP(e)),new iW("ltrim",t,"ltrim")}rtrim(e){let t=[this];return e&&t.push(iP(e)),new iW("rtrim",t,"rtrim")}type(){return new iW("type",[this])}
3isType(e){return new iW("is_type",[this,iG(e)],"isType").asBoolean()}stringConcat(e,...t){return new iW("string_concat",[this,...[e,...t].map(iP)],"stringConcat")}stringIndexOf(e){return new iW("string_index_of",[this,iP(e)],"stringIndexOf")}stringRepeat(e){return new iW("string_repeat",[this,iP(e)],"stringRepeat")}stringReplaceAll(e,t){return new iW("string_replace_all",[this,iP(e),iP(t)],"stringReplaceAll")}stringReplaceOne(e,t){return new iW("string_replace_one",[this,iP(e),iP(t)],"stringReplaceOne")}concat(e,...t){return new iW("concat",[this,...[e,...t].map(iP)],"concat")}reverse(){return new iW("reverse",[this],"reverse")}arrayFilter(e,t){return new iW("array_filter",[this,iP(e),t],"arrayFilter")}arrayTransform(e,t){return new iW("array_transform",[this,iP(e),t],"arrayTransform")}arrayTransformWithIndex(e,t,r){return new iW("array_transform",[this,iP(e),iP(t),r],"arrayTransformWithIndex")}arraySlice(e,t){let r=[this,iP(e)];return void 0!==t&&r.push(iP(t)),new iW("array_slice",r,"arraySlice")}arrayFirst(){return new iW("array_first",[this],"arrayFirst")}arrayFirstN(e){return new iW("array_first_n",[this,iP(e)],"arrayFirstN")}arrayLast(){return new iW("array_last",[this],"arrayLast")}arrayLastN(e){return new iW("array_last_n",[this,iP(e)],"arrayLastN")}arrayMaximum(){return new iW("maximum",[this],"arrayMaximum")}arrayMaximumN(e){return new iW("maximum_n",[this,iP(e)],"arrayMaximumN")}arrayMinimum(){return new iW("minimum",[this],"arrayMinimum")}arrayMinimumN(e){return new iW("minimum_n",[this,iP(e)],"arrayMinimumN")}arrayIndexOf(e){return new iW("array_index_of",[this,iP(e),iP("first")],"arrayIndexOf")}arrayLastIndexOf(e){return new iW("array_index_of",[this,iP(e),iP("last")],"arrayLastIndexOf")}arrayIndexOfAll(e){return new iW("array_index_of_all",[this,iP(e)],"arrayIndexOfAll")}byteLength(){return new iW("byte_length",[this],"byteLength")}ceil(){return new iW("ceil",[this])}floor(){return new iW("floor",[this])}abs(){return new iW("abs",[this])}exp(){return new iW("exp",[this])}
3mapGet(e){return new iW("map_get",[this,iG(e)],"mapGet")}mapSet(e,t,...r){return new iW("map_set",[this,iP(e),iP(t),...r.map(iP)],"mapSet")}mapKeys(){return new iW("map_keys",[this],"mapKeys")}mapValues(){return new iW("map_values",[this],"mapValues")}mapEntries(){return new iW("map_entries",[this],"mapEntries")}getField(e){return new iW("get_field",[this,iP(e)],"get_field")}count(){return iU._create("count",[this],"count")}sum(){return iU._create("sum",[this],"sum")}average(){return iU._create("average",[this],"average")}minimum(){return iU._create("minimum",[this],"minimum")}maximum(){return iU._create("maximum",[this],"maximum")}first(){return iU._create("first",[this],"first")}last(){return iU._create("last",[this],"last")}arrayAgg(){return iU._create("array_agg",[this],"arrayAgg")}arrayAggDistinct(){return iU._create("array_agg_distinct",[this],"arrayAggDistinct")}countDistinct(){return iU._create("count_distinct",[this],"countDistinct")}logicalMaximum(e,...t){return new iW("maximum",[this,...[e,...t].map(iP)],"logicalMaximum")}logicalMinimum(e,...t){return new iW("minimum",[this,...[e,...t].map(iP)],"minimum")}vectorLength(){return new iW("vector_length",[this],"vectorLength")}cosineDistance(e){return new iW("cosine_distance",[this,iO(e)],"cosineDistance")}dotProduct(e){return new iW("dot_product",[this,iO(e)],"dotProduct")}euclideanDistance(e){return new iW("euclidean_distance",[this,iO(e)],"euclideanDistance")}unixMicrosToTimestamp(){return new iW("unix_micros_to_timestamp",[this],"unixMicrosToTimestamp")}timestampToUnixMicros(){return new iW("timestamp_to_unix_micros",[this],"timestampToUnixMicros")}unixMillisToTimestamp(){return new iW("unix_millis_to_timestamp",[this],"unixMillisToTimestamp")}timestampToUnixMillis(){return new iW("timestamp_to_unix_millis",[this],"timestampToUnixMillis")}unixSecondsToTimestamp(){return new iW("unix_seconds_to_timestamp",[this],"unixSecondsToTimestamp")}timestampToUnixSeconds(){return new iW("timestamp_to_unix_seconds",[this],"timestampToUnixSeconds")}timestampAdd(e,t){return new iW("timestamp_add",[this,iP(e),iP(t)],"timestampAdd")}timestampSubtract(e,t){return new iW("timestamp_subtract",[this,iP(e),iP(t)],"timestampSubtract")}timestampDiff(e,t){return new iW("timestamp_diff",[this,iF(e),iP(t)],"timestampDiff")}timestampExtract(e,t){let r=[this,iP(e)];return t&&r.push(iP(t)),new iW("timestamp_extract",r,"timestampExtract")}documentId(){return new iW("document_id",[this],"documentId")}parent(){return new iW("parent",[this],"parent")}substring(e,t){let r=iP(e);return new iW("substring",void 0===t?[this,r]:[this,r,iP(t)],"substring")}arrayGet(e){return new iW("array_get",[this,iP(e)],"arrayGet")}isError(){return new iW("is_error",[this],"isError").asBoolean()}ifError(e){let t=new iW("if_error",[this,iP(e)],"ifError");return e instanceof iH?t.asBoolean():t}isAbsent(){return new iW("is_absent",[this],"isAbsent").asBoolean()}mapRemove(e){return new iW("map_remove",[this,iP(e)],"mapRemove")}mapMerge(e,...t){return new iW("map_merge",[this,iP(e),...t.map(iP)],"mapMerge")}pow(e){return new iW("pow",[this,iP(e)])}trunc(e){return void 0===e?new iW("trunc",[this]):new iW("trunc",[this,iP(e)],"trunc")}round(e){return void 0===e?new iW("round",[this]):new iW("round",[this,iP(e)],"round")}collectionId(){return new iW("collection_id",[this])}length(){return new iW("length",[this])}ln(){return new iW("ln",[this])}sqrt(){return new iW("sqrt",[this])}stringReverse(){return new iW("string_reverse",[this])}ifAbsent(e){return new iW("if_absent",[this,iP(e)],"ifAbsent")}ifNull(e){return new iW("if_null",[this,iP(e)],"ifNull")}coalesce(e,...t){return new iW("coalesce",[this,iP(e),...t.map(iP)],"coalesce")}join(e){return new iW("join",[this,iP(e)],"join")}log10(){return new iW("log10",[this])}arraySum(){return new iW("sum",[this])}split(e){return new iW("split",[this,iP(e)])}timestampTruncate(e,t){let r=[this,iP(e)];return t&&r.push(iP(t)),new iW("timestamp_trunc",r)}ascending(){var e;return e=this,new iZ(iF(e),"ascending","ascending")}descending(){var e;return e=this,new iZ(iF(e),"descending","descending")}as(e){return new iq(this,e,"as")}}class iU{constructor(e,t){this.name=e,this.params=t,this.exprType="AggregateFunction",this._protoValueType="ProtoValue"}static _create(e,t,r){let n=new iU(e,t);return n._methodName=r,n}as(e){return new iB(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}
vendor: 9,104 bytes, line 3
3):e,this.params.forEach(t=>t._readUserData(e))}}class iB{constructor(e,t,r){this.aggregate=e,this.alias=t,this._methodName=r}_readUserData(e){this.aggregate._readUserData(e)}}class iq{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 iz extends iM{constructor(e,t){super(),this.ur=e,this._methodName=t,this.expressionType="ListOfExpressions"}_toProto(e){return{arrayValue:{values:this.ur.map(t=>t._toProto(e))}}}_readUserData(e){this.ur.forEach(t=>t._readUserData(e))}}class i$ extends iM{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 iW("geo_distance",[this,iP(e)],"geoDistance")}_toProto(e){return{fieldReferenceValue:this.fieldPath.canonicalString()}}_readUserData(e){}}function ij(e){var t,r;return r="field",new i$("string"==typeof(t=e)?M===t?new na(M)._internalPath:iN("field",t):t._internalPath,r)}class iK extends iM{constructor(e,t){super(),this.value=e,this._methodName=t,this.expressionType="Constant"}static _fromProto(e){let t=new iK(e,void 0);return t._protoValue=e,t}_toProto(e){return T(void 0!==this._protoValue,237),this._protoValue}_getValue(){return this._protoValue}_readUserData(e){var t,r,n,i,s,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(i=t.arrayValue)&&null!==i&&!(!("values"in i)||null!==i.values&&!Array.isArray(i.values)))||"mapValue"in t&&(null===t.mapValue||"object"==typeof(s=t.mapValue)&&null!==s&&!(!("fields"in s)||null!==s.fields&&!X(s.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=ib(this.value,e))}}function iG(e,t){return iQ(e,"constant")}function iQ(e,t){let r=new iK(e,t);return"boolean"==typeof e?new iX(r):r}class iW extends iM{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 iR({})}_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}):e,this.params.forEach(t=>t._readUserData(e)),this._options&&(this._optionsProto=this._optionsUtil.getOptionsProto(e,this._options))}}class iH extends iM{get _methodName(){return this._expr._methodName}countIf(){return iU._create("count_if",[this],"countIf")}not(){return new iW("not",[this],"not").asBoolean()}conditional(e,t){return new iW("conditional",[this,e,t],"conditional")}ifError(e){let t=iP(e),r=new iW("if_error",[this,t],"ifError");return t instanceof iH?r.asBoolean():r}_toProto(e){return this._expr._toProto(e)}_readUserData(e){this._expr._readUserData(e)}}class iY extends iH{constructor(e){super(),this._expr=e,this.expressionType="Function"}}class iX extends iH{constructor(e){super(),this._expr=e,this.expressionType="Constant"}_getValue(){return this._expr._getValue()}}class iJ extends iH{constructor(e){super(),this._expr=e,this.expressionType="Field"}}class iZ{constructor(e,t,r){this.expr=e,this.direction=t,this._methodName=r,this._protoValueType="ProtoValue"}_toProto(e){return{mapValue:{fields:{direction:nn(this.direction),expression:this.expr._toProto(e)}}}}_readUserData(e){this.expr._readUserData(e)}}class i0{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 i1 extends i0{get _name(){return"add_fields"}get _optionsUtil(){return new iR({})}constructor(e,t){super(t),this.fields=e}_toProto(e){return{...super._toProto(e),args:[nr(e,this.fields)]}}_readUserData(e){super._readUserData(e),si(this.fields,e)}}class i2 extends i0{get _name(){return"aggregate"}get _optionsUtil(){return new iR({})}constructor(e,t,r){super(r),this.groups=e,this.accumulators=t}_toProto(e){return{...super._toProto(e),args:[nr(e,this.accumulators),nr(e,this.groups)]}}_readUserData(e){super._readUserData(e),si(this.groups,e),si(this.accumulators,e)}}class i4 extends i0{get _name(){return"distinct"}get _optionsUtil(){return new iR({})}constructor(e,t){super(t),this.groups=e}_toProto(e){return{...super._toProto(e),args:[nr(e,this.groups)]}}_readUserData(e){super._readUserData(e),si(this.groups,e)}}class i3 extends i0{get _name(){return"collection"}get _optionsUtil(){return new iR({forceIndex:{serverName:"force_index"}})}constructor(e,t){super(t),this.Er=e.startsWith("/")?e:"/"+e}_toProto(e){return{...super._toProto(e),args:[{referenceValue:this.Er}]}}_readUserData(e){super._readUserData(e)}}class i6 extends i0{get _name(){return"collection_group"}get _optionsUtil(){return new iR({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 i5 extends i0{get _name(){return"database"}get _optionsUtil(){return new iR({})}_toProto(e){return{...super._toProto(e)}}_readUserData(e){super._readUserData(e)}}class i8 extends i0{get _name(){return"documents"}get _optionsUtil(){return new iR({})}constructor(e,t){if(super(t),!e||0===e.length)throw new F(O.INVALID_ARGUMENT,"Empty document paths are not allowed in DocumentsSource");let r=e.map(e=>e.startsWith("/")?e:"/"+e),n=new Set(r);if(n.size!==r.length)throw new F(O.INVALID_ARGUMENT,"Duplicate document paths are not allowed in DocumentsSource");this.hr=r,this.Tr=n}_toProto(e){return{...super._toProto(e),args:this.hr.map(e=>({referenceValue:e}))}}_readUserData(e){super._readUserData(e)}}class i9 extends i0{get _name(){return"where"}get _optionsUtil(){return new iR({})}constructor(e,t){super(t),this.condition=e}_toProto(e){return{...super._toProto(e),args:[this.condition._toProto(e)]}}_readUserData(e){super._readUserData(e),si(this.condition,e)}}class i7 extends i0{get _name(){return"limit"}get _optionsUtil(){return new iR({})}constructor(e,t){T(!isNaN(e)&&e!==1/0&&e!==-1/0,34860),super(t),this.limit=e}_toProto(e){return{...super._toProto(e),args:[e0(e,this.limit)]}}}class se extends i0{get _name(){return"offset"}get _optionsUtil(){return new iR({})}constructor(e,t){super(t),this.offset=e}_toProto(e){return{...super._toProto(e),args:[e0(e,this.offset)]}}}class st extends i0{get _name(){return"select"}get _optionsUtil(){return new iR({})}constructor(e,t){super(t),this.selections=e}_toProto(e){return{...super._toProto(e),args:[nr(e,this.selections)]}}_readUserData(e){super._readUserData(e),si(this.selections,e)}}class sr extends i0{get _name(){return"sort"}get _optionsUtil(){return new iR({})}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),si(this.orderings,e)}}class sn extends i0{get _name(){return"replace_with"}get _optionsUtil(){return new iR({})}constructor(e,t){super(t),this.map=e}_toProto(e){return{...super._toProto(e),args:[this.map._toProto(e),nn(sn.Pr)]}}_readUserData(e){super._readUserData(e),si(this.map,e)}}function si(e,t){return ik(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}sn.Pr="full_replace";class ss{constructor(e,t,r,n){this._db=e,this.userDataReader=t,this._userDataWriter=r,this.stages=n}Ar(e,t){let r=this.userDataReader.createContext(3,e);return ik(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.Ar("where",e),t.push(new i9(e,{})),new ss(this._db,this.userDataReader,this._userDataWriter,t)}limit(e){let t=this.stages.map(e=>e);return t.push(new i7(e,{})),new ss(this._db,this.userDataReader,this._userDataWriter,t)}sort(e,...t){let r=this.stages.map(e=>e);return"orderings"in e?r.push(new sr(this.Ar("sort",e.orderings),{})):r.push(new sr(this.Ar("sort",[e,...t]),{})),new ss(this._db,this.userDataReader,this._userDataWriter,r)}Vr(e){return{pipeline:{stages:this.stages.map(t=>t._toProto(e))}}}}class sa{constructor(e,t){this.type=e,this.value=t}static dr(){return new sa("ERROR",void 0)}static mr(){return new sa("UNSET",void 0)}static pr(){return new sa("NULL",eS)}static newValue(e){return eq(e)?new sa("NULL",eS):e&&"booleanValue"in e?new sa("BOOLEAN",e):eF(e)?new sa("INT",e):eM(e)?new sa("DOUBLE",e):e&&"timestampValue"in e&&e.timestampValue?new sa("TIMESTAMP",e):e&&"stringValue"in e?new sa("STRING",e):e&&"bytesValue"in e?new sa("BYTES",e):e.referenceValue?new sa("REFERENCE",e):e.geoPointValue?new sa("GEO_POINT",e):eB(e)?new sa("ARRAY",e):ej(e)?new sa("VECTOR",e):e$(e)?new sa("MAP",e):new sa("ERROR",void 0)}gr(){return"ERROR"===this.type||"UNSET"===this.type}yr(){return"NULL"===this.type}}function so(e){if(!e.gr())return e.value}function sl(e){return e instanceof iH?e._expr:e}function su(e){if((e=sl(e))instanceof i$)return new sc(e);if(e instanceof iK)return new sh(e);if(e instanceof iz)return new sd(e);if(e instanceof iW){if("add"===e.name)return new sv(e);if("subtract"===e.name)return new s_(e);if("multiply"===e.name)return new sx(e);if("divide"===e.name)return new sE(e);if("mod"===e.name)return new sb(e);if("and"===e.name)return new sT(e);if("equal"===e.name)return new sB(e);if("not_equal"===e.name)return new sq(e);if("less_than"===e.name)return new sz(e);if("less_than_or_equal"===e.name)return new s$(e);if("greater_than"===e.name)return new sj(e);if("greater_than_or_equal"===e.name)return new sK(e);if("array_concat"===e.name)return new sG(e);if("array_reverse"===e.name)return new sQ(e);if("array_contains"===e.name)return new sW(e);if("array_contains_all"===e.name)return new sH(e);if("array_contains_any"===e.name)return new sY(e);if("array_length"===e.name)return new sX(e);if("array_element"===e.name)return new sJ(e);if("equal_any"===e.name)return new sD(e);if("not_equal_any"===e.name)return new sC(e);if("is_nan"===e.name)return new sA(e);if("is_not_nan"===e.name)return new sV(e);if("is_null"===e.name)return new sk(e);if("is_not_null"===e.name)return new sR(e);if("is_error"===e.name)return new sL(e);if("exists"===e.name)return new sP(e);if("not"===e.name)return new sI(e);if("or"===e.name)return new sS(e);if("xor"===e.name)return new sN(e);if("conditional"===e.name)return new sO(e);if("maximum"===e.name)return new sF(e);if("minimum"===e.name)return new sM(e);if("reverse"===e.name)return new sZ(e);if("replace_first"===e.name)return new s0(e);if("replace_all"===e.name)return new s1(e);if("char_length"===e.name)return new s2(e);if("byte_length"===e.name)return new s4(e);if("like"===e.name)return new s6(e);if("regex_contains"===e.name)return new s5(e);if("regex_match"===e.name)return new s8(e);if("string_contains"===e.name)return new s9(e);if("starts_with"===e.name)return new s7(e);if("ends_with"===e.name)return new ae(e);if("to_lower"===e.name)return new at(e);if("to_upper"===e.name)return new ar(e);if("trim"===e.name)return new an(e);if("string_concat"===e.name)return new ai(e);if("map_get"===e.name)return new as(e);if("cosine_distance"===e.name)return new ao(e);if("dot_product"===e.name)return new al(e);if("euclidean_distance"===e.name)return new au(e);if("vector_length"===e.name)return new ac(e);if("unix_micros_to_timestamp"===e.name)return new aT(e);if("timestamp_to_unix_micros"===e.name)return new aD(e);if("unix_millis_to_timestamp"===e.name)return new aI(e);if("timestamp_to_unix_millis"===e.name)return new aC(e);if("unix_seconds_to_timestamp"===e.name)return new aS(e);if("timestamp_to_unix_seconds"===e.name)return new aA(e);if("timestamp_add"===e.name)return new ak(e);if("timestamp_subtract"===e.name)return new aR(e)}throw Error(`Unknown Expr : ${e}`)}class sc{constructor(e){this.expr=e}evaluate(e,t){if(this.expr.fieldName===M)return sa.newValue({referenceValue:rH(e.serializer,t.key)});if("__update_time__"===this.expr.fieldName)return sa.newValue({timestampValue:rj(e.serializer,t.version)});if("__create_time__"===this.expr.fieldName)return sa.newValue({timestampValue:rj(e.serializer,t.createTime)});let r=t.data.field(this.expr._fieldPath);return r?ef(r)?sa.newValue(function(e,t){if("estimate"===e.serverTimestampBehavior)return{timestampValue:rj(e.serializer,tB.fromTimestamp(ep(t)))};if("previous"===e.serverTimestampBehavior){let e=em(t);if(e)return e}return{nullValue:"NULL_VALUE"}}(e,r)):sa.newValue(r):sa.mr()}}class sh{constructor(e){this.expr=e}evaluate(e,t){return sa.newValue(this.expr._getValue())}}class sd{constructor(e){this.expr=e}evaluate(e,t){let r=this.expr.ur.map(r=>su(r).evaluate(e,t));return r.some(e=>e.gr())?sa.dr():sa.newValue({arrayValue:{values:r.map(e=>e.value)}})}}function sf(e){return eM(e)?Number(e.doubleValue):Number(e.integerValue)}function sm(e){return BigInt(e.integerValue)}let sp=BigInt("0x7fffffffffffffff"),sg=-BigInt("0x8000000000000000");class sy{constructor(e){this.expr=e}evaluate(e,t){T(this.expr.params.length>=2,24778);let r=su(this.expr.params[0]).evaluate(e,t),n=su(this.expr.params[1]).evaluate(e,t),i=this.wr(r,n);for(let r of this.expr.params.slice(2)){let n=su(r).evaluate(e,t);i=this.wr(i,n)}return i}wr(e,t){if(e.gr()||t.gr())return sa.dr();if(e.yr()||t.yr())return sa.pr();let r=e.value,n=t.value;if(!eM(r)&&!eF(r)||!eM(n)&&!eF(n))return sa.dr();if(eM(r)||eM(n)){let e=this.br(r,n);return e?sa.newValue(e):sa.dr()}if(eF(r)&&eF(n)){let e=this.vr(r,n);return void 0===e?sa.dr():"number"==typeof e?sa.newValue({doubleValue:e}):e<sg||e>sp?sa.dr():sa.newValue({integerValue:`${e}`})}return sa.dr()}}function sw(e,t){return eC(e)!==eC(t)?"TYPE_MISMATCH":ez(e)||ez(t)?"NOT_EQ":eq(e)&&eq(t)?"EQ":eq(e)||eq(t)?"NULL":eB(e)&&eB(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 i=e.values[n],s=t.values[n];switch(sw(i,s)){case"EQ":break;case"NOT_EQ":case"TYPE_MISMATCH":return"NOT_EQ";case"NULL":r=!0;break;default:E(44609,{Sr:i,Dr:s})}}return r?"NULL":"EQ"}(e.arrayValue,t.arrayValue):ej(e)&&ej(t)||e$(e)&&e$(t)?function(e,t){let r=e.fields||{},n=t.fields||{};if(j(r)!==j(n))return"NOT_EQ";let i=!1;for(let e in r)if(r.hasOwnProperty(e)){if(void 0===n[e])return"NOT_EQ";switch(sw(r[e],n[e])){case"NOT_EQ":case"TYPE_MISMATCH":return"NOT_EQ";case"NULL":i=!0}}return i?"NULL":"EQ"}(e.mapValue,t.mapValue):eA(e,t,{o:!1,t:!0,i:!0})?"EQ":"NOT_EQ"}class sv extends sy{vr(e,t){return sm(e)+sm(t)}br(e,t){return{doubleValue:sf(e)+sf(t)}}}class s_ extends sy{constructor(e){super(e),this.expr=e}vr(e,t){return sm(e)-sm(t)}br(e,t){return{doubleValue:sf(e)-sf(t)}}}class sx extends sy{constructor(e){super(e),this.expr=e}vr(e,t){return sm(e)*sm(t)}br(e,t){return{doubleValue:sf(e)*sf(t)}}}class sE extends sy{constructor(e){super(e),this.expr=e}vr(e,t){let r=sm(t);if(r!==BigInt(0))return sm(e)/r}br(e,t){let r=sf(t);return 0===r?{doubleValue:e_(r)?-1/0:1/0}:{doubleValue:sf(e)/r}}}class sb extends sy{constructor(e){super(e),this.expr=e}vr(e,t){let r=sm(t);if(r!==BigInt(0))return sm(e)%r}br(e,t){let r=sf(t);if(0!==r)return{doubleValue:sf(e)%r}}}class sT{constructor(e){this.expr=e}evaluate(e,t){let r=!1,n=!1;for(let i of this.expr.params){let s=su(i).evaluate(e,t);switch(s.type){case"BOOLEAN":if(!s.value?.booleanValue)return sa.newValue(eD);break;case"NULL":n=!0;break;default:r=!0}}
3return r?sa.dr():n?sa.pr():sa.newValue(eN)}}class sI{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,9634);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"BOOLEAN":return sa.newValue({booleanValue:!r.value?.booleanValue});case"NULL":return sa.pr();default:return sa.dr()}}}class sS{constructor(e){this.expr=e}evaluate(e,t){let r=!1,n=!1;for(let i of this.expr.params){let s=su(i).evaluate(e,t);switch(s.type){case"BOOLEAN":if(s.value?.booleanValue)return sa.newValue(eN);break;case"NULL":n=!0;break;default:r=!0}}return r?sa.dr():n?sa.pr():sa.newValue(eD)}}class sN{constructor(e){this.expr=e}evaluate(e,t){let r=!1,n=!1;for(let i of this.expr.params){let s=su(i).evaluate(e,t);switch(s.type){case"BOOLEAN":r=sN.xor(r,!!s.value?.booleanValue);break;case"NULL":n=!0;break;default:return sa.dr()}}return n?sa.pr():sa.newValue({booleanValue:r})}static xor(e,t){return(e||t)&&!(e&&t)}}class sD{constructor(e){this.expr=e}evaluate(e,t){T(2===this.expr.params.length,55094);let r=!1,n=su(this.expr.params[0]).evaluate(e,t);switch(n.type){case"NULL":r=!0;break;case"ERROR":case"UNSET":return sa.dr()}let i=su(this.expr.params[1]).evaluate(e,t);switch(i.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sa.dr()}if(r)return sa.pr();for(let e of i.value?.arrayValue?.values??[])switch(eq(n.value)&&eq(e)?"EQ":sw(n.value,e)){case"EQ":return sa.newValue(eN);case"NOT_EQ":case"TYPE_MISMATCH":break;case"NULL":r=!0;break;default:E(44608,{value:n.value,candidate:e})}return r?sa.pr():sa.newValue(eD)}}class sC{constructor(e){this.expr=e}evaluate(e,t){return new sI(new iW("not",[new iW("equal_any",this.expr.params)])).evaluate(e,t)}}class sA{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,23322);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"INT":return sa.newValue(eD);case"DOUBLE":return sa.newValue({booleanValue:isNaN(sf(r.value))});case"NULL":return sa.pr();default:return sa.dr()}}}class sV{constructor(e){this.expr=e}evaluate(e,t){return T(1===this.expr.params.length,50406),new sI(new iW("not",[new iW("is_nan",this.expr.params)])).evaluate(e,t)}}class sk{constructor(e){this.expr=e}evaluate(e,t){switch(T(1===this.expr.params.length,23123),su(this.expr.params[0]).evaluate(e,t).type){case"NULL":return sa.newValue(eN);case"UNSET":case"ERROR":return sa.dr();default:return sa.newValue(eD)}}}class sR{constructor(e){this.expr=e}evaluate(e,t){return T(1===this.expr.params.length,23167),new sI(new iW("not",[new iW("is_null",this.expr.params)])).evaluate(e,t)}}class sL{constructor(e){this.expr=e}evaluate(e,t){return T(1===this.expr.params.length,5228),"ERROR"===su(this.expr.params[0]).evaluate(e,t).type?sa.newValue(eN):sa.newValue(eD)}}class sP{constructor(e){this.expr=e}evaluate(e,t){switch(T(1===this.expr.params.length,6877),su(this.expr.params[0]).evaluate(e,t).type){case"ERROR":return sa.dr();case"UNSET":return sa.newValue(eD);default:return sa.newValue(eN)}}}class sO{constructor(e){this.expr=e}evaluate(e,t){T(3===this.expr.params.length,11706);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"BOOLEAN":return r.value?.booleanValue?su(this.expr.params[1]).evaluate(e,t):su(this.expr.params[2]).evaluate(e,t);case"NULL":return su(this.expr.params[2]).evaluate(e,t);default:return sa.dr()}}}class sF{constructor(e){this.expr=e}evaluate(e,t){let r;for(let n of this.expr.params.map(r=>su(r).evaluate(e,t)))switch(n.type){case"ERROR":case"UNSET":case"NULL":continue;default:r=void 0===r||ek(n.value,r.value)>0?n:r}return void 0===r?sa.pr():r}}class sM{constructor(e){this.expr=e}evaluate(e,t){let r;for(let n of this.expr.params.map(r=>su(r).evaluate(e,t)))switch(n.type){case"ERROR":case"UNSET":case"NULL":continue;default:r=void 0===r||0>ek(n.value,r.value)?n:r}return void 0===r?sa.pr():r}}class sU{constructor(e){this.expr=e}evaluate(e,t){T(2===this.expr.params.length,31033,`${this.expr.name}() function should have exactly 2 params`);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"ERROR":case"UNSET":return sa.dr()}let n=su(this.expr.params[1]).evaluate(e,t);switch(n.type){case"ERROR":case"UNSET":return sa.dr()}return this.Cr(r,n)}}class sB extends sU{constructor(e){super(e),this.expr=e}
3Cr(e,t){if(e.yr()&&t.yr())return sa.newValue(eN);if(e.yr()||t.yr()||ez(e.value)||ez(t.value)||eC(e.value)!==eC(t.value))return sa.newValue(eD);switch(sw(e.value,t.value)){case"EQ":return sa.newValue(eN);case"NOT_EQ":return sa.newValue(eD);case"NULL":return sa.pr();default:E(44615,{left:e,right:t})}}}class sq extends sU{constructor(e){super(e),this.expr=e}Cr(e,t){switch(sw(e.value,t.value)){case"EQ":return sa.newValue(eD);case"NOT_EQ":case"TYPE_MISMATCH":return sa.newValue(eN);case"NULL":return sa.pr();default:E(44614,{left:e,right:t})}}}class sz extends sU{constructor(e){super(e),this.expr=e}Cr(e,t){return eC(e.value)!==eC(t.value)||ez(e.value)||ez(t.value)?sa.newValue(eD):sa.newValue({booleanValue:0>ek(e.value,t.value)})}}class s$ extends sU{constructor(e){super(e),this.expr=e}Cr(e,t){return eC(e.value)!==eC(t.value)||ez(e.value)||ez(t.value)?sa.newValue(eD):"EQ"===sw(e.value,t.value)?sa.newValue(eN):sa.newValue({booleanValue:0>ek(e.value,t.value)})}}class sj extends sU{constructor(e){super(e),this.expr=e}Cr(e,t){return eC(e.value)!==eC(t.value)||ez(e.value)||ez(t.value)?sa.newValue(eD):sa.newValue({booleanValue:ek(e.value,t.value)>0})}}class sK extends sU{constructor(e){super(e),this.expr=e}Cr(e,t){return eC(e.value)!==eC(t.value)||ez(e.value)||ez(t.value)?sa.newValue(eD):"EQ"===sw(e.value,t.value)?sa.newValue(eN):sa.newValue({booleanValue:ek(e.value,t.value)>0})}}class sG{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class sQ{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,216);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sa.pr();case"ARRAY":{let e=r.value.arrayValue?.values??[];return sa.newValue({arrayValue:{values:[...e].reverse()}})}default:return sa.dr()}}}class sW{constructor(e){this.expr=e}evaluate(e,t){return T(2===this.expr.params.length,52884),new sD(new iW("eq_any",[this.expr.params[1],this.expr.params[0]])).evaluate(e,t)}}class sH{constructor(e){this.expr=e}evaluate(e,t){T(2===this.expr.params.length,1392);let r=!1,n=su(this.expr.params[0]).evaluate(e,t);switch(n.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sa.dr()}let i=su(this.expr.params[1]).evaluate(e,t);switch(i.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sa.dr()}if(r)return sa.pr();let s=i.value?.arrayValue?.values??[],a=n.value?.arrayValue?.values??[];for(let e of s){let t=!1;for(let n of(r=!1,a)){switch(eq(e)&&eq(n)?"EQ":sw(e,n)){case"EQ":t=!0;break;case"NOT_EQ":case"TYPE_MISMATCH":break;case"NULL":r=!0;break;default:E(44613,{value:n,search:e})}if(t)break}if(!t)return sa.newValue(eD)}return sa.newValue(eN)}}class sY{constructor(e){this.expr=e}evaluate(e,t){T(2===this.expr.params.length,2680);let r=!1,n=su(this.expr.params[0]).evaluate(e,t);switch(n.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sa.dr()}let i=su(this.expr.params[1]).evaluate(e,t);switch(i.type){case"ARRAY":break;case"NULL":r=!0;break;default:return sa.dr()}if(r)return sa.pr();let s=i.value?.arrayValue?.values??[];for(let e of n.value?.arrayValue?.values??[])for(let t of s)switch(eq(e)&&eq(t)?"EQ":sw(e,t)){case"EQ":return sa.newValue(eN);case"NOT_EQ":case"TYPE_MISMATCH":break;case"NULL":r=!0;break;default:E(60403,{value:e,search:t})}return r?sa.pr():sa.newValue(eD)}}class sX{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,38605);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sa.pr();case"ARRAY":return sa.newValue({integerValue:`${r.value?.arrayValue?.values?.length??0}`});default:return sa.dr()}}}class sJ{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class sZ{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,1508);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sa.pr();case"BYTES":{let e=r.value?.bytesValue;if("string"==typeof e){let t=ei.fromBase64String(e).toUint8Array();return t.reverse(),sa.newValue({bytesValue:ei.fromUint8Array(t).toBase64()})}return sa.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 sa.newValue({stringValue:t.join("")})}default:return sa.dr()}}}class s0{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class s1{constructor(e){this.expr=e}evaluate(e,t){throw Error("Unimplemented")}}class s2{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,19400);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"NULL":return sa.pr();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?sa.dr():sa.newValue({integerValue:e})}default:return sa.dr()}}}class s4{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,8486);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"BYTES":{let e=r.value?.bytesValue;return"string"==typeof e?sa.newValue({integerValue:ei.fromBase64String(e).toUint8Array().length}):sa.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?sa.dr():sa.newValue({integerValue:e})}case"NULL":return sa.pr();default:return sa.dr()}}}class s3{constructor(e){this.expr=e}evaluate(e,t){T(2===this.expr.params.length,39773,`${this.expr.name}() function should have exactly two parameters`);let r=!1,n=su(this.expr.params[0]).evaluate(e,t);switch(n.type){case"STRING":break;case"NULL":r=!0;break;default:return sa.dr()}let i=su(this.expr.params[1]).evaluate(e,t);switch(i.type){case"STRING":break;case"NULL":r=!0;break;default:return sa.dr()}return r?sa.pr():this.Fr(n.value?.stringValue,i.value?.stringValue)}}class s6 extends s3{Fr(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=h.L3.compile(r);return sa.newValue({booleanValue:n.matches(e)})}catch(e){return _(`Invalid LIKE pattern converted to regex: ${t}, returning error. Error: ${e}`),sa.dr()}}}class s5 extends s3{Fr(e,t){try{let r=h.L3.compile(t);return sa.newValue({booleanValue:r.test(e)})}catch(e){return _(`Invalid regex pattern found in regex_contains: ${t}, returning error`),sa.dr()}}}class s8 extends s3{Fr(e,t){try{return sa.newValue({booleanValue:h.L3.compile(t).matches(e)})}catch(e){return _(`Invalid regex pattern found in regex_match: ${t}, returning error`),sa.dr()}}}class s9 extends s3{Fr(e,t){return sa.newValue({booleanValue:e.includes(t)})}}class s7 extends s3{Fr(e,t){return sa.newValue({booleanValue:e.startsWith(t)})}}class ae extends s3{Fr(e,t){return sa.newValue({booleanValue:e.endsWith(t)})}}class at{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,29079);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"STRING":return sa.newValue({stringValue:r.value?.stringValue?.toLowerCase()});case"NULL":return sa.pr();default:return sa.dr()}}}class ar{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,60487);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"STRING":return sa.newValue({stringValue:r.value?.stringValue?.toUpperCase()});case"NULL":return sa.pr();default:return sa.dr()}}}class an{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,28544);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"STRING":return sa.newValue({stringValue:r.value?.stringValue?.trim()});case"NULL":return sa.pr();default:return sa.dr()}}}class ai{constructor(e){this.expr=e}evaluate(e,t){let r=this.expr.params.map(r=>su(r).evaluate(e,t)),n="",i=!1;for(let e of r)switch(e.type){case"STRING":n+=e.value.stringValue;break;case"NULL":i=!0;break;default:return sa.dr()}return i?sa.pr():sa.newValue({stringValue:n})}}class as{constructor(e){this.expr=e}evaluate(e,t){T(2===this.expr.params.length,4483);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"UNSET":return sa.mr();case"MAP":break;default:return sa.dr()}let n=su(this.expr.params[1]).evaluate(e,t);if("STRING"!==n.type)return sa.dr();let i=r.value?.mapValue?.fields?.[n.value?.stringValue];return void 0===i?sa.mr():sa.newValue(i)}}class aa{constructor(e){this.expr=e}evaluate(e,t){T(2===this.expr.params.length,25231,`${this.expr.name}() function should have exactly 2 params`);let r=!1,n=su(this.expr.params[0]).evaluate(e,t);switch(n.type){case"VECTOR":break;case"NULL":r=!0;break;default:return sa.dr()}let i=su(this.expr.params[1]).evaluate(e,t);switch(i.type){case"VECTOR":break;case"NULL":r=!0;break;default:return sa.dr()}if(r)return sa.pr();let s=eK(n.value),a=eK(i.value);if(void 0===s||void 0===a||s.values?.length!==a.values?.length)return sa.dr();let o=this.Or(s,a);return void 0===o||isNaN(o)?sa.dr():sa.newValue({doubleValue:o})}}class ao extends aa{Or(e,t){let r=e?.values??[],n=t?.values??[];if(0===r.length)return;let i=0,s=0,a=0;for(let e=0;e<r.length;e++){if(!eU(r[e])||!eU(n[e]))return;let t=sf(r[e]),o=sf(n[e]);i+=t*o,s+=t*t,a+=o*o}
3let o=Math.sqrt(s)*Math.sqrt(a);if(0!==o)return 1-Math.max(-1,Math.min(1,i/o))}}class al extends aa{Or(e,t){let r=e?.values??[],n=t?.values??[];if(0===r.length)return 0;let i=0;for(let e=0;e<r.length;e++){if(!eU(r[e])||!eU(n[e]))return;i+=sf(r[e])*sf(n[e])}return i}}class au extends aa{Or(e,t){let r=e?.values??[],n=t?.values??[];if(0===r.length)return 0;let i=0;for(let e=0;e<r.length;e++){if(!eU(r[e])||!eU(n[e]))return;i+=Math.pow(sf(r[e])-sf(n[e]),2)}return Math.sqrt(i)}}class ac{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,39044);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"VECTOR":{let e=eK(r.value);return sa.newValue({integerValue:e?.values?.length??0})}case"NULL":return sa.pr();default:return sa.dr()}}}let ah=BigInt(-0xe7791f700),ad=BigInt(0x3afff4417f),af=BigInt(1e3),am=BigInt(1e6),ap=ah*af,ag=ad*af+BigInt(999),ay=ah*am,aw=ad*am+BigInt(999999);function av(e){return e>=ay&&e<=aw}function a_(e,t){let r=BigInt(e);return!(r<ah||r>ad)&&!(t<0||t>=1e9)&&(r!==ah||0===t)&&!(r===ad&&t>0x3b9ac9ff)}function ax(e,t){return t<0?{seconds:e-1,nanos:t+1e9}:{seconds:e,nanos:t}}function aE(e){return BigInt(e.seconds)*am+BigInt(Math.trunc(e.nanoseconds/1e3))}class ab{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,49262,`${this.expr.name}() function should have exactly one parameter`);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"INT":return this.toTimestamp(BigInt(r.value.integerValue));case"NULL":return sa.pr();default:return sa.dr()}}}class aT extends ab{toTimestamp(e){if(!av(e))return sa.dr();let t=Number(e/am),r=Number(e%am*BigInt(1e3)),n=ax(t,r);return a_(t=n.seconds,r=n.nanos)?sa.newValue({timestampValue:{seconds:t,nanos:r}}):sa.dr()}}class aI extends ab{toTimestamp(e){if(!(e>=ap&&e<=ag))return sa.dr();let t=Number(e/af),r=Number(e%af*BigInt(1e6)),n=ax(t,r);return a_(t=n.seconds,r=n.nanos)?sa.newValue({timestampValue:{seconds:t,nanos:r}}):sa.dr()}}class aS extends ab{toTimestamp(e){if(!(e>=ah&&e<=ad))return sa.dr();let t=Number(e);return sa.newValue({timestampValue:{seconds:t,nanos:0}})}}class aN{constructor(e){this.expr=e}evaluate(e,t){T(1===this.expr.params.length,1265,`${this.expr.name}() function should have exactly one parameter`);let r=su(this.expr.params[0]).evaluate(e,t);switch(r.type){case"TIMESTAMP":break;case"NULL":return sa.pr();default:return sa.dr()}let n=rz(r.value.timestampValue);return a_(n.seconds,n.nanoseconds)?this.Mr(n):sa.dr()}}class aD extends aN{Mr(e){let t=aE(e);return av(t)?sa.newValue({integerValue:`${t.toString()}`}):sa.dr()}}class aC extends aN{Mr(e){let t=aE(e),r=t/BigInt(1e3),n=t%BigInt(1e3);return r>BigInt(0)||n===BigInt(0)?sa.newValue({integerValue:r.toString()}):sa.newValue({integerValue:(r-BigInt(1)).toString()})}}class aA extends aN{Mr(e){let t=BigInt(e.seconds);return t>=ah&&t<=ad?sa.newValue({integerValue:t.toString()}):sa.dr()}}class aV{constructor(e){this.expr=e}evaluate(e,t){let r,n;T(3===this.expr.params.length,2775,`${this.expr.name}() function should have exactly 3 parameters`);let i=!1,s=su(this.expr.params[0]).evaluate(e,t);switch(s.type){case"TIMESTAMP":break;case"NULL":i=!0;break;default:return sa.dr()}let a=su(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 sa.dr();break;case"NULL":i=!0;break;default:return sa.dr()}let o=su(this.expr.params[2]).evaluate(e,t);switch(o.type){case"INT":break;case"NULL":i=!0;break;default:return sa.dr()}if(i)return sa.pr();let 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 sa.dr()}if("microsecond"!==r&&l!==BigInt(0)&&n/l!==BigInt(this.Nr(r)))return sa.dr()}catch(e){return _(`Error during timestamp arithmetic: ${e}`),sa.dr()}let u=rz(s.value.timestampValue);if(!a_(u.seconds,u.nanoseconds))return sa.dr();let c=aE(u),h=this.Lr(c,n);if(!av(h))return sa.dr();let d=Number(h/am),f=h%am,m=Number((f<0?f+am:f)*BigInt(1e3)),p=f<0?d-1:d;return a_(p,m)?sa.newValue({timestampValue:{seconds:p,nanos:m}}):sa.dr()}Nr(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 ak extends aV{Lr(e,t){return e+t}}class aR extends aV{Lr(e,t){return e-t}}
3class aL{constructor(e,t,r){this.serializer=e,this.stages=t,this.listenOptions=r,this.isCorePipeline=!0}getPipelineCollection(){return aO(this)}getPipelineCollectionGroup(){return aF(this)}getPipelineCollectionId(){var e=this;switch(aP(e)){case"collection":return B.fromString(aO(e)).lastSegment();case"collection_group":return aF(e);default:return}}getPipelineDocuments(){return aM(this)}getPipelineFlavor(){var e;let t;return e=this,t="exact",e.stages.forEach((r,n)=>{r._name!==i4.name&&r._name!==i2.name||(t="keyless"),r._name===st.name&&"exact"===t&&(t="augmented"),r._name===i1.name&&n<e.stages.length-1&&"exact"===t&&(t="augmented")}),t}getPipelineSourceType(){return aP(this)}}function aP(e){let t=e.stages[0];return t instanceof i3||t instanceof i6||t instanceof i5||t instanceof i8?t._name:"unknown"}function aO(e){if("collection"===aP(e))return e.stages[0].Er}function aF(e){if("collection_group"===aP(e))return e.stages[0].collectionId}function aM(e){if("documents"===aP(e))return e.stages[0].hr}function aU(e){if((e=sl(e))instanceof i$)return`fld(${e.fieldName})`;if(e instanceof iK){var t;return`cst(${null===(t=e.value)?"null":"number"==typeof t?t.toString():"string"==typeof t?`"${t}"`:t instanceof ii?`ref(${t.path})`:t instanceof il?`vec(${JSON.stringify(t)})`:JSON.stringify(t)})`}if(e instanceof iW)return`fn(${e.name},[${e.params.map(aU).join(",")}])`;if("ListOfExpressions"===e.expressionType)return`list([${e.ur.map(aU).join(",")}])`;throw Error(`Unrecognized expr ${JSON.stringify(e,null,2)}`)}function aB(e){return`${Array.from(e.entries()).sort().map(([e,t])=>`${e}=${aU(t)}`).join(",")}`}function aq(e){return e.stages.map(e=>(function(e){if(e instanceof i1)return`${e._name}(${aB(e.fields)})`;if(e instanceof i2){let t=`${e._name}(${aB(e.accumulators)})`;return e.groups.size>0&&(t+=`grouping(${aB(e.groups)})`),t}if(e instanceof i4)return`${e._name}(${aB(e.groups)})`;if(e instanceof i3)return`${e._name}(${e.Er})`;if(e instanceof i6)return`${e._name}(${e.collectionId})`;if(e instanceof i5)return`${e._name}()`;if(e instanceof i8)return`${e._name}(${e.hr.sort()})`;if(e instanceof i9)return`${e._name}(${aU(e.condition)})`;if(e instanceof i7)return`${e._name}(${e.limit})`;if(e instanceof sr)return`${e._name}(${e.orderings.map(e=>`${aU(e.expr)}${e.direction}`).join(",")})`;throw Error(`Unrecognized stage ${e._name}`)})(e)).join("|")}function az(e){return e instanceof aL}function a$(e){return az(e)?aq(e):ra(e)}function aj(e){return az(e)?aq(e):`${tJ(re(e))}|lt:${e.limitType}`}function aK(e,t){return e instanceof aL&&t instanceof aL?aq(e)===aq(t):!(e instanceof aL&&!(t instanceof aL)||!(e instanceof aL)&&t instanceof aL)&&tZ(re(e),re(t))&&e.limitType===t.limitType}function aG(e){return t0(e)?aq(e):tJ(e)}function aQ(e,t){return e instanceof aL&&t instanceof aL?aq(e)===aq(t):!(e instanceof aL&&!(t instanceof aL)||!(e instanceof aL)&&t instanceof aL)&&tZ(e,t)}class aW{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){e instanceof tf?function(e,t,r){let n=e.value.clone(),i=tg(e.fieldTransforms,t,r.transformResults);n.setAll(i),t.convertToFoundDocument(r.version,n).setHasCommittedMutations()}(e,t,r):e instanceof tm?function(e,t,r){if(!tl(e.precondition,t))return t.convertToUnknownDocument(r.version);let n=tg(e.fieldTransforms,t,r.transformResults),i=t.data;i.setAll(tp(e)),i.setAll(n),t.convertToFoundDocument(r.version,i).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=th(r,e,t,this.localWriteTime));for(let r of this.mutations)r.key.isEqual(e.key)&&(t=th(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let r=rg();return this.mutations.forEach(n=>{let i=e.get(n.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=tc(s,a=t.has(n.key)?null:a);null!==o&&r.set(n.key,o),s.isValidDocument()||s.convertToNoDocument(tB.min())}),r}keys(){return this.mutations.reduce((e,t)=>
3e.add(t.key),rv())}isEqual(e){return this.batchId===e.batchId&&C(this.mutations,e.mutations,(e,t)=>td(e,t))&&C(this.baseMutations,e.baseMutations,(e,t)=>td(e,t))}}class aH{constructor(e,t,r,n){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=n}static from(e,t,r){T(e.mutations.length===r.length,58842,{Br:e.mutations.length,Ur:r.length});let n=ry,i=e.mutations;for(let e=0;e<i.length;e++)n=n.insert(i[e].key,r[e].version);return new aH(e,t,r,n)}}function aY(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"}function aX(e){let t=e.length;if(T(t>=2,64408,{path:e}),2===t)return T("\x01"===e.charAt(0)&&"\x01"===e.charAt(1),56145,{path:e}),B.emptyPath();let r=t-2,n=[],i="";for(let s=0;s<t;){let t=e.indexOf("\x01",s);switch((t<0||t>r)&&E(50515,{path:e}),e.charAt(t+1)){case"\x01":let a,o=e.substring(s,t);0===i.length?a=o:(i+=o,a=i,i=""),n.push(a);break;case"\x10":i+=e.substring(s,t),i+="\0";break;case"\x11":i+=e.substring(s,t+1);break;default:E(61167,{path:e})}s=t+2}return new B(n)}
3let aJ="remoteDocuments",aZ="owner",a0="owner",a1="mutationQueues",a2="mutations",a4="batchId",a3="userMutationsIndex",a6=["userId","batchId"],a5={},a8="documentMutations",a9="remoteDocumentsV14",a7=["prefixPath","collectionGroup","readTime","documentId"],oe="documentKeyIndex",ot=["prefixPath","collectionGroup","documentId"],or="collectionGroupIndex",on=["collectionGroup","readTime","prefixPath","documentId"],oi="remoteDocumentGlobal",os="remoteDocumentGlobalKey",oa="targets",oo="queryTargetsIndex",ol=["canonicalId","targetId"],ou="targetDocuments",oc=["targetId","path"],oh="documentTargetsIndex",od=["path","targetId"],of="targetGlobalKey",om="targetGlobal",op="collectionParents",og=["collectionId","parent"],oy="clientMetadata",ow="bundles",ov="namedQueries",o_="indexConfiguration",ox="collectionGroupIndex",oE="indexState",ob=["indexId","uid"],oT="sequenceNumberIndex",oI=["uid","sequenceNumber"],oS="indexEntries",oN=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],oD="documentKeyIndex",oC=["indexId","uid","orderedDocumentKey"],oA="documentOverlays",oV=["userId","collectionPath","documentId"],ok="collectionPathOverlayIndex",oR=["userId","collectionPath","largestBatchId"],oL="collectionGroupOverlayIndex",oP=["userId","collectionGroup","largestBatchId"],oO="globals",oF=[a1,a2,a8,aJ,oa,aZ,om,ou,oy,oi,op,ow,ov],oM=[...oF,oA],oU=[a1,a2,a8,a9,oa,aZ,om,ou,oy,oi,op,ow,ov,oA],oB=[...oU,o_,oE,oS],oq=[...oB,oO];function oz(e,t,r){let n=e.store(a2),i=e.store(a8),s=[],a=IDBKeyRange.only(r.batchId),o=0,l=n.jn({range:a},(e,t,r)=>(o++,r.delete()));s.push(l.next(()=>{T(1===o,47070,{batchId:r.batchId})}));let u=[];for(let e of r.mutations){var c,h;let n=(c=e.key.path,h=r.batchId,[t,aY(c),h]);s.push(i.delete(n)),u.push(e.key)}return nG.waitFor(s).next(()=>u)}function o$(e){let t;if(!e)return 0;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw E(14731);t=e.noDocument}return JSON.stringify(t).length}class oj extends nj{constructor(e,t){super(),this.kr=e,this.currentSequenceNumber=t}}function oK(e,t){return nH.xn(e.kr,t)}class oG{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 oQ{constructor(e,t,r,n,i=tB.min(),s=tB.min(),a=ei.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=n,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new oQ(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new oQ(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new oQ(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new oQ(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class oW{constructor(e){this.qr=e}}function oH(e,t){let r=t.key,n={prefixPath:r.getCollectionPath().popLast().toArray(),collectionGroup:r.collectionGroup,documentId:r.path.lastSegment(),readTime:oY(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument()){var i;n.document={name:rH(i=e.qr,t.key),fields:t.data.value.mapValue.fields,updateTime:rq(i,t.version.toTimestamp()),createTime:rq(i,t.createTime.toTimestamp())}}else if(t.isNoDocument())n.noDocument={path:r.path.toArray(),readTime:oX(t.version)};else{if(!t.isUnknownDocument())return E(57904,{document:t});n.unknownDocument={path:r.path.toArray(),version:oX(t.version)}}return n}function oY(e){let t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function oX(e){let t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function oJ(e){let t=new er(e.seconds,e.nanoseconds);return tB.fromTimestamp(t)}function oZ(e,t){let r=(t.baseMutations||[]).map(t=>r4(e.qr,t));for(let e=0;e<t.mutations.length-1;++e){let r=t.mutations[e];e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform&&(r.updateTransforms=t.mutations[e+1].transform.fieldTransforms,t.mutations.splice(e+1,1),++e)}let n=t.mutations.map(t=>r4(e.qr,t)),i=er.fromMillis(t.localWriteTimeMs);return new aW(t.batchId,i,r,n)}function o0(e,t){let r=oJ(t.readTime),n=void 0!==t.lastLimboFreeSnapshotVersion?oJ(t.lastLimboFreeSnapshotVersion):tB.min();return new oQ(void 0!==t.query.structuredPipeline?function(e,t){let r=e.structuredPipeline;return T((r?.pipeline?.stages??[]).length>0,1845),new aL(t,r?.pipeline?.stages.map(o5))}(t.query,e.qr):void 0!==t.query.documents?function(e){let t=e.documents.length;return T(1===t,1966,{count:t}),re(t5(rJ(e.documents[0])))}(t.query):re(r5(t.query)),t.targetId,"TargetPurposeListen",t.lastListenSequenceNumber,r,n,ei.fromBase64String(t.resumeToken))}function o1(e,t){let r,n=oX(t.snapshotVersion),i=oX(t.lastLimboFreeSnapshotVersion);r=t0(t.target)?r8(e.qr,t.target):t1(t.target)?r3(e.qr,t.target):r6(e.qr,t.target).be;let s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:aG(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:r}}function o2(e){let t=r5({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?rn(t,t.limit,"L"):t}function o4(e,t){return new oG(t.largestBatchId,r4(e.qr,t.overlayMutation))}function o3(e,t){let r=t.path.lastSegment();return[e,aY(t.path.popLast()),r]}function o6(e,t,r,n){return{indexId:e,uid:t,sequenceNumber:r,readTime:oX(n.readTime),documentKey:aY(n.documentKey.path),largestBatchId:n.largestBatchId}}function o5(e){switch(e.name){case"collection":return new i3(e.args[0].referenceValue,{});case"collection_group":return new i6(e.args[1].stringValue,{});case"database":return new i5({});case"documents":return new i8(e.args.map(e=>e.referenceValue),{});case"where":return new i9(o8(e.args[0]),{});case"limit":{let t=e.args[0].integerValue??e.args[0].doubleValue;return new i7("number"==typeof t?t:Number(t),{})}case"sort":return new sr(e.args.map(e=>(function(e){let t=e.mapValue?.fields;return new iZ(o8(t.expression),t.direction?.stringValue,"orderingFromProto")})(e)),{});default:throw Error(`Stage type: ${e.name} not supported.`)}}function o8(e){return e.fieldReferenceValue?new i$(iN("_exprFromProto",e.fieldReferenceValue),"_exprFromProto"):e.functionValue?new iW(e.functionValue.name,e.functionValue.args?.map(o8)||[]):iK._fromProto(e)}
6class o9{constructor(e,t,r,n){this.userId=e,this.serializer=t,this.indexManager=r,this.referenceDelegate=n,this.$r={}}static Kr(e,t,r,n){return T(""!==e.uid,64387),new o9(e.isAuthenticated()?e.uid:"",t,r,n)}checkEmpty(e){let t=!0,r=IDBKeyRange.bound([this.userId,-1/0],[this.userId,1/0]);return le(e).jn({index:a3,range:r},(e,r,n)=>{t=!1,n.done()}).next(()=>t)}addMutationBatch(e,t,r,n){let i=oK(e,a8),s=le(e);return s.add({}).next(a=>{T("number"==typeof a,49019);let o=new aW(a,t,r,n),l=function(e,t,r){let n=r.baseMutations.map(t=>r2(e.qr,t)),i=r.mutations.map(t=>r2(e.qr,t));return{userId:t,batchId:r.batchId,localWriteTimeMs:r.localWriteTime.toMillis(),baseMutations:n,mutations:i}}(this.serializer,this.userId,o),u=[],c=new R((e,t)=>S(e.canonicalString(),t.canonicalString()));for(let e of n){var h,d;let t=(h=this.userId,d=e.key.path,[h,aY(d),a]);c=c.add(e.key.path.popLast()),u.push(s.put(l)),u.push(i.put(t,a5))}return c.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.$r[a]=o.keys()}),nG.waitFor(u).next(()=>o)})}lookupMutationBatch(e,t){return le(e).get(t).next(e=>e?(T(e.userId===this.userId,48,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),oZ(this.serializer,e)):null)}Wr(e,t){return this.$r[t]?nG.resolve(this.$r[t]):this.lookupMutationBatch(e,t).next(e=>{if(e){let r=e.keys();return this.$r[t]=r,r}return null})}getNextMutationBatchAfterBatchId(e,t){let r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]),i=null;return le(e).jn({index:a3,range:n},(e,t,n)=>{t.userId===this.userId&&(T(t.batchId>=r,47524,{Qr:r}),i=oZ(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,1/0]),r=-1;return le(e).jn({index:a3,range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,-1],[this.userId,1/0]);return le(e).Kn(a3,t).next(e=>e.map(e=>oZ(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){let r=[this.userId,aY(t.path)],n=IDBKeyRange.lowerBound(r),i=[];return oK(e,a8).jn({range:n},(r,n,s)=>{let[a,o,l]=r,u=aX(o);if(a===this.userId&&t.path.isEqual(u))return le(e).get(l).next(e=>{if(!e)throw E(61480,{Gr:r,batchId:l});T(e.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:e.userId,batchId:l}),i.push(oZ(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new R(S),n=[];return t.forEach(t=>{let i=[this.userId,aY(t.path)],s=IDBKeyRange.lowerBound(i),a=oK(e,a8).jn({range:s},(e,n,i)=>{let[s,a,o]=e,l=aX(a);s===this.userId&&t.path.isEqual(l)?r=r.add(o):i.done()});n.push(a)}),nG.waitFor(n).next(()=>this.zr(e,r))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,n=r.length+1,i=[this.userId,aY(r)],s=IDBKeyRange.lowerBound(i),a=new R(S);return oK(e,a8).jn({range:s},(e,t,i)=>{let[s,o,l]=e,u=aX(o);s===this.userId&&r.isPrefixOf(u)?u.length===n&&(a=a.add(l)):i.done()}).next(()=>this.zr(e,a))}zr(e,t){let r=[],n=[];return t.forEach(t=>{n.push(le(e).get(t).next(e=>{if(null===e)throw E(35274,{batchId:t});T(e.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),r.push(oZ(this.serializer,e))}))}),nG.waitFor(n).next(()=>r)}removeMutationBatch(e,t){return oz(e.kr,this.userId,t).next(r=>(e.addOnCommittedListener(()=>{this.jr(t.batchId)}),nG.forEach(r,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}jr(e){delete this.$r[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>{if(!t)return nG.resolve();let r=IDBKeyRange.lowerBound([this.userId]),n=[];return oK(e,a8).jn({range:r},(e,t,r)=>{if(e[0]===this.userId){let t=aX(e[1]);n.push(t)}else r.done()}).next(()=>{T(0===n.length,56720,{Hr:n.map(e=>e.canonicalString())})})})}containsKey(e,t){return o7(e,this.userId,t)}Jr(e){return oK(e,a1).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function o7(e,t,r){let n=[t,aY(r.path)],i=n[1],s=IDBKeyRange.lowerBound(n),a=!1;return oK(e,a8).jn({range:s,zn:!0},(e,r,n)=>{let[s,o,l]=e;s===t&&o===i&&(a=!0),n.done()}).next(()=>a)}function le(e){return oK(e,a2)}class lt{getBundleMetadata(e,t){return oK(e,ow).get(t).next(e=>{if(e)return{id:e.bundleId,createTime:oJ(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return oK(e,ow).put({bundleId:t.id,createTime:oX(rK(t.createTime)),version:t.version})}getNamedQuery(e,t){return oK(e,ov).get(t).next(e=>
6{if(e)return{name:e.name,query:o2(e.bundledQuery),readTime:oJ(e.readTime)}})}saveNamedQuery(e,t){return oK(e,ov).put({name:t.name,readTime:oX(rK(t.readTime)),bundledQuery:t.bundledQuery})}}class lr{constructor(e,t){this.serializer=e,this.userId=t}static Kr(e,t){return new lr(e,t.uid||"")}getOverlay(e,t){return oK(e,oA).get(o3(this.userId,t)).next(e=>e?o4(this.serializer,e):null)}getOverlays(e,t){let r=rg();return nG.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&r.set(t,e)})).next(()=>r)}getAllOverlays(e,t){let r=rg();return oK(e,oA).jn((e,n)=>{let i=o4(this.serializer,n);i.largestBatchId>t&&r.set(i.getKey(),i)}).next(()=>r)}saveOverlays(e,t,r){let n=[];return r.forEach((r,i)=>{let s=new oG(t,i);n.push(this.Yr(e,s))}),nG.waitFor(n)}removeOverlaysForBatchId(e,t,r){let n=new Set;t.forEach(e=>n.add(aY(e.getCollectionPath())));let i=[];return n.forEach(t=>{let n=IDBKeyRange.bound([this.userId,t,r],[this.userId,t,r+1],!1,!0);i.push(oK(e,oA).Gn(ok,n))}),nG.waitFor(i)}getOverlaysForCollection(e,t,r){let n=rg(),i=aY(t),s=IDBKeyRange.bound([this.userId,i,r],[this.userId,i,1/0],!0);return oK(e,oA).Kn(ok,s).next(e=>{for(let t of e){let e=o4(this.serializer,t);n.set(e.getKey(),e)}return n})}getOverlaysForCollectionGroup(e,t,r,n){let i,s=rg(),a=IDBKeyRange.bound([this.userId,t,r],[this.userId,t,1/0],!0);return oK(e,oA).jn({index:oL,range:a},(e,t,r)=>{let a=o4(this.serializer,t);s.size()<n||a.largestBatchId===i?(s.set(a.getKey(),a),i=a.largestBatchId):r.done()}).next(()=>s)}Yr(e,t){return oK(e,oA).put(function(e,t,r){let[n,i,s]=o3(t,r.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:r.mutation.key.getCollectionGroup(),largestBatchId:r.largestBatchId,overlayMutation:r2(e.qr,r.mutation)}}(this.serializer,this.userId,t))}}class ln{Zr(e){return oK(e,oO)}getSessionToken(e){return this.Zr(e).get("sessionToken").next(e=>{let t=e?.value;return t?ei.fromUint8Array(t):ei.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.Zr(e).put({name:"sessionToken",value:t.toUint8Array()})}}class li{constructor(){}Xr(e,t){this.ei(e,t),t.ti()}ei(e,t){if("nullValue"in e)this.ni(t,5);else if("booleanValue"in e)this.ni(t,10),t.ri(+!!e.booleanValue);else if("integerValue"in e)this.ni(t,15),t.ri(eo(e.integerValue));else if("doubleValue"in e){let r=eo(e.doubleValue);isNaN(r)?this.ni(t,13):(this.ni(t,15),e_(r)?t.ri(0):t.ri(r))}else if("timestampValue"in e){let r=e.timestampValue;this.ni(t,20),"string"==typeof r&&(r=ea(r)),t.ii(`${r.seconds||""}`),t.ri(r.nanos||0)}else if("stringValue"in e)this.si(e.stringValue,t),this._i(t);else if("bytesValue"in e)this.ni(t,30),t.oi(el(e.bytesValue)),this._i(t);else if("referenceValue"in e)this.ai(e.referenceValue,t);else if("geoPointValue"in e){let r=e.geoPointValue;this.ni(t,45),t.ri(r.latitude||0),t.ri(r.longitude||0)}else"mapValue"in e?eQ(e)?this.ni(t,Number.MAX_SAFE_INTEGER):ej(e)?this.ui(e.mapValue,t):(this.ci(e.mapValue,t),this._i(t)):"arrayValue"in e?(this.li(e.arrayValue,t),this._i(t)):E(19022,{Ei:e})}si(e,t){this.ni(t,25),this.hi(e,t)}hi(e,t){t.ii(e)}ci(e,t){let r=e.fields||{};for(let e of(this.ni(t,55),Object.keys(r)))this.si(e,t),this.ei(r[e],t)}ui(e,t){let r=e.fields||{};this.ni(t,53);let n=r[eI].arrayValue?.values?.length||0;this.ni(t,15),t.ri(eo(n)),this.si(eI,t),this.ei(r[eI],t)}li(e,t){let r=e.values||[];for(let e of(this.ni(t,50),r))this.ei(e,t)}ai(e,t){this.ni(t,37),Q.fromName(e).path.forEach(e=>{this.ni(t,60),this.hi(e,t)})}ni(e,t){e.ri(t)}_i(e){e.ri(2)}}function ls(e){return Math.ceil((64-function(e){let t=0;for(let r=0;r<8;++r){let n=function(e){if(0===e)return 8;let t=0;return e>>4||(t+=4,e<<=4),e>>6||(t+=2,e<<=2),e>>7||(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e))/8)}li.Ti=new li;class la{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Pi(e){let t=e[Symbol.iterator](),r=t.next();for(;!r.done;)this.Ri(r.value),r=t.next();this.Ii()}Ai(e){let t=e[Symbol.iterator](),r=t.next();for(;!r.done;)this.Vi(r.value),r=t.next();this.di()}fi(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.Ri(e);else if(e<2048)this.Ri(960|e>>>6),this.Ri(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ri(480|e>>>12),this.Ri(128|63&e>>>6),this.Ri(128|63&e);else{let e=t.codePointAt(0);this.Ri(240|e>>>18),this.Ri(128|63&e>>>12),this.Ri(128|63&e>>>6),this.Ri(128|63&e)}}this.Ii()}mi(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.Vi(e);else if(e<2048)this.Vi(960|e>>>6),this.Vi(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Vi(480|e>>>12),this.Vi(128|63&e>>>6),this.Vi(128|63&e);else{let e=t.codePointAt(0);this.Vi(240|e>>>18),this.Vi(128|63&e>>>12),this.Vi(128|63&e>>>6),this.Vi(128|63&e)}}this.di()}pi(e){let t=this.gi(e),r=ls(t);this.yi(1+r),this.buffer[this.position++]=255&r;for(let e=t.length-r;e<t.length;++e)this.buffer[this.position++]=255&t[e]}wi(e){let t=this.gi(e),r=ls(t);this.yi(1+r),this.buffer[this.position++]=~(255&r);for(let e=t.length-r;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}bi(){this.Si(255),this.Si(255)}Di(){this.xi(255),this.xi(255)}reset(){this.position=0}seed(e){this.yi(e.length),this.buffer.set(e,this.position),this.position+=e.length}Ci(){return this.buffer.slice(0,this.position)}gi(e){let t=function(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),r=!!(128&t[0]);t[0]^=r?255:128;for(let e=1;e<t.length;++e)t[e]^=255*!!r;return t}Ri(e){let t=255&e;0===t?(this.Si(0),this.Si(255)):255===t?(this.Si(255),this.Si(0)):this.Si(t)}Vi(e){let t=255&e;0===t?(this.xi(0),this.xi(255)):255===t?(this.xi(255),this.xi(0)):this.xi(e)}Ii(){this.Si(0),this.Si(1)}di(){this.xi(0),this.xi(1)}Si(e){this.yi(1),this.buffer[this.position++]=e}xi(e){this.yi(1),this.buffer[this.position++]=~e}yi(e){let t=e+this.position;if(t<=this.buffer.length)return;let r=2*this.buffer.length;r<t&&(r=t);let n=new Uint8Array(r);n.set(this.buffer),this.buffer=n}}class lo{constructor(e){this.Fi=e}oi(e){this.Fi.Pi(e)}ii(e){this.Fi.fi(e)}ri(e){this.Fi.pi(e)}ti(){this.Fi.bi()}}class ll{constructor(e){this.Fi=e}oi(e){this.Fi.Ai(e)}ii(e){this.Fi.mi(e)}ri(e){this.Fi.wi(e)}ti(){this.Fi.Di()}}class lu{constructor(){this.Fi=new la,this.ascending=new lo(this.Fi),this.descending=new ll(this.Fi)}seed(e){this.Fi.seed(e)}Oi(e){return 0===e?this.ascending:this.descending}Ci(){return this.Fi.Ci()}reset(){this.Fi.reset()}}class lc{constructor(e,t,r,n){this.Mi=e,this.Ni=t,this.Li=r,this.Bi=n}Ui(){let e=this.Bi.length,t=0===e||255===this.Bi[e-1]?e+1:e,r=new Uint8Array(t);return r.set(this.Bi,0),t!==e?r.set([0],this.Bi.length):++r[r.length-1],new lc(this.Mi,this.Ni,this.Li,r)}ki(e,t,r){return{indexId:this.Mi,uid:e,arrayValue:lf(this.Li),directionalValue:lf(this.Bi),orderedDocumentKey:lf(t),documentKey:r.path.toArray()}}qi(e,t,r){let n=this.ki(e,t,r);return[n.indexId,n.uid,n.arrayValue,n.directionalValue,n.orderedDocumentKey,n.documentKey]}}function lh(e,t){let r=e.Mi-t.Mi;return 0!==r||0!==(r=ld(e.Li,t.Li))||0!==(r=ld(e.Bi,t.Bi))?r:Q.comparator(e.Ni,t.Ni)}function ld(e,t){for(let r=0;r<e.length&&r<t.length;++r){let n=e[r]-t[r];if(0!==n)return n}return e.length-t.length}function lf(e){return(0,o.Ov)()?function(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}(e):e}function lm(e){return"string"!=typeof e?e:function(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}(e)}class lp{constructor(e){for(let t of(this.$i=new R((e,t)=>z.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ki=e.orderBy,this.Wi=[],e.filters))t.isInequality()?this.$i=this.$i.add(t):this.Wi.push(t)}get Qi(){return this.$i.size>1}Gi(e){if(T(e.collectionGroup===this.collectionId,49279),this.Qi)return!1;let t=t$(e);if(void 0!==t&&!this.zi(t))return!1;let r=tj(e),n=new Set,i=0,s=0;for(;i<r.length&&this.zi(r[i]);++i)n=n.add(r[i].fieldPath.canonicalString());if(i===r.length)return!0;
6if(this.$i.size>0){let e=this.$i.getIterator().getNext();if(!n.has(e.field.canonicalString())){let t=r[i];if(!this.ji(e,t)||!this.Hi(this.Ki[s++],t))return!1}++i}for(;i<r.length;++i){let e=r[i];if(s>=this.Ki.length||!this.Hi(this.Ki[s++],e))return!1}return!0}Ji(){if(this.Qi)return null;let e=new R(z.comparator),t=[];for(let r of this.Wi)if(!r.field.isKeyField())if("array-contains"===r.op||"array-contains-any"===r.op)t.push(new tK(r.field,2));else{if(e.has(r.field))continue;e=e.add(r.field),t.push(new tK(r.field,0))}for(let r of this.Ki)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new tK(r.field,+("asc"!==r.dir))));return new tz(tz.UNKNOWN_ID,this.collectionId,t,tG.empty())}zi(e){for(let t of this.Wi)if(this.ji(t,e))return!0;return!1}ji(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;let r="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===r}Hi(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function lg(e){return e instanceof tT}function ly(e){return e instanceof tI&&tD(e)}function lw(e){return lg(e)||ly(e)||function(e){if(e instanceof tI&&tN(e)){for(let t of e.getFilters())if(!lg(t)&&!ly(t))return!1;return!0}return!1}(e)}function lv(e,t){return T(e instanceof tT||e instanceof tI,38388),T(t instanceof tT||t instanceof tI,25473),lx(e instanceof tT?t instanceof tT?tI.create([e,t],"and"):l_(e,t):t instanceof tT?l_(t,e):function(e,t){if(T(e.filters.length>0&&t.filters.length>0,48005),tS(e)&&tS(t))return tA(e,t.getFilters());let r=tN(e)?e:t,n=tN(e)?t:e,i=r.filters.map(e=>lv(e,n));return tI.create(i,"or")}(e,t))}function l_(e,t){if(tS(t))return tA(t,e.getFilters());{let r=t.filters.map(t=>lv(e,t));return tI.create(r,"or")}}function lx(e){if(T(e instanceof tT||e instanceof tI,11850),e instanceof tT)return e;let t=e.getFilters();if(1===t.length)return lx(t[0]);if(tC(e))return e;let r=t.map(e=>lx(e)),n=[];return r.forEach(t=>{t instanceof tT?n.push(t):t instanceof tI&&(t.op===e.op?n.push(...t.filters):n.push(t))}),1===n.length?n[0]:tI.create(n,e.op)}class lE{constructor(){this.Yi=new lb}addToCollectionParentIndex(e,t){return this.Yi.add(t),nG.resolve()}getCollectionParents(e,t){return nG.resolve(this.Yi.getEntries(t))}addFieldIndex(e,t){return nG.resolve()}deleteFieldIndex(e,t){return nG.resolve()}deleteAllFieldIndexes(e){return nG.resolve()}createTargetIndexes(e,t){return nG.resolve()}getDocumentsMatchingTarget(e,t){return nG.resolve(null)}getIndexType(e,t){return nG.resolve(0)}getFieldIndexes(e,t){return nG.resolve([])}getNextCollectionGroupToUpdate(e){return nG.resolve(null)}getMinOffset(e,t){return nG.resolve(tW.min())}getMinOffsetFromCollectionGroup(e,t){return nG.resolve(tW.min())}updateCollectionGroup(e,t,r){return nG.resolve()}updateIndexEntries(e,t){return nG.resolve()}}class lb{constructor(){this.index={}}add(e){let t=e.lastSegment(),r=e.popLast(),n=this.index[t]||new R(B.comparator),i=!n.has(r);return this.index[t]=n.add(r),i}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 R(B.comparator)).toArray()}}let lT="IndexedDbIndexManager",lI=new Uint8Array(0);class lS{constructor(e,t){this.databaseId=t,this.Zi=new lb,this.Xi=new rh(e=>tJ(e),(e,t)=>tZ(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.Zi.has(t)){let r=t.lastSegment(),n=t.popLast();e.addOnCommittedListener(()=>{this.Zi.add(t)});let i={collectionId:r,parent:aY(n)};return oK(e,op).put(i)}return nG.resolve()}getCollectionParents(e,t){let r=[],n=IDBKeyRange.bound([t,""],[t+"\0",""],!1,!0);return oK(e,op).Kn(n).next(e=>{for(let n of e){if(n.collectionId!==t)break;r.push(aX(n.parent))}return r})}addFieldIndex(e,t){let r=oK(e,o_),n={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete n.indexId;let i=r.add(n);if(t.indexState){let r=oK(e,oE);return i.next(e=>{r.put(o6(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let r=oK(e,o_),n=oK(e,oE),i=oK(e,oS);return r.delete(t.indexId).next(()=>n.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){let t=oK(e,o_),r=oK(e,oS),n=oK(e,oE);return t.Gn().next(()=>r.Gn()).next(()=>n.Gn())}createTargetIndexes(e,t){return nG.forEach(this.es(t),t=>this.getIndexType(e,t).next(r=>{if(0===r||1===r){let r=new lp(t).Ji();if(null!=r)return this.addFieldIndex(e,r)}}))}getDocumentsMatchingTarget(e,t){let r=oK(e,oS),n=!0,i=new Map;return nG.forEach(this.es(t),t=>this.ts(e,t).next(e=>{n&&(n=!!e),i.set(t,e)})).next(()=>{if(n){let e=rv(),n=[];return nG.forEach(i,(i,s)=>{w(lT,`Using index id=${i.indexId}|cg=${i.collectionGroup}|f=${i.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")} to execute ${tJ(t)}`);let a=function(e,t){let r=t$(t);if(void 0===r)return null;for(let t of t2(e,r.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),o=function(e,t){let r=new Map;for(let n of tj(t))for(let t of t2(e,n.fieldPath))switch(t.op){case"==":case"in":r.set(n.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return r.set(n.fieldPath.canonicalString(),t.value),Array.from(r.values())}return null}(s,i),l=function(e,t){let r=[],n=!0;for(let i of tj(t)){let t=0===i.kind?t4(e,i.fieldPath,e.startAt):t3(e,i.fieldPath,e.startAt);r.push(t.value),n&&(n=t.inclusive)}return new t_(r,n)}(s,i),u=function(e,t){let r=[],n=!0;for(let i of tj(t)){let t=0===i.kind?t3(e,i.fieldPath,e.endAt):t4(e,i.fieldPath,e.endAt);r.push(t.value),n&&(n=t.inclusive)}return new t_(r,n)}(s,i),c=this.ns(i,s,l),h=this.ns(i,s,u),d=this.rs(i,s,o),f=this.ss(i.indexId,a,c,l.inclusive,h,u.inclusive,d);return nG.forEach(f,i=>r.Qn(i,t.limit).next(t=>{t.forEach(t=>{let r=Q.fromSegments(t.documentKey);e.has(r)||(e=e.add(r),n.push(r))})}))}).next(()=>n)}return nG.resolve(null)})}es(e){let t=this.Xi.get(e);return t||(t=0===e.filters.length?[e]:(function(e){if(0===e.getFilters().length)return[];let t=function e(t){if(T(t instanceof tT||t instanceof tI,34018),t instanceof tT)return t;if(1===t.filters.length)return e(t.filters[0]);let r=t.filters.map(t=>e(t)),n=tI.create(r,t.op);
6return lw(n=lx(n))?n:(T(n instanceof tI,64498),T(tS(n),40251),T(n.filters.length>1,57927),n.filters.reduce((e,t)=>lv(e,t)))}(function e(t){if(T(t instanceof tT||t instanceof tI,20012),t instanceof tT){if(t instanceof tO){let e=t.value.arrayValue?.values?.map(e=>tT.create(t.field,"==",e))||[];return tI.create(e,"or")}return t}let r=t.filters.map(t=>e(t));return tI.create(r,t.op)}(e));return T(lw(t),7391),lg(t)||ly(t)?[t]:t.getFilters()})(tI.create(e.filters,"and")).map(t=>tX(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)),this.Xi.set(e,t)),t}ss(e,t,r,n,i,s,a){let o=(null!=t?t.length:1)*Math.max(r.length,i.length),l=o/(null!=t?t.length:1),u=[];for(let c=0;c<o;++c){let o=t?this._s(t[c/l]):lI,h=this.us(e,o,r[c%l],n),d=this.cs(e,o,i[c%l],s),f=a.map(t=>this.us(e,o,t,!0));u.push(...this.createRange(h,d,f))}return u}us(e,t,r,n){let i=new lc(e,Q.empty(),t,r);return n?i:i.Ui()}cs(e,t,r,n){let i=new lc(e,Q.empty(),t,r);return n?i.Ui():i}ts(e,t){let r=new lp(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(let n of e)r.Gi(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let r=2,n=this.es(t);return nG.forEach(n,t=>this.ts(e,t).next(e=>{e?0!==r&&e.fields.length<function(e){let t=new R(z.comparator),r=!1;for(let n of e.filters)for(let e of n.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?r=!0:t=t.add(e.field));for(let r of e.orderBy)r.field.isKeyField()||(t=t.add(r.field));return t.size+ +!!r}(t)&&(r=1):r=0})).next(()=>null!==t.limit&&n.length>1&&2===r?1:r)}ls(e,t){let r=new lu;for(let n of tj(e)){let e=t.data.field(n.fieldPath);if(null==e)return null;let i=r.Oi(n.kind);li.Ti.Xr(e,i)}return r.Ci()}_s(e){let t=new lu;return li.Ti.Xr(e,t.Oi(0)),t.Ci()}Es(e,t){let r=new lu;return li.Ti.Xr(eO(this.databaseId,t),r.Oi(function(e){let t=tj(e);return 0===t.length?0:t[t.length-1].kind}(e))),r.Ci()}rs(e,t,r){if(null===r)return[];let n=[];n.push(new lu);let i=0;for(let s of tj(e)){let e=r[i++];for(let r of n)if(this.hs(t,s.fieldPath)&&eB(e))n=this.Ts(n,s,e);else{let t=r.Oi(s.kind);li.Ti.Xr(e,t)}}return this.Ps(n)}ns(e,t,r){return this.rs(e,t,r.position)}Ps(e){let t=[];for(let r=0;r<e.length;++r)t[r]=e[r].Ci();return t}Ts(e,t,r){let n=[...e],i=[];for(let e of r.arrayValue.values||[])for(let r of n){let n=new lu;n.seed(r.Ci()),li.Ti.Xr(e,n.Oi(t.kind)),i.push(n)}return i}hs(e,t){return!!e.filters.find(e=>e instanceof tT&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let r=oK(e,o_),n=oK(e,oE);return(t?r.Kn(ox,IDBKeyRange.bound(t,t)):r.Kn()).next(e=>{let t=[];return nG.forEach(e,e=>n.get([e.indexId,this.uid]).next(r=>{t.push(function(e,t){let r=t?new tG(t.sequenceNumber,new tW(oJ(t.readTime),new Q(aX(t.documentKey)),t.largestBatchId)):tG.empty(),n=e.fields.map(([e,t])=>new tK(z.fromServerFormat(e),t));return new tz(e.indexId,e.collectionGroup,n,r)}(e,r))})).next(()=>t)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{let r=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==r?r:S(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,r){let n=oK(e,o_),i=oK(e,oE);return this.Rs(e).next(e=>n.Kn(ox,IDBKeyRange.bound(t,t)).next(t=>nG.forEach(t,t=>i.put(o6(t.indexId,this.uid,e,r)))))}updateIndexEntries(e,t){let r=new Map;return nG.forEach(t,(t,n)=>{let i=r.get(t.collectionGroup);return(i?nG.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(r.set(t.collectionGroup,i),nG.forEach(i,r=>this.Is(e,t,r).next(t=>{let i=this.As(n,r);return t.isEqual(i)?nG.resolve():this.Vs(e,n,r,t,i)}))))})}ds(e,t,r,n){return oK(e,oS).put(n.ki(this.uid,this.Es(r,t.key),t.key))}fs(e,t,r,n){return oK(e,oS).delete(n.qi(this.uid,this.Es(r,t.key),t.key))}Is(e,t,r){let n=oK(e,oS),i=new R(lh);return n.jn({index:oD,range:IDBKeyRange.only([r.indexId,this.uid,lf(this.Es(r,t))])},(e,n)=>{i=i.add(new lc(r.indexId,t,lm(n.arrayValue),lm(n.directionalValue)))}).next(()=>i)}As(e,t){let r=new R(lh),n=this.ls(t,e);if(null==n)return r;let i=t$(t);if(null!=i){let s=e.data.field(i.fieldPath);
6if(eB(s))for(let i of s.arrayValue.values||[])r=r.add(new lc(t.indexId,e.key,this._s(i),n))}else r=r.add(new lc(t.indexId,e.key,lI,n));return r}Vs(e,t,r,n,i){w(lT,"Updating index entries for document '%s'",t.key);let s=[];return function(e,t,r,n,i){let s=e.getIterator(),a=t.getIterator(),o=P(s),l=P(a);for(;o||l;){let e=!1,t=!1;if(o&&l){let n=r(o,l);n<0?t=!0:n>0&&(e=!0)}else null!=o?t=!0:e=!0;e?(n(l),l=P(a)):t?(i(o),o=P(s)):(o=P(s),l=P(a))}}(n,i,lh,n=>{s.push(this.ds(e,t,r,n))},n=>{s.push(this.fs(e,t,r,n))}),nG.waitFor(s)}Rs(e){let t=1;return oK(e,oE).jn({index:oT,reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,r,n)=>{n.done(),t=r.sequenceNumber+1}).next(()=>t)}createRange(e,t,r){r=r.sort((e,t)=>lh(e,t)).filter((e,t,r)=>!t||0!==lh(e,r[t-1]));let n=[];for(let i of(n.push(e),r)){let r=lh(i,e),s=lh(i,t);if(0===r)n[0]=e.Ui();else if(r>0&&s<0)n.push(i),n.push(i.Ui());else if(s>0)break}n.push(t);let i=[];for(let e=0;e<n.length;e+=2){if(this.ps(n[e],n[e+1]))return[];let t=n[e].qi(this.uid,lI,Q.empty()),r=n[e+1].qi(this.uid,lI,Q.empty());i.push(IDBKeyRange.bound(t,r))}return i}ps(e,t){return lh(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(lN)}getMinOffset(e,t){return nG.mapArray(this.es(t),t=>this.ts(e,t).next(e=>e||E(44426))).next(lN)}}function lN(e){T(0!==e.length,28825);let t=e[0].indexState.offset,r=t.largestBatchId;for(let n=1;n<e.length;n++){let i=e[n].indexState.offset;0>tH(i,t)&&(t=i),r<i.largestBatchId&&(r=i.largestBatchId)}return new tW(t.readTime,t.documentKey,r)}class lD{constructor(e){this.gs=e}next(){return this.gs+=2,this.gs}static ys(){return new lD(0)}static ws(){return new lD(-1)}}class lC{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.bs(e).next(t=>{let r=new lD(t.highestTargetId);return t.highestTargetId=r.next(),this.vs(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.bs(e).next(e=>tB.fromTimestamp(new er(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.bs(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(e,t,r){return this.bs(e).next(n=>(n.highestListenSequenceNumber=t,r&&(n.lastRemoteSnapshotVersion=r.toTimestamp()),t>n.highestListenSequenceNumber&&(n.highestListenSequenceNumber=t),this.vs(e,n)))}addTargetData(e,t){return this.Ss(e,t).next(()=>this.bs(e).next(r=>(r.targetCount+=1,this.Ds(t,r),this.vs(e,r))))}updateTargetData(e,t){return this.Ss(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>oK(e,oa).delete(t.targetId)).next(()=>this.bs(e)).next(t=>(T(t.targetCount>0,8065),t.targetCount-=1,this.vs(e,t)))}removeTargets(e,t,r){let n=0,i=[];return oK(e,oa).jn((s,a)=>{let o=o0(this.serializer,a);o.sequenceNumber<=t&&null===r.get(o.targetId)&&(n++,i.push(this.removeTargetData(e,o)))}).next(()=>nG.waitFor(i)).next(()=>n)}forEachTarget(e,t){return oK(e,oa).jn((e,r)=>{t(o0(this.serializer,r))})}bs(e){return oK(e,om).get(of).next(e=>(T(null!==e,2888),e))}vs(e,t){return oK(e,om).put(of,t)}Ss(e,t){return oK(e,oa).put(o1(this.serializer,t))}Ds(e,t){let r=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,r=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,r=!0),r}getTargetCount(e){return this.bs(e).next(e=>e.targetCount)}getTargetData(e,t){let r=aG(t),n=IDBKeyRange.bound([r,-1/0],[r,1/0]),i=null;return oK(e,oa).jn({range:n,index:oo},(e,r,n)=>{let s=o0(this.serializer,r);aQ(t,s.target)&&(i=s,n.done())}).next(()=>i)}addMatchingKeys(e,t,r){let n=[],i=lA(e);return t.forEach(t=>{let s=aY(t.path);n.push(i.put({targetId:r,path:s})),n.push(this.referenceDelegate.addReference(e,r,t))}),nG.waitFor(n)}removeMatchingKeys(e,t,r){let n=lA(e);return nG.forEach(t,t=>{let i=aY(t.path);return nG.waitFor([n.delete([r,i]),this.referenceDelegate.removeReference(e,r,t)])})}removeMatchingKeysForTargetId(e,t){let r=lA(e),n=IDBKeyRange.bound([t],[t+1],!1,!0);return r.delete(n)}getMatchingKeysForTargetId(e,t){let r=IDBKeyRange.bound([t],[t+1],!1,!0),n=lA(e),i=rv();return n.jn({range:r,zn:!0},(e,t,r)=>{let n=new Q(aX(e[1]));i=i.add(n)}).next(()=>i)}containsKey(e,t){let r=aY(t.path),n=IDBKeyRange.bound([r],[r+"\0"],!1,!0),i=0;return lA(e).jn({index:oh,zn:!0,range:n},([e,t],r,n)=>{0!==e&&(i++,n.done())}).next(()=>i>0)}ge(e,t){return oK(e,oa).get(t).next(e=>e?o0(this.serializer,e):null)}}function lA(e){return oK(e,ou)}class lV{constructor(e,t){this.db=e,this.garbageCollector=new n9(this,t)}rr(e){let t=this.xs(e);return this.db.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}xs(e){let t=0;return this.ir(e,e=>{t++}).next(()=>t)}
6forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}ir(e,t){return this.Cs(e,(e,r)=>t(r))}addReference(e,t,r){return lk(e,r)}removeReference(e,t,r){return lk(e,r)}removeTargets(e,t,r){return this.db.getTargetCache().removeTargets(e,t,r)}markPotentiallyOrphaned(e,t){return lk(e,t)}Fs(e,t){let r;return r=!1,oK(e,a1).Hn(n=>o7(e,n,t).next(e=>(e&&(r=!0),nG.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(e,t){let r=this.db.getRemoteDocumentCache().newChangeBuffer(),n=[],i=0;return this.Cs(e,(s,a)=>{if(a<=t){let t=this.Fs(e,s).next(t=>{if(!t)return i++,r.getEntry(e,s).next(()=>(r.removeEntry(s,tB.min()),lA(e).delete([0,aY(s.path)])))});n.push(t)}}).next(()=>nG.waitFor(n)).next(()=>r.apply(e)).next(()=>i)}removeTarget(e,t){let r=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,r)}updateLimboDocument(e,t){return lk(e,t)}Cs(e,t){let r=lA(e),n,i=nz.yn;return r.jn({index:oh},([e,r],{path:s,sequenceNumber:a})=>{0===e?(i!==nz.yn&&t(new Q(aX(n)),i),i=a,n=s):i=nz.yn}).next(()=>{i!==nz.yn&&t(new Q(aX(n)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function lk(e,t){var r;return lA(e).put((r=e.currentSequenceNumber,{targetId:0,path:aY(t.path),sequenceNumber:r}))}function lR(e,t){let r=t;for(let t of e.stages)r=function(e,t,r){if(t instanceof i3)return r.filter(e=>e.isFoundDocument()&&`/${e.key.getCollectionPath().canonicalString()}`===t.Er);if(t instanceof i9)return r.filter(r=>{let n=so(su(t.condition).evaluate(e,r));return void 0!==n&&eA(n,eN)});if(t instanceof i6)return r.filter(e=>e.isFoundDocument()&&e.key.getCollectionPath().lastSegment()===t.collectionId);if(t instanceof i5)return r.filter(e=>e.isFoundDocument());if(t instanceof i8)return r.filter(e=>e.isFoundDocument()&&t.Tr.has(e.key.path.toStringWithLeadingSlash()));if(t instanceof i7)return r.slice(0,t.limit);if(t instanceof sr){let n=t.orderings.map(e=>({Os:su(e.expr),direction:e.direction}));return[...r].sort((t,r)=>{for(let{Os:i,direction:s}of n){let n=ek(so(i.evaluate(e,t))??eS,so(i.evaluate(e,r))??eS);if(0!==n)return"ascending"===s?n:-n}return 0})}throw Error(`Unknown stage: ${t._name}`)}({serializer:e.serializer,serverTimestampBehavior:e.listenOptions?.serverTimestampBehavior},t,r);return r}function lL(e,t){return lR(e,[t]).length>0}function lP(e,t){return az(e)?lL(e,t):ro(e,t)}function lO(e){let t=function(e){for(let t=e.stages.length-1;t>=0;t--){let r=e.stages[t];if(r instanceof sr)return r.orderings}throw Error("Pipeline must contain at least one Sort stage")}(e);return(r,n)=>{for(let i of t){let t=ek(so(su(i.expr).evaluate({serializer:e.serializer},r))||eS,so(su(i.expr).evaluate({serializer:e.serializer},n))||eS);if(0!==t)return"ascending"===i.direction?t:-t}return 0}}function lF(e){for(let t=e.stages.length-1;t>=0;t--){let r=e.stages[t];if(r instanceof i7)return{limit:r.limit}}}class lM{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,tq.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let r=this.changes.get(t);return void 0!==r?nG.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class lU{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,r){return lq(e).put(r)}removeEntry(e,t,r){return lq(e).delete(function(e,t){let r=e.path.toArray();return[r.slice(0,r.length-2),r[r.length-2],oY(t),r[r.length-1]]}(t,r))}updateMetadata(e,t){return this.getMetadata(e).next(r=>(r.byteSize+=t,this.Ms(e,r)))}getEntry(e,t){let r=tq.newInvalidDocument(t);return lq(e).jn({index:oe,range:IDBKeyRange.only(lz(t))},(e,n)=>{r=this.Ns(t,n)}).next(()=>r)}Ls(e,t){let r={size:0,document:tq.newInvalidDocument(t)};return lq(e).jn({index:oe,range:IDBKeyRange.only(lz(t))},(e,n)=>{r={document:this.Ns(t,n),size:o$(n)}}).next(()=>r)}getEntries(e,t){let r=rd;return this.Bs(e,t,(e,t)=>{let n=this.Ns(e,t);r=r.insert(e,n)}).next(()=>r)}getAllEntries(e){let t=rd;return lq(e).jn((e,r)=>{let n=this.Ns(Q.fromSegments(r.prefixPath.concat(r.collectionGroup,r.documentId)),r);t=t.insert(n.key,n)}).next(()=>t)}Us(e,t){let r=rd,n=new A(Q.comparator);return this.Bs(e,t,(e,t)=>{let i=this.Ns(e,t);r=r.insert(e,i),n=n.insert(e,o$(t))}).next(()=>({documents:r,ks:n}))}Bs(e,t,r){if(t.isEmpty())return nG.resolve();let n=new R(lj);
6t.forEach(e=>n=n.add(e));let i=IDBKeyRange.bound(lz(n.first()),lz(n.last())),s=n.getIterator(),a=s.getNext();return lq(e).jn({index:oe,range:i},(e,t,n)=>{let i=Q.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&0>lj(a,i);)r(a,null),a=s.getNext();a&&a.isEqual(i)&&(r(a,t),a=s.hasNext()?s.getNext():null),a?n.$n(lz(a)):n.done()}).next(()=>{for(;a;)r(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,t,r,n,i){let s=az(t)?B.fromString(aO(t)):t.path,a=[s.popLast().toArray(),s.lastSegment(),oY(r.readTime),r.documentKey.path.isEmpty()?"":r.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return lq(e).Kn(IDBKeyRange.bound(a,o,!0)).next(e=>{i?.incrementDocumentReadCount(e.length);let r=rd;for(let i of e){let e=this.Ns(Q.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(lP(t,e)||n.has(e.key))&&(r=r.insert(e.key,e))}return r})}getAllFromCollectionGroup(e,t,r,n){let i=rd,s=l$(t,r),a=l$(t,tW.max());return lq(e).jn({index:or,range:IDBKeyRange.bound(s,a,!0)},(e,t,r)=>{let s=this.Ns(Q.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(i=i.insert(s.key,s)).size===n&&r.done()}).next(()=>i)}newChangeBuffer(e){return new lB(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return oK(e,oi).get(os).next(e=>(T(!!e,20021),e))}Ms(e,t){return oK(e,oi).put(os,t)}Ns(e,t){if(t){let e=function(e,t){let r;if(t.document)r=function(e,t,r){let n=rY(e,t.name),i=rK(t.updateTime),s=t.createTime?rK(t.createTime):tB.min(),a=new eX({mapValue:{fields:t.fields}}),o=tq.newFoundDocument(n,i,s,a);return r&&o.setHasCommittedMutations(),r?o.setHasCommittedMutations():o}(e.qr,t.document,!!t.hasCommittedMutations);else if(t.noDocument){let e=Q.fromSegments(t.noDocument.path),n=oJ(t.noDocument.readTime);r=tq.newNoDocument(e,n),t.hasCommittedMutations&&r.setHasCommittedMutations()}else{if(!t.unknownDocument)return E(56709);{let e=Q.fromSegments(t.unknownDocument.path),n=oJ(t.unknownDocument.version);r=tq.newUnknownDocument(e,n)}}return t.readTime&&r.setReadTime(function(e){let t=new er(e[0],e[1]);return tB.fromTimestamp(t)}(t.readTime)),r}(this.serializer,t);if(!(e.isNoDocument()&&e.version.isEqual(tB.min())))return e}return tq.newInvalidDocument(e)}}class lB extends lM{constructor(e,t){super(),this.qs=e,this.trackRemovals=t,this.$s=new rh(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){let t=[],r=0,n=new R((e,t)=>S(e.canonicalString(),t.canonicalString()));
6return this.changes.forEach((i,s)=>{let a=this.$s.get(i);if(t.push(this.qs.removeEntry(e,i,a.readTime)),s.isValidDocument()){let o=oH(this.qs.serializer,s);n=n.add(i.path.popLast());let l=o$(o);r+=l-a.size,t.push(this.qs.addEntry(e,i,o))}else if(r-=a.size,this.trackRemovals){let r=oH(this.qs.serializer,s.convertToNoDocument(tB.min()));t.push(this.qs.addEntry(e,i,r))}}),n.forEach(r=>{t.push(this.qs.indexManager.addToCollectionParentIndex(e,r))}),t.push(this.qs.updateMetadata(e,r)),nG.waitFor(t)}getFromCache(e,t){return this.qs.Ls(e,t).next(e=>(this.$s.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.qs.Us(e,t).next(({documents:e,ks:t})=>(t.forEach((t,r)=>{this.$s.set(t,{size:r,readTime:e.get(t).readTime})}),e))}}function lq(e){return oK(e,a9)}function lz(e){let t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function l$(e,t){let r=t.documentKey.path.toArray();return[e,oY(t.readTime),r.slice(0,r.length-2),r.length>0?r[r.length-1]:""]}function lj(e,t){let r=e.path.toArray(),n=t.path.toArray(),i=0;for(let e=0;e<r.length-2&&e<n.length-2;++e)if(i=S(r[e],n[e]))return i;return(i=S(r.length,n.length))||(i=S(r[r.length-2],n[n.length-2]))||S(r[r.length-1],n[n.length-1])}class lK{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class lG{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&&th(r.mutation,e,$.empty(),er.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=rm();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 i=rd,s=rg(),a=rg();return t.forEach((e,t)=>{let a=r.get(t.key);n.has(t.key)&&(void 0===a||a.mutation instanceof tm)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),th(a.mutation,t,a.mutation.getFieldMask(),er.now())):s.set(t.key,$.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>a.set(e,new lK(t,s.get(e)??null))),a))}recalculateAndSaveOverlays(e,t){let r=rg(),n=new A((e,t)=>
6e-t),i=rv();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let i of e)i.keys().forEach(e=>{let s=t.get(e);if(null===s)return;let a=r.get(e)||$.empty();a=i.applyToLocalView(s,a),r.set(e,a);let o=(n.get(i.batchId)||rv()).add(e);n=n.insert(i.batchId,o)})}).next(()=>{let s=[],a=n.getReverseIterator();for(;a.hasNext();){let n=a.getNext(),o=n.key,l=n.value,u=rg();l.forEach(e=>{if(!i.has(e)){let n=tc(t.get(e),r.get(e));null!==n&&u.set(e,n),i=i.add(e)}}),s.push(this.documentOverlayCache.saveOverlays(e,o,u))}return nG.waitFor(s)}).next(()=>r)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,r,n){return az(t)?this.getDocumentsMatchingPipeline(e,t,r,n):Q.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(i=>{let s=n-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,r.largestBatchId,n-i.size):nG.resolve(rg()),a=-1,o=i;return s.next(t=>nG.forEach(t,(t,r)=>(a<r.largestBatchId&&(a=r.largestBatchId),i.get(t)?nG.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,i)).next(()=>this.computeViews(e,o,t,rv())).next(e=>({batchId:a,changes:rp(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new Q(t)).next(e=>{let t=rm();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,r,n){let i=t.collectionGroup,s=rm();return this.indexManager.getCollectionParents(e,i).next(a=>nG.forEach(a,a=>{let o=new t6(a.child(i),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)=>{s=s.insert(e,t)})})}).next(()=>s))}getDocumentsMatchingCollectionQuery(e,t,r,n){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,r.largestBatchId).next(s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,i,n))).next(e=>this.retrieveMatchingLocalDocuments(i,e,e=>ro(t,e)))}getDocumentsMatchingPipeline(e,t,r,n){if("collection_group"===aP(t)){let i=aF(t),s=rm();return this.indexManager.getCollectionParents(e,i).next(a=>nG.forEach(a,a=>{let o=function(e,t){let r=e.stages.map(e=>e instanceof i6?new i3(t.canonicalString(),{}):e);return new aL(e.serializer,r)}(t,a.child(i));return this.getDocumentsMatchingPipeline(e,o,r,n).next(e=>{e.forEach((e,t)=>{s=s.insert(e,t)})})}).next(()=>s))}{let i;return this.getOverlaysForPipeline(e,t,r.largestBatchId).next(s=>{switch(i=s,aP(t)){case"collection":return this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,i,n);case"documents":let a=rv();for(let e of aM(t))a=a.add(Q.fromPath(e));return this.remoteDocumentCache.getEntries(e,a);case"database":return this.remoteDocumentCache.getAllEntries(e);default:throw new F("invalid-argument",`Invalid pipeline source to execute offline: ${aq(t)}`)}}).next(e=>this.retrieveMatchingLocalDocuments(i,e,e=>lL(t,e)))}}retrieveMatchingLocalDocuments(e,t,r){e.forEach((e,r)=>{let n=r.getKey();null===t.get(n)&&(t=t.insert(n,tq.newInvalidDocument(n)))});let n=rm();return t.forEach((t,i)=>{let s=e.get(t);void 0!==s&&th(s.mutation,i,$.empty(),er.now()),r(i)&&(n=n.insert(t,i))}),n}getOverlaysForPipeline(e,t,r){switch(aP(t)){case"collection":return this.documentOverlayCache.getOverlaysForCollection(e,B.fromString(aO(t)),r);case"collection_group":throw new F("invalid-argument",`Unexpected collection group pipeline: ${aq(t)}`);case"documents":return this.documentOverlayCache.getOverlays(e,aM(t).map(e=>Q.fromPath(e)));case"database":return this.documentOverlayCache.getAllOverlays(e,r);default:throw new F("invalid-argument",`Failed to get overlays for pipeline: ${aq(t)}`)}}}
6class lQ{constructor(e){this.serializer=e,this.Ks=new Map,this.Ws=new Map}getBundleMetadata(e,t){return nG.resolve(this.Ks.get(t))}saveBundleMetadata(e,t){return this.Ks.set(t.id,{id:t.id,version:t.version,createTime:rK(t.createTime)}),nG.resolve()}getNamedQuery(e,t){return nG.resolve(this.Ws.get(t))}saveNamedQuery(e,t){return this.Ws.set(t.name,{name:t.name,query:o2(t.bundledQuery),readTime:rK(t.readTime)}),nG.resolve()}}class lW{constructor(){this.overlays=new A(Q.comparator),this.Qs=new Map}getOverlay(e,t){return nG.resolve(this.overlays.get(t))}getOverlays(e,t){let r=rg();return nG.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)}),nG.resolve(r)}saveOverlays(e,t,r){return r.forEach((r,n)=>{this.Yr(e,t,n)}),nG.resolve()}removeOverlaysForBatchId(e,t,r){let n=this.Qs.get(r);return void 0!==n&&(n.forEach(e=>this.overlays=this.overlays.remove(e)),this.Qs.delete(r)),nG.resolve()}getOverlaysForCollection(e,t,r){let n=rg(),i=t.length+1,s=new Q(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){let e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>r&&n.set(e.getKey(),e)}return nG.resolve(n)}getOverlaysForCollectionGroup(e,t,r,n){let i=new A((e,t)=>e-t),s=this.overlays.getIterator();for(;s.hasNext();){let e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>r){let t=i.get(e.largestBatchId);null===t&&(t=rg(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=rg(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=n)););return nG.resolve(a)}Yr(e,t,r){let n=this.overlays.get(r.key);if(null!==n){let e=this.Qs.get(n.largestBatchId).delete(r.key);this.Qs.set(n.largestBatchId,e)}this.overlays=this.overlays.insert(r.key,new oG(t,r));let i=this.Qs.get(t);void 0===i&&(i=rv(),this.Qs.set(t,i)),this.Qs.set(t,i.add(r.key))}}class lH{constructor(){this.sessionToken=ei.EMPTY_BYTE_STRING}getSessionToken(e){return nG.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,nG.resolve()}}class lY{constructor(){this.Gs=new R(lX.zs),this.js=new R(lX.Hs)}isEmpty(){return this.Gs.isEmpty()}addReference(e,t){let r=new lX(e,t);this.Gs=this.Gs.add(r),this.js=this.js.add(r)}Js(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ys(new lX(e,t))}Zs(e,t){e.forEach(e=>this.removeReference(e,t))}Xs(e){let t=new Q(new B([])),r=new lX(t,e),n=new lX(t,e+1),i=[];return this.js.forEachInRange([r,n],e=>{this.Ys(e),i.push(e.key)}),i}e_(){this.Gs.forEach(e=>this.Ys(e))}Ys(e){this.Gs=this.Gs.delete(e),this.js=this.js.delete(e)}t_(e){let t=new Q(new B([])),r=new lX(t,e),n=new lX(t,e+1),i=rv();return this.js.forEachInRange([r,n],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new lX(e,0),r=this.Gs.firstAfterOrEqual(t);return null!==r&&e.isEqual(r.key)}}class lX{constructor(e,t){this.key=e,this.n_=t}static zs(e,t){return Q.comparator(e.key,t.key)||S(e.n_,t.n_)}static Hs(e,t){return S(e.n_,t.n_)||Q.comparator(e.key,t.key)}}class lJ{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Qr=1,this.r_=new R(lX.zs)}checkEmpty(e){return nG.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,r,n){let i=this.Qr;this.Qr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new aW(i,t,r,n);for(let t of(this.mutationQueue.push(s),n))this.r_=this.r_.add(new lX(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return nG.resolve(s)}lookupMutationBatch(e,t){return nG.resolve(this.i_(t))}getNextMutationBatchAfterBatchId(e,t){let r=this.s_(t+1),n=r<0?0:r;return nG.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return nG.resolve(0===this.mutationQueue.length?-1:this.Qr-1)}getAllMutationBatches(e){return nG.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let r=new lX(t,0),n=new lX(t,1/0),i=[];return this.r_.forEachInRange([r,n],e=>{let t=this.i_(e.n_);i.push(t)}),nG.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new R(S);
6return t.forEach(e=>{let t=new lX(e,0),n=new lX(e,1/0);this.r_.forEachInRange([t,n],e=>{r=r.add(e.n_)})}),nG.resolve(this.__(r))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,n=r.length+1,i=r;Q.isDocumentKey(i)||(i=i.child(""));let s=new lX(new Q(i),0),a=new R(S);return this.r_.forEachWhile(e=>{let t=e.key.path;return!!r.isPrefixOf(t)&&(t.length===n&&(a=a.add(e.n_)),!0)},s),nG.resolve(this.__(a))}__(e){let t=[];return e.forEach(e=>{let r=this.i_(e);null!==r&&t.push(r)}),t}removeMutationBatch(e,t){T(0===this.o_(t.batchId,"removed"),55003),this.mutationQueue.shift();let r=this.r_;return nG.forEach(t.mutations,n=>{let i=new lX(n.key,t.batchId);return r=r.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,n.key)}).next(()=>{this.r_=r})}jr(e){}containsKey(e,t){let r=new lX(t,0),n=this.r_.firstAfterOrEqual(r);return nG.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,nG.resolve()}o_(e,t){return this.s_(e)}s_(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}i_(e){let t=this.s_(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class lZ{constructor(e){this.a_=e,this.docs=new A(Q.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let r=t.key,n=this.docs.get(r),i=n?n.size:0,s=this.a_(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let r=this.docs.get(t);return nG.resolve(r?r.document.mutableCopy():tq.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():tq.newInvalidDocument(e))}),nG.resolve(r)}getAllEntries(e){let t=rd;return this.docs.forEach((e,r)=>{t=t.insert(e,r.document)}),nG.resolve(t)}getDocumentsMatchingQuery(e,t,r,n){let i,s;az(t)?(i=B.fromString(aO(t)),s=e=>lL(t,e)):(i=t.path,s=e=>ro(t,e));let a=rd,o=new Q(i.child("__id-9223372036854775808__")),l=this.docs.getIteratorFrom(o);for(;l.hasNext();){let{key:e,value:{document:t}}=l.getNext();if(!i.isPrefixOf(e.path))break;e.path.length>i.length+1||0>=tH(tQ(t),r)||(n.has(t.key)||s(t))&&(a=a.insert(t.key,t.mutableCopy()))}return nG.resolve(a)}getAllFromCollectionGroup(e,t,r,n){E(9500)}u_(e,t){return nG.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new l0(this)}getSize(e){return nG.resolve(this.size)}}class l0 extends lM{constructor(e){super(),this.qs=e}applyChanges(e){let t=[];
vendor: 4,734 bytes, line 6
6return this.changes.forEach((r,n)=>{n.isValidDocument()?t.push(this.qs.addEntry(e,n)):this.qs.removeEntry(r)}),nG.waitFor(t)}getFromCache(e,t){return this.qs.getEntry(e,t)}getAllFromCache(e,t){return this.qs.getEntries(e,t)}}class l1{constructor(e){this.persistence=e,this.c_=new rh(e=>aG(e),aQ),this.lastRemoteSnapshotVersion=tB.min(),this.highestTargetId=0,this.l_=0,this.E_=new lY,this.targetCount=0,this.h_=lD.ys()}forEachTarget(e,t){return this.c_.forEach((e,r)=>t(r)),nG.resolve()}getLastRemoteSnapshotVersion(e){return nG.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return nG.resolve(this.l_)}allocateTargetId(e){return this.highestTargetId=this.h_.next(),nG.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.l_&&(this.l_=t),nG.resolve()}Ss(e){this.c_.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.h_=new lD(t),this.highestTargetId=t),e.sequenceNumber>this.l_&&(this.l_=e.sequenceNumber)}addTargetData(e,t){return this.Ss(t),this.targetCount+=1,nG.resolve()}updateTargetData(e,t){return this.Ss(t),nG.resolve()}removeTargetData(e,t){return this.c_.delete(t.target),this.E_.Xs(t.targetId),this.targetCount-=1,nG.resolve()}removeTargets(e,t,r){let n=0,i=[];return this.c_.forEach((s,a)=>{a.sequenceNumber<=t&&null===r.get(a.targetId)&&(this.c_.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),n++)}),nG.waitFor(i).next(()=>n)}getTargetCount(e){return nG.resolve(this.targetCount)}getTargetData(e,t){let r=this.c_.get(t)||null;return nG.resolve(r)}addMatchingKeys(e,t,r){return this.E_.Js(t,r),nG.resolve()}removeMatchingKeys(e,t,r){this.E_.Zs(t,r);let n=this.persistence.referenceDelegate,i=[];return n&&t.forEach(t=>{i.push(n.markPotentiallyOrphaned(e,t))}),nG.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.E_.Xs(t),nG.resolve()}getMatchingKeysForTargetId(e,t){let r=this.E_.t_(t);return nG.resolve(r)}containsKey(e,t){return nG.resolve(this.E_.containsKey(t))}}class l2{constructor(e,t){this.T_={},this.overlays={},this.P_=new nz(0),this.R_=!1,this.R_=!0,this.I_=new lH,this.referenceDelegate=e(this),this.A_=new l1(this),this.indexManager=new lE,this.remoteDocumentCache=new lZ(e=>this.referenceDelegate.V_(e)),this.serializer=new oW(t),this.d_=new lQ(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.R_=!1,Promise.resolve()}get started(){return this.R_}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new lW,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this.T_[e.toKey()];return r||(r=new lJ(t,this.referenceDelegate),this.T_[e.toKey()]=r),r}getGlobalsCache(){return this.I_}getTargetCache(){return this.A_}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.d_}runTransaction(e,t,r){w("MemoryPersistence","Starting transaction:",e);let n=new l4(this.P_.next());return this.referenceDelegate.f_(),r(n).next(e=>this.referenceDelegate.m_(n).next(()=>e)).toPromise().then(e=>(n.raiseOnCommittedEvent(),e))}p_(e,t){return nG.or(Object.values(this.T_).map(r=>()=>r.containsKey(e,t)))}}class l4 extends nj{constructor(e){super(),this.currentSequenceNumber=e}}class l3{constructor(e){this.persistence=e,this.g_=new lY,this.y_=null}static w_(e){return new l3(e)}get b_(){if(this.y_)return this.y_;throw E(60996)}addReference(e,t,r){return this.g_.addReference(r,t),this.b_.delete(r.toString()),nG.resolve()}removeReference(e,t,r){return this.g_.removeReference(r,t),this.b_.add(r.toString()),nG.resolve()}markPotentiallyOrphaned(e,t){return this.b_.add(t.toString()),nG.resolve()}removeTarget(e,t){this.g_.Xs(t.targetId).forEach(e=>this.b_.add(e.toString()));let r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.b_.add(e.toString()))}).next(()=>r.removeTargetData(e,t))}f_(){this.y_=new Set}m_(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return nG.forEach(this.b_,r=>{let n=Q.fromPath(r);return this.v_(e,n).next(e=>{e||t.removeEntry(n,tB.min())})}).next(()=>(this.y_=null,t.apply(e)))}updateLimboDocument(e,t){return this.v_(e,t).next(e=>{e?this.b_.delete(t.toString()):this.b_.add(t.toString())})}V_(e){return 0}v_(e,t){return nG.or([()=>nG.resolve(this.g_.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.p_(e,t)])}}class l6{constructor(e,t){this.persistence=e,this.S_=new rh(e=>aY(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=new n9(this,t)}static w_(e,t){return new l6(e,t)}f_(){}m_(e){return nG.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEac
6hTarget(e,t)}rr(e){let t=this.xs(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}xs(e){let t=0;return this.ir(e,e=>{t++}).next(()=>t)}ir(e,t){return nG.forEach(this.S_,(r,n)=>this.Fs(e,r,n).next(e=>e?nG.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(),i=n.newChangeBuffer();return n.u_(e,n=>this.Fs(e,n,t).next(e=>{e||(r++,i.removeEntry(n,tB.min()))})).next(()=>i.apply(e)).next(()=>r)}markPotentiallyOrphaned(e,t){return this.S_.set(t,e.currentSequenceNumber),nG.resolve()}removeTarget(e,t){let r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.S_.set(r,e.currentSequenceNumber),nG.resolve()}removeReference(e,t,r){return this.S_.set(r,e.currentSequenceNumber),nG.resolve()}updateLimboDocument(e,t){return this.S_.set(t,e.currentSequenceNumber),nG.resolve()}V_(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(eC(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let r=em(t);return r?16+e(r):16;case 5:return 2*t.stringValue.length;case 6:return el(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 i;return n=t.mapValue,i=0,K(n.fields,(t,r)=>{i+=t.length+e(r)}),i;default:throw E(13486,{value:t})}}(e.data.value)),t}Fs(e,t,r){return nG.or([()=>this.persistence.p_(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.S_.get(t);return nG.resolve(void 0!==e&&e>r)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class l5{constructor(e){this.serializer=e}Mn(e,t,r,n){let i=new nW("createOrUpgrade",t);r<1&&n>=1&&(e.createObjectStore(aZ),e.createObjectStore(a1,{keyPath:"userId"}),e.createObjectStore(a2,{keyPath:a4,autoIncrement:!0}).createIndex(a3,a6,{unique:!0}),e.createObjectStore(a8),l8(e),e.createObjectStore(aJ));let s=nG.resolve();return r<3&&n>=3&&(0!==r&&(e.deleteObjectStore(ou),e.deleteObjectStore(oa),e.deleteObjectStore(om),l8(e)),s=s.next(()=>(function(e){let t=e.store(om),r={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:tB.min().toTimestamp(),targetCount:0};return t.put(of,r)})(i))),r<4&&n>=4&&(0!==r&&(s=s.next(()=>i.store(a2).Kn().next(t=>{e.deleteObjectStore(a2),e.createObjectStore(a2,{keyPath:a4,autoIncrement:!0}).createIndex(a3,a6,{unique:!0});let r=i.store(a2),n=t.map(e=>r.put(e));return nG.waitFor(n)}))),s=s.next(()=>{e.createObjectStore(oy,{keyPath:"clientId"})})),r<5&&n>=5&&(s=s.next(()=>this.D_(i))),r<6&&n>=6&&(s=s.next(()=>(e.createObjectStore(oi),this.x_(i)))),r<7&&n>=7&&(s=s.next(()=>this.C_(i))),r<8&&n>=8&&(s=s.next(()=>this.F_(e,i))),r<9&&n>=9&&(s=s.next(()=>{e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),r<10&&n>=10&&(s=s.next(()=>this.O_(i))),r<11&&n>=11&&(s=s.next(()=>{e.createObjectStore(ow,{keyPath:"bundleId"}),e.createObjectStore(ov,{keyPath:"name"})})),r<12&&n>=12&&(s=s.next(()=>{let t=e.createObjectStore(oA,{keyPath:oV});t.createIndex(ok,oR,{unique:!1}),t.createIndex(oL,oP,{unique:!1})})),r<13&&n>=13&&(s=s.next(()=>(function(e){let t=e.createObjectStore(a9,{keyPath:a7});t.createIndex(oe,ot),t.createIndex(or,on)})(e)).next(()=>this.M_(e,i)).next(()=>e.deleteObjectStore(aJ))),r<14&&n>=14&&(s=s.next(()=>this.N_(e,i))),r<15&&n>=15&&(s=s.next(()=>{e.createObjectStore(o_,{keyPath:"indexId",autoIncrement:!0}).createIndex(ox,"collectionGroup",{unique:!1}),e.createObjectStore(oE,{keyPath:ob}).createIndex(oT,oI,{unique:!1}),e.createObjectStore(oS,{keyPath:oN}).createIndex(oD,oC,{unique:!1})})),r<16&&n>=16&&(s=s.next(()=>{t.objectStore(oE).clear()}).next(()=>{t.objectStore(oS).clear()})),r<17&&n>=17&&(s=s.next(()=>{e.createObjectStore(oO,{keyPath:"name"})})),r<18&&n>=18&&(0,o.Ov)()&&(s=s.next(()=>{t.objectStore(oE).clear()}).next(()=>{t.objectStore(oS).clear()}
6)),s}x_(e){let t=0;return e.store(aJ).jn((e,r)=>{t+=o$(r)}).next(()=>{let r={byteSize:t};return e.store(oi).put(os,r)})}D_(e){let t=e.store(a1),r=e.store(a2);return t.Kn().next(t=>nG.forEach(t,t=>{let n=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return r.Kn(a3,n).next(r=>nG.forEach(r,r=>{T(r.userId===t.userId,18650,"Cannot process batch from unexpected user",{batchId:r.batchId});let n=oZ(this.serializer,r);return oz(e,t.userId,n).next(()=>{})}))}))}C_(e){let t=e.store(ou),r=e.store(aJ);return e.store(om).get(of).next(e=>{let n=[];return r.jn((r,i)=>{let s=new B(r),a=[0,aY(s)];n.push(t.get(a).next(r=>r?nG.resolve():t.put({targetId:0,path:aY(s),sequenceNumber:e.highestListenSequenceNumber})))}).next(()=>nG.waitFor(n))})}F_(e,t){e.createObjectStore(op,{keyPath:og});let r=t.store(op),n=new lb,i=e=>{if(n.add(e)){let t=e.lastSegment(),n=e.popLast();return r.put({collectionId:t,parent:aY(n)})}};return t.store(aJ).jn({zn:!0},(e,t)=>i(new B(e).popLast())).next(()=>t.store(a8).jn({zn:!0},([e,t,r],n)=>i(aX(t).popLast())))}O_(e){let t=e.store(oa);return t.jn((e,r)=>{let n=o0(this.serializer,r),i=o1(this.serializer,n);return t.put(i)})}M_(e,t){let r=t.store(aJ),n=[];return r.jn((e,r)=>{let i=t.store(a9),s=(r.document?new Q(B.fromString(r.document.name).popFirst(5)):r.noDocument?Q.fromSegments(r.noDocument.path):r.unknownDocument?Q.fromSegments(r.unknownDocument.path):E(36783)).path.toArray(),a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:r.readTime||[0,0],unknownDocument:r.unknownDocument,noDocument:r.noDocument,document:r.document,hasCommittedMutations:!!r.hasCommittedMutations};n.push(i.put(a))}).next(()=>nG.waitFor(n))}N_(e,t){let r=t.store(a2),n=new lU(this.serializer),i=new l2(l3.w_,this.serializer.qr);return r.Kn().next(e=>{let r=new Map;return e.forEach(e=>{let t=r.get(e.userId)??rv();oZ(this.serializer,e).keys().forEach(e=>t=t.add(e)),r.set(e.userId,t)}),nG.forEach(r,(e,r)=>{let s=new nu(r),a=lr.Kr(this.serializer,s),o=i.getIndexManager(s);return new lG(n,o9.Kr(s,this.serializer,o,i.referenceDelegate),a,o).recalculateAndSaveOverlaysForDocumentKeys(new oj(t,nz.yn),e).next()})})}}function l8(e){e.createObjectStore(ou,{keyPath:oc}).createIndex(oh,od,{unique:!0}),e.createObjectStore(oa,{keyPath:"targetId"}).createIndex(oo,ol,{unique:!0}),e.createObjectStore(om)}let l9="IndexedDbPersistence",l7="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class ue{constructor(e,t,r,n,i,s,a,o,l,u,c=18){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=r,this.xt=i,this.window=s,this.document=a,this.L_=l,this.B_=u,this.U_=c,this.P_=null,this.R_=!1,this.isPrimary=!1,this.networkEnabled=!0,this.k_=null,this.inForeground=!1,this.q_=null,this.K_=null,this.W_=-1/0,this.Q_=e=>Promise.resolve(),!ue.Je())throw new F(O.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new lV(this,n),this.G_=t+"main",this.serializer=new oW(o),this.z_=new nH(this.G_,this.U_,new l5(this.serializer)),this.I_=new ln,this.A_=new lC(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new lU(this.serializer),this.d_=new lt,this.window&&this.window.localStorage?this.j_=this.window.localStorage:(this.j_=null,!1===u&&v(l9,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.H_().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new F(O.FAILED_PRECONDITION,l7);return this.J_(),this.Y_(),this.Z_(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.A_.getHighestSequenceNumber(e))}).then(e=>{this.P_=new nz(e,this.L_)}).then(()=>{this.R_=!0}).catch(e=>(this.z_&&this.z_.close(),Promise.reject(e)))}X_(e){return this.Q_=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.z_.Ln(async t=>{null===t.newVersion&&await e()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.xt.enqueueAndForget(async()=>{this.started&&await this.H_()}))}H_(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>oK(e,oy).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.eo(e).next(e=>{e||(this.isPrimary=!1,this.xt.enqueueRetryable(()=>this.Q_(!1)))})}).next(()=>this.no(e)).next(t=>this.isPrimary&&!t?this.ro(e).next(()=>!1):!!t&&this.io(e).next(()=>!0))).catch(e=>{if(nZ(e))return w(l9,"Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return w(l9,"Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.xt.enqueueRetryable(()=>this.Q_(e)),this.isPrimary=e})}eo(e){return oK(e,aZ).get(a0).next(e=>nG.resolve(this.so(e)))}_o(e){return oK(e,oy).delete(this.clientId)}
6async oo(){if(this.isPrimary&&!this.ao(this.W_,18e5)){this.W_=Date.now();let e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let t=oK(e,oy);return t.Kn().next(e=>{let r=this.uo(e,18e5),n=e.filter(e=>-1===r.indexOf(e));return nG.forEach(n,e=>t.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.j_)for(let t of e)this.j_.removeItem(this.co(t.clientId))}}Z_(){this.K_=this.xt.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.H_().then(()=>this.oo()).then(()=>this.Z_()))}so(e){return!!e&&e.ownerId===this.clientId}no(e){return this.B_?nG.resolve(!0):oK(e,aZ).get(a0).next(t=>{if(null!==t&&this.ao(t.leaseTimestampMs,5e3)&&!this.lo(t.ownerId)){if(this.so(t)&&this.networkEnabled)return!0;if(!this.so(t)){if(!t.allowTabSynchronization)throw new F(O.FAILED_PRECONDITION,l7);return!1}}return!(!this.networkEnabled||!this.inForeground)||oK(e,oy).Kn().next(e=>void 0===this.uo(e,5e3).find(e=>{if(this.clientId!==e.clientId){let t=!this.networkEnabled&&e.networkEnabled,r=!this.inForeground&&e.inForeground,n=this.networkEnabled===e.networkEnabled;if(t||r&&n)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&w(l9,`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.R_=!1,this.Eo(),this.K_&&(this.K_.cancel(),this.K_=null),this.ho(),this.To(),await this.z_.runTransaction("shutdown","readwrite",[aZ,oy],e=>{let t=new oj(e,nz.yn);return this.ro(t).next(()=>this._o(t))}),this.z_.close(),this.Po()}uo(e,t){return e.filter(e=>this.ao(e.updateTimeMs,t)&&!this.lo(e.clientId))}Ro(){return this.runTransaction("getActiveClients","readonly",e=>oK(e,oy).Kn().next(e=>this.uo(e,18e5).map(e=>e.clientId)))}get started(){return this.R_}getGlobalsCache(){return this.I_}getMutationQueue(e,t){return o9.Kr(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.A_}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new lS(e,this.serializer.qr.databaseId)}getDocumentOverlayCache(e){return lr.Kr(this.serializer,e)}getBundleCache(){return this.d_}runTransaction(e,t,r){var n;let i;w(l9,"Starting transaction:",e);let s=18===(n=this.U_)||17===n?oq:16===n||15===n?oB:14===n||13===n?oU:12===n?oM:11===n?oF:void E(60245);return this.z_.runTransaction(e,"readonly"===t?"readonly":"readwrite",s,n=>(i=new oj(n,this.P_?this.P_.next():nz.yn),"readwrite-primary"===t?this.eo(i).next(e=>!!e||this.no(i)).next(t=>{if(!t)throw v(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.xt.enqueueRetryable(()=>this.Q_(!1)),new F(O.FAILED_PRECONDITION,n$);return r(i)}).next(e=>this.io(i).next(()=>e)):this.Io(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Io(e){return oK(e,aZ).get(a0).next(e=>{if(null!==e&&this.ao(e.leaseTimestampMs,5e3)&&!this.lo(e.ownerId)&&!this.so(e)&&!(this.B_||this.allowTabSynchronization&&e.allowTabSynchronization))throw new F(O.FAILED_PRECONDITION,l7)})}io(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return oK(e,aZ).put(a0,t)}static Je(){return nH.Je()}ro(e){let t=oK(e,aZ);return t.get(a0).next(e=>this.so(e)?(w(l9,"Releasing primary lease."),t.delete(a0)):nG.resolve())}ao(e,t){let r=Date.now();return!(e<r-t)&&(!(e>r)||(v(`Detected an update time that is in the future: ${e} > ${r}`),!1))}J_(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.q_=()=>{this.xt.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.H_()))},this.document.addEventListener("visibilitychange",this.q_),this.inForeground="visible"===this.document.visibilityState)}ho(){this.q_&&(this.document.removeEventListener("visibilitychange",this.q_),this.q_=null)}Y_(){"function"==typeof this.window?.addEventListener&&(this.k_=()=>{this.Eo();let e=/(?:Version|Mobile)\/1[456]/;(0,o.nr)()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.xt.enterRestrictedMode(!0),this.xt.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.k_))}To(){this.k_&&(this.window.removeEventListener("pagehide",this.k_),this.k_=null)}lo(e){try{let t=null!==this.j_?.getItem(this.co(e));return w(l9,`Client '${e}' ${t?"is":"is not"} zombied in LocalStorage`),t}catch(e){return v(l9,"Failed to get zombied client id.",e),!1}}Eo(){if(this.j_)try{this.j_.setItem(this.co(this.clientId),String(Date.now()))}catch(e){v("Failed to set zombie client id.",e)}}Po(){if(this.j_)try{this.j_.removeItem(this.co(this.clientId))}catch(e){}}co(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}class ut{constructor(e,t,r,n){this.targetId=e,this.fromCache=t,this.Ao=r,this.Vo=n}static fo(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 ut(e,t.fromCache,r,n)}}function ur(e,t){return Q.comparator(e.key,t.key)}class un{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class ui{constructor(){this.mo=!1,this.po=!1,this.yo=100,this.wo=(0,o.nr)()?8:nY((0,o.ZQ)())>0?6:4}initialize(e,t){this.bo=e,this.indexManager=t,this.mo=!0}getDocumentsMatchingQuery(e,t,r,n){let i={result:null};return this.vo(e,t).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.So(e,t,n,r).next(e=>{i.result=e})}).next(()=>{if(i.result)return;let r=new un;return this.Do(e,t,r).next(n=>{if(i.result=n,this.po)return this.xo(e,t,r,n.size)})}).next(()=>i.result)}xo(e,t,r,n){return az(t)?nG.resolve():r.documentReadCount<this.yo?(y()<=u.$b.DEBUG&&w("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.yo,"documents"),nG.resolve()):(y()<=u.$b.DEBUG&&w("QueryEngine","Query:",ra(t),"scans",r.documentReadCount,"local documents and returns",n,"documents as results."),r.documentReadCount>this.wo*n?(y()<=u.$b.DEBUG&&w("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))):nG.resolve())}vo(e,t){if(az(t))return nG.resolve(null);let r=t;if(t8(r))return nG.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 i=rv(...t);return this.bo.getDocuments(e,i).next(t=>this.indexManager.getMinOffset(e,n).next(n=>{let s=this.Co(r,t);return this.Fo(r,s,i,n.readTime)?this.vo(e,rn(r,null,"F")):this.Oo(e,s,r,n)}))})))}So(e,t,r,n){return(az(t)?function(e){for(let t of e.stages){if(t instanceof i7||t instanceof se)return!1;if(t instanceof i9){if(t.condition instanceof iY&&"exists"===t.condition._expr.name&&t.condition._expr.params[0]instanceof i$&&t.condition._expr.params[0].fieldName===M)continue;return!1}}return!0}(t):t8(t))||n.isEqual(tB.min())?nG.resolve(null):this.bo.getDocuments(e,r).next(i=>{let s=this.Co(t,i);return this.Fo(t,s,r,n)?nG.resolve(null):(y()<=u.$b.DEBUG&&w("QueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),a$(t)),this.Oo(e,s,t,function(e,t){let r=e.toTimestamp().seconds,n=e.toTimestamp().nanoseconds+1;return new tW(tB.fromTimestamp(1e9===n?new er(r+1,0):new er(r,n)),Q.empty(),-1)}(n,0)).next(e=>e))})}Co(e,t){let r,n;return az(e)?(r=new R(ur),n=t=>lL(e,t)):(r=new R(rl(e)),n=t=>ro(e,t)),t.forEach((e,t)=>{n(t)&&(r=r.add(t))}),r}
6Fo(e,t,r,n){if(az(e))return e.stages.some(e=>e instanceof i7||e instanceof se);if(null===e.limit)return!1;if(r.size!==t.size)return!0;let i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(n)>0)}Do(e,t,r){return y()<=u.$b.DEBUG&&w("QueryEngine","Using full collection scan to execute query:",a$(t)),this.bo.getDocumentsMatchingQuery(e,t,tW.min(),r)}Oo(e,t,r,n){return this.bo.getDocumentsMatchingQuery(e,r,n).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let us="LocalStore";class ua{constructor(e,t,r,n){this.persistence=e,this.Mo=t,this.serializer=n,this.No=new A(S),this.Lo=new rh(e=>aG(e),aQ),this.Bo=new Map,this.Uo=e.getRemoteDocumentCache(),this.A_=e.getTargetCache(),this.d_=e.getBundleCache(),this.ko(r)}ko(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new lG(this.Uo,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Uo.setIndexManager(this.indexManager),this.Mo.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.No))}}async function uo(e,t){return await e.persistence.runTransaction("Handle user change","readonly",r=>{let n;return e.mutationQueue.getAllMutationBatches(r).next(i=>(n=i,e.ko(t),e.mutationQueue.getAllMutationBatches(r))).next(t=>{let i=[],s=[],a=rv();for(let e of n)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(r,a).next(e=>({qo:e,removedBatchIds:i,addedBatchIds:s}))})})}function ul(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.A_.getLastRemoteSnapshotVersion(t))}async function uu(e,t,r){let n=e.No.get(t);try{r||await e.persistence.runTransaction("Release target",r?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,n))}catch(e){if(!nZ(e))throw e;w(us,`Failed to update sequence numbers for target ${t}: ${e}`)}e.No=e.No.remove(t),e.Lo.delete(n.target)}function uc(e,t,r){let n=tB.min(),i=rv();return e.persistence.runTransaction("Execute query","readwrite",s=>(function(e,t,r){let n=e.Lo.get(r);return void 0!==n?nG.resolve(e.No.get(n)):e.A_.getTargetData(t,r)})(e,s,az(t)?t:re(t)).next(t=>{if(t)return n=t.lastLimboFreeSnapshotVersion,e.A_.getMatchingKeysForTargetId(s,t.targetId).next(e=>{i=e})}).next(()=>e.Mo.getDocumentsMatchingQuery(s,t,r?n:tB.min(),r?i:rv())).next(t=>{var r;return r=e,t.forEach((e,t)=>{let n=t.key.getCollectionGroup(),i=r.Bo.get(n)||tB.min();t.readTime.compareTo(i)>0&&r.Bo.set(n,t.readTime)}),{documents:t,Wo:i}}))}class uh{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Jo=0,this.Yo=null,this.Zo=!0}Xo(){0===this.Jo&&(this.ea("Unknown"),this.Yo=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.Yo=null,this.ta("Backend didn't respond within 10 seconds."),this.ea("Offline"),Promise.resolve())))}na(e){"Online"===this.state?this.ea("Unknown"):(this.Jo++,this.Jo>=1&&(this.ra(),this.ta(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ea("Offline")))}set(e){this.ra(),this.Jo=0,"Online"===e&&(this.Zo=!1),this.ea(e)}ea(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}ta(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.Zo?(v(t),this.Zo=!1):w("OnlineStateTracker",t)}ra(){null!==this.Yo&&(this.Yo.cancel(),this.Yo=null)}}let ud="RemoteStore";class uf{constructor(e,t,r,n,i){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.ia=[],this.sa=new Map,this._a=new Map,this.oa=new Map,this.aa=new lD(1e3),this.ua=new lD(1001),this.ca=new Set,this.la=[],this.Ea=i,this.Ea.Ke(e=>{r.enqueueAndForget(async()=>
7{ub(this)&&(w(ud,"Restarting streams for network reachability change."),await async function(e){e.ca.add(4),await up(e),e.ha.set("Unknown"),e.ca.delete(4),await um(e)}(this))})}),this.ha=new uh(r,n)}}async function um(e){if(ub(e))for(let t of e.la)await t(!0)}async function up(e){for(let t of e.la)await t(!1)}function ug(e,t){return e._a.get(t)||void 0}function uy(e,t){let r=ug(e,t.targetId);if(void 0!==r&&e.sa.has(r))return;let n=function(e,t){let r=ug(e,t);void 0!==r&&e.oa.delete(r);let n=t%2!=0?e.ua.next():e.aa.next();return e._a.set(t,n),e.oa.set(n,t),n}(e,t.targetId);w(ud,"remoteStoreListen mapping SDK target ID to remote",t.targetId,n);let i=new oQ(t.target,n,t.purpose,t.sequenceNumber,t.snapshotVersion,t.lastLimboFreeSnapshotVersion,t.resumeToken);e.sa.set(n,i),uE(e)?ux(e):uU(e).Jt()&&uv(e,i)}function uw(e,t){let r=uU(e),n=ug(e,t);w(ud,"remoteStoreUnlisten removing mapping of SDK target ID to remote",t,n),e.sa.delete(n),e._a.delete(t),e.oa.delete(n),r.Jt()&&u_(e,n),0===e.sa.size&&(r.Jt()?r.Xt():ub(e)&&e.ha.set("Unknown"))}function uv(e,t){if(e.Ta.H(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(tB.min())>0){let r=e.oa.get(t.targetId);if(void 0===r)return void w(ud,"SDK target ID not found for remote ID: "+t.targetId);let n=e.remoteSyncer.getRemoteKeysForTarget(r).size;t=t.withExpectedCount(n)}uU(e).Tn(t)}function u_(e,t){e.Ta.H(t),uU(e).Pn(t)}function ux(e){e.Ta=new rR({getRemoteKeysForTarget:t=>{let r=e.oa.get(t);return void 0!==r?e.remoteSyncer.getRemoteKeysForTarget(r):rv()},ge:t=>e.sa.get(t)||null,Ae:()=>e.datastore.serializer.databaseId}),uU(e).start(),e.ha.Xo()}function uE(e){return ub(e)&&!uU(e).Ht()&&e.sa.size>0}function ub(e){return 0===e.ca.size}async function uT(e){e.ha.set("Online")}async function uI(e){e.sa.forEach((t,r)=>{uv(e,t)})}async function uS(e,t){e.Ta=void 0,uE(e)?(e.ha.na(t),ux(e)):e.ha.set("Unknown")}async function uN(e,t,r){if(e.ha.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.sa.has(n)){let t=e.oa.get(n);void 0!==t&&(await e.remoteSyncer.rejectListen(t,r),e._a.delete(t),e.oa.delete(n)),e.sa.delete(n)}e.Ta.removeTarget(n)}}(e,t)}catch(r){w(ud,"Failed to remove targets %s: %s ",t.targetIds.join(","),r),await uD(e,r)}else if(t instanceof rD?e.Ta.se(t):t instanceof rC?e.Ta.Ee(t):e.Ta.ae(t),!r.isEqual(tB.min()))try{let t=await ul(e.localStore);r.compareTo(t)>=0&&await function(e,t){let r=e.Ta.de(t);
7r.targetChanges.forEach((r,n)=>{if(r.resumeToken.approximateByteSize()>0){let i=e.sa.get(n);i&&e.sa.set(n,i.withResumeToken(r.resumeToken,t))}}),r.targetMismatches.forEach((t,r)=>{let n=e.sa.get(t);if(!n)return;e.sa.set(t,n.withResumeToken(ei.EMPTY_BYTE_STRING,n.snapshotVersion)),u_(e,t);let i=new oQ(n.target,t,r,n.sequenceNumber);uv(e,i)});let n=function(e,t){let r=new Map;t.targetChanges.forEach((t,n)=>{let i=e.oa.get(n);void 0!==i&&r.set(i,t)});let n=new A(S);return t.targetMismatches.forEach((t,r)=>{let i=e.oa.get(t);void 0!==i&&(n=n.insert(i,r))}),new rS(t.snapshotVersion,r,n,t.documentUpdates,t.augmentedDocumentUpdates,t.resolvedLimboDocuments)}(e,r);return e.remoteSyncer.applyRemoteEvent(n)}(e,r)}catch(t){w(ud,"Failed to raise snapshot:",t),await uD(e,t)}}async function uD(e,t,r){if(!nZ(t))throw t;e.ca.add(1),await up(e),e.ha.set("Offline"),r||(r=()=>ul(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{w(ud,"Retrying IndexedDB access"),await r(),e.ca.delete(1),await um(e)})}function uC(e,t){return t().catch(r=>uD(e,r,t))}async function uA(e){var t;let r=uB(e),n=e.ia.length>0?e.ia[e.ia.length-1].batchId:-1;for(;ub(t=e)&&t.ia.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.ia.length&&r.Xt();break}n=t.batchId,function(e,t){e.ia.push(t);let r=uB(e);r.Jt()&&r.Rn&&r.In(t.mutations)}(e,t)}catch(t){await uD(e,t)}uV(e)&&uk(e)}function uV(e){return ub(e)&&!uB(e).Ht()&&e.ia.length>0}function uk(e){uB(e).start()}async function uR(e){uB(e).dn()}async function uL(e){let t=uB(e);for(let r of e.ia)t.In(r.mutations)}async function uP(e,t,r){let n=e.ia.shift(),i=aH.from(n,t,r);await uC(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await uA(e)}async function uO(e,t){t&&uB(e).Rn&&await async function(e,t){var r;if(function(e){switch(e){case O.OK:return E(64938);case O.CANCELLED:case O.UNKNOWN:case O.DEADLINE_EXCEEDED:case O.RESOURCE_EXHAUSTED:case O.INTERNAL:case O.UNAVAILABLE:case O.UNAUTHENTICATED:return!1;case O.INVALID_ARGUMENT:case O.NOT_FOUND:case O.ALREADY_EXISTS:case O.PERMISSION_DENIED:case O.FAILED_PRECONDITION:case O.ABORTED:case O.OUT_OF_RANGE:case O.UNIMPLEMENTED:case O.DATA_LOSS:return!0;default:return E(15467,{code:e})}}(r=t.code)&&r!==O.ABORTED){let r=e.ia.shift();uB(e).Zt(),await uC(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await uA(e)}}(e,t),uV(e)&&uk(e)}async function uF(e,t){e.asyncQueue.verifyOperationInProgress(),w(ud,"RemoteStore received new credentials");let r=ub(e);e.ca.add(3),await up(e),r&&e.ha.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.ca.delete(3),await um(e)}async function uM(e,t){t?(e.ca.delete(2),await um(e)):t||(e.ca.add(2),await up(e),e.ha.set("Unknown"))}function uU(e){var t,r,n;return e.Pa||(t=e.datastore,r=e.asyncQueue,n={ut:uT.bind(null,e),lt:uI.bind(null,e),ht:uS.bind(null,e),hn:uN.bind(null,e)},t.mn(),e.Pa=new nP(r,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,n),e.la.push(async t=>{t?(e.Pa.Zt(),uE(e)?ux(e):e.ha.set("Unknown")):(await e.Pa.stop(),e.Ta=void 0)})),e.Pa}function uB(e){var t,r,n;return e.Ra||(t=e.datastore,r=e.asyncQueue,n={ut:()=>Promise.resolve(),lt:uR.bind(null,e),ht:uO.bind(null,e),An:uL.bind(null,e),Vn:uP.bind(null,e)},t.mn(),e.Ra=new nO(r,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,n),e.la.push(async t=>{t?(e.Ra.Zt(),await uA(e)):(await e.Ra.stop(),e.ia.length>0&&(w(ud,`Stopping write stream with ${e.ia.length} pending writes`),e.ia=[]))})),e.Ra}class uq{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ia(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ia(this.observer.error,e):v("Uncaught Error in snapshot listener:",e.toString()))}Aa(){this.muted=!0}Ia(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class uz{constructor(e,t,r,n,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=n,this.removalCallback=i,this.deferred=new nc,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,i){let s=new uz(e,t,Date.now()+r,n,i);return s.start(r),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new F(O.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 u$(e,t){if(v("AsyncQueue",`${t}: ${e}`),nZ(e))return new F(O.UNAVAILABLE,`${t}: ${e}`);throw e}let uj="IndexBackfiller";class uK{constructor(e,t){this.asyncQueue=e,this.Sa=t,this.task=null}start(){this.Da(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}Da(e){w(uj,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{let e=await this.Sa.xa();w(uj,`Documents written: ${e}`)}catch(e){nZ(e)?w(uj,"Ignoring IndexedDB error during index backfill: ",e):await nK(e)}await this.Da(6e4)})}}class uG{constructor(e,t){this.localStore=e,this.persistence=t}async xa(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.Ca(t,e))}Ca(e,t){let r=new Set,n=t,i=!0;return nG.doWhile(()=>!0===i&&n>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>
7{if(null!==t&&!r.has(t))return w(uj,`Processing collection: ${t}`),this.Fa(e,t,n).next(e=>{n-=e,r.add(t)});i=!1})).next(()=>t-n)}Fa(e,t,r){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(n=>this.localStore.localDocuments.getNextDocuments(e,t,n,r).next(r=>{let i=r.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next(()=>this.Oa(n,r)).next(r=>(w(uj,`Updating offset: ${r}`),this.localStore.indexManager.updateCollectionGroup(e,t,r))).next(()=>i.size)}))}Oa(e,t){let r=e;return t.changes.forEach((e,t)=>{let n=tQ(t);tH(n,r)>0&&(r=n)}),new tW(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class uQ{constructor(){this.activeTargetIds=r_}La(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ba(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Na(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class uW{constructor(){this.du=new uQ,this.fu={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.du.La(e),this.fu[e]||"not-current"}updateQueryState(e,t,r){this.fu[e]=t}removeLocalQueryTarget(e){this.du.Ba(e)}isLocalQueryTarget(e){return this.du.activeTargetIds.has(e)}clearQueryState(e){delete this.fu[e]}getAllActiveQueryTargets(){return this.du.activeTargetIds}isActiveQueryTarget(e){return this.du.activeTargetIds.has(e)}start(){return this.du=new uQ,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}function uH(){return"undefined"!=typeof document?document:null}class uY{static emptySet(e){return new uY(e.comparator)}constructor(e){this.comparator=e?(t,r)=>e(t,r)||Q.comparator(t.key,r.key):(e,t)=>Q.comparator(e.key,t.key),this.keyedMap=rm(),this.sortedSet=new A(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 uY)||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 uY;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}}class uX{constructor(){this.mu=new A(Q.comparator)}track(e){let t=e.doc.key,r=this.mu.get(t);r?0!==e.type&&3===r.type?this.mu=this.mu.insert(t,e):3===e.type&&1!==r.type?this.mu=this.mu.insert(t,{type:r.type,doc:e.doc}):2===e.type&&2===r.type?this.mu=this.mu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===r.type?this.mu=this.mu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===r.type?this.mu=this.mu.remove(t):1===e.type&&2===r.type?this.mu=this.mu.insert(t,{type:1,doc:r.doc}):0===e.type&&1===r.type?this.mu=this.mu.insert(t,{type:2,doc:e.doc}):E(63341,{ye:e,pu:r}):this.mu=this.mu.insert(t,e)}gu(){let e=[];return this.mu.inorderTraversal((t,r)=>{e.push(r)}),e}}class uJ{constructor(e,t,r,n,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=n,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,r,n,i){let s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new uJ(e,t,uY.emptySet(t),s,r,n,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&aK(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 uZ{constructor(){this.yu=void 0,this.wu=[]}bu(){return this.wu.some(e=>e.vu())}}class u0{constructor(){this.queries=u1(),this.onlineState="Unknown",this.Su=new Set}terminate(){!function(e,t){let r=e.queries;e.queries=u1(),r.forEach((e,r)=>{for(let e of r.wu)e.onError(t)})}(this,new F(O.ABORTED,"Firestore shutting down"))}}function u1(){return new rh(e=>aj(e),aK)}async function u2(e,t){let r=3,n=t.query,i=e.queries.get(n);i?!i.bu()&&t.vu()&&(r=2):(i=new uZ,r=+!t.vu());try{switch(r){case 0:i.yu=await e.onListen(n,!0);break;case 1:i.yu=await e.onListen(n,!1);break;case 2:await e.onFirstRemoteStoreListen(n)}}catch(r){let e=u$(r,`Initialization of query '${az(t.query)?aq(t.query):ra(t.query)}' failed`);return void t.onError(e)}e.queries.set(n,i),i.wu.push(t),t.Du(e.onlineState),i.yu&&t.xu(i.yu)&&u5(e)}async function u4(e,t){let r=t.query,n=3,i=e.queries.get(r);if(i){let e=i.wu.indexOf(t);e>=0&&(i.wu.splice(e,1),0===i.wu.length?n=+!t.vu():!i.bu()&&t.vu()&&(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 u3(e,t){let r=!1;for(let n of t){let t=n.query,i=e.queries.get(t);if(i){for(let e of i.wu)e.xu(n)&&(r=!0);i.yu=n}}r&&u5(e)}function u6(e,t,r){let n=e.queries.get(t);if(n)for(let e of n.wu)e.onError(r);e.queries.delete(t)}
7function u5(e){e.Su.forEach(e=>{e.next()})}!function(e){e.Default="default",e.Cache="cache"}(s||(s={}));class u8{constructor(e,t,r){this.query=e,this.Cu=t,this.Fu=!1,this.Ou=null,this.onlineState="Unknown",this.options=r||{}}xu(e){if(!this.options.includeMetadataChanges){let t=[];for(let r of e.docChanges)3!==r.type&&t.push(r);e=new uJ(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Fu?this.Mu(e)&&(this.Cu.next(e),t=!0):this.Nu(e,this.onlineState)&&(this.Lu(e),t=!0),this.Ou=e,t}onError(e){this.Cu.error(e)}Du(e){this.onlineState=e;let t=!1;return this.Ou&&!this.Fu&&this.Nu(this.Ou,e)&&(this.Lu(this.Ou),t=!0),t}Nu(e,t){return!(e.fromCache&&this.vu())||(!this.options.waitForSyncWhenOnline||"Offline"===t)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Mu(e){if(e.docChanges.length>0)return!0;let t=this.Ou&&this.Ou.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Lu(e){e=uJ.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Fu=!0,this.Cu.next(e)}vu(){return this.options.source!==s.Cache}}class u9{constructor(e){this.key=e}}class u7{constructor(e){this.key=e}}class ce{constructor(e,t){this.query=e,this.Gu=t,this.zu=null,this.hasCachedResults=!1,this.current=!1,this.ju=rv(),this.mutatedKeys=rv(),this.Hu=az(e)?lO(e):rl(e),this.Ju=new uY(this.Hu)}get Yu(){return this.Gu}Zu(e,t){let r=t?t.Xu:new uX,n=t?t.Ju:this.Ju,i=t?t.mutatedKeys:this.mutatedKeys,s=n,a=!1,[o,l]=this.ec(this.query,n);e.inorderTraversal((e,t)=>{let u=n.get(e),c=lP(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!c&&(c.hasLocalMutations||this.mutatedKeys.has(c.key)&&c.hasCommittedMutations),f=!1;u&&c?u.data.isEqual(c.data)?h!==d&&(r.track({type:3,doc:c}),f=!0):this.tc(u,c)||(r.track({type:2,doc:c}),f=!0,(o&&this.Hu(c,o)>0||l&&0>this.Hu(c,l))&&(a=!0)):!u&&c?(r.track({type:0,doc:c}),f=!0):u&&!c&&(r.track({type:1,doc:u}),f=!0,(o||l)&&(a=!0)),f&&(c?(s=s.add(c),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))});let u=this.nc(this.query);if(u)if(az(this.query)){let e=[];s.forEach(t=>e.push(t));let t=lR(this.query,e),n=new uY(lO(this.query));for(let e of t)n=n.add(e);s.forEach(e=>{n.has(e.key)||(i=i.delete(e.key),r.track({type:1,doc:e}))}),s=n}else{let e=this.rc(this.query);for(;s.size>u;){let t="F"===e?s.last():s.first();s=s.delete(t.key),i=i.delete(t.key),r.track({type:1,doc:t})}}return{Ju:s,Xu:r,Fo:a,mutatedKeys:i}}nc(e){return az(e)?lF(e)?.limit:e.limit||void 0}rc(e){if(az(e)){let t=lF(e);return t&&t.limit<0?"L":"F"}return e.limitType}ec(e,t){if(az(e)){let r=lF(e)?.limit;return[t.size===r?t.last():null,null]}return["F"===e.limitType&&t.size===this.nc(this.query)?t.last():null,"L"===e.limitType&&t.size===this.nc(this.query)?t.first():null]}tc(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,n){let i=this.Ju;this.Ju=e.Ju,this.mutatedKeys=e.mutatedKeys;let s=e.Xu.gu();s.sort((e,t)=>(function(e,t){let r=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return E(20277,{ye:e})}};return r(e)-r(t)})(e.type,t.type)||this.Hu(e.doc,t.doc)),this.sc(r),n=n??!1;let a=t&&!n?this._c():[],o=0===this.ju.size&&this.current&&!n?1:0,l=o!==this.zu;return(this.zu=o,0!==s.length||l)?{snapshot:new uJ(this.query,e.Ju,i,s,e.mutatedKeys,0===o,l,!1,!!r&&r.resumeToken.approximateByteSize()>0),oc:a}:{oc:a}}Du(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ju:this.Ju,Xu:new uX,mutatedKeys:this.mutatedKeys,Fo:!1},!1)):{oc:[]}}ac(e){return!this.Gu.has(e)&&!!this.Ju.has(e)&&!this.Ju.get(e).hasLocalMutations}sc(e){e&&(e.addedDocuments.forEach(e=>this.Gu=this.Gu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Gu=this.Gu.delete(e)),this.current=e.current)}_c(){if(!this.current)return[];let e=this.ju;this.ju=rv(),this.Ju.forEach(e=>{this.ac(e.key)&&(this.ju=this.ju.add(e.key))});let t=[];return e.forEach(e=>{this.ju.has(e)||t.push(new u7(e))}),this.ju.forEach(r=>{e.has(r)||t.push(new u9(r))}),t}uc(e){this.Gu=e.Wo,this.ju=rv();let t=this.Zu(e.documents);return this.applyChanges(t,!0)}cc(){return uJ.fromInitialDocuments(this.query,this.Ju,this.mutatedKeys,0===this.zu,this.hasCachedResults)}}let ct="SyncEngine";class cr{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}}class cn{constructor(e){this.key=e,this.lc=!1}}class ci{constructor(e,t,r,n,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedCl
7ientState=n,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Ec={},this.hc=new rh(e=>aj(e),aK),this.Tc=new Map,this.Pc=new Set,this.Rc=new A(Q.comparator),this.Ic=new Map,this.Ac=new lY,this.Vc={},this.dc=new Map,this.fc=lD.ws(),this.onlineState="Unknown",this.mc=void 0}get isPrimaryClient(){return!0===this.mc}}async function cs(e,t,r=!0){let n,i=cS(e),s=i.hc.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),n=s.view.cc()):n=await co(i,t,r,!0),n}async function ca(e,t){let r=cS(e);await co(r,t,!0,!1)}async function co(e,t,r,n){var i,s;let a,o=await (i=e.localStore,s=az(t)?t:re(t),i.persistence.runTransaction("Allocate target","readwrite",e=>{let t;return i.A_.getTargetData(e,s).next(r=>r?(t=r,nG.resolve(t)):i.A_.allocateTargetId(e).next(r=>(t=new oQ(s,r,"TargetPurposeListen",e.currentSequenceNumber),i.A_.addTargetData(e,t).next(()=>t))))}).then(e=>{let t=i.No.get(e.targetId);return(null===t||e.snapshotVersion.compareTo(t.snapshotVersion)>0)&&(i.No=i.No.insert(e.targetId,e),i.Lo.set(s,e.targetId)),e})),l=o.targetId,u=e.sharedClientState.addLocalQueryTarget(l,r);return n&&(a=await cl(e,t,l,"current"===u,o.resumeToken)),e.isPrimaryClient&&r&&uy(e.remoteStore,o),a}async function cl(e,t,r,n,i){e.gc=(t,r,n)=>(async function(e,t,r,n){let i=t.view.Zu(r);i.Fo&&(i=await uc(e.localStore,t.query,!1).then(({documents:e})=>t.view.Zu(e,i)));let s=n&&n.targetChanges.get(t.targetId),a=n&&null!=n.targetMismatches.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s,a);return cx(e,t.targetId,o.oc),o.snapshot})(e,t,r,n);let s=await uc(e.localStore,t,!0),a=new ce(t,s.Wo),o=a.Zu(s.documents),l=rN.createSynthesizedTargetChangeForCurrentChange(r,n&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);cx(e,r,u.oc);let c=new cr(t,r,a);return e.hc.set(t,c),e.Tc.has(r)?e.Tc.get(r).push(t):e.Tc.set(r,[t]),u.snapshot}async function cu(e,t,r){let n=e.hc.get(t),i=e.Tc.get(n.targetId);if(i.length>1)return e.Tc.set(n.targetId,i.filter(e=>!aK(e,t))),void e.hc.delete(t);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(n.targetId),e.sharedClientState.isActiveQueryTarget(n.targetId)||await uu(e.localStore,n.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(n.targetId),r&&uw(e.remoteStore,n.targetId),cv(e,n.targetId)}).catch(nK)):(cv(e,n.targetId),await uu(e.localStore,n.targetId,!0))}async function cc(e,t){let r=e.hc.get(t),n=e.Tc.get(r.targetId);e.isPrimaryClient&&1===n.length&&(e.sharedClientState.removeLocalQueryTarget(r.targetId),uw(e.remoteStore,r.targetId))}async function ch(e,t,r){let n=cN(e);try{var i;let e,s=await function(e,t){let r,n,i=er.now(),s=t.reduce((e,t)=>e.add(t.key),rv());return e.persistence.runTransaction("Locally write mutations","readwrite",a=>{let o=rd,l=rv();return e.Uo.getEntries(a,s).next(e=>{(o=e).forEach((e,t)=>{t.isValidDocument()||(l=l.add(e))})}).next(()=>e.localDocuments.getOverlayedDocuments(a,o)).next(n=>{r=n;let s=[];for(let e of t){let t=function(e,t){let r=null;for(let n of e.fieldTransforms){let e=t.data.field(n.field),i=e2(n.transform,e||null);null!=i&&(null===r&&(r=eX.empty()),r.set(n.field,i))}return r||null}(e,r.get(e.key).overlayedDocument);null!=t&&s.push(new tm(e.key,t,function e(t){let r=[];return K(t.fields,(t,n)=>{let i=new z([t]);if(e$(n)){let t=e(n.mapValue).fields;if(0===t.length)r.push(i);else for(let e of t)r.push(i.child(e))}else r.push(i)}),new $(r)}(t.value.mapValue),to.exists(!0)))}return e.mutationQueue.addMutationBatch(a,i,s,t)}).next(t=>{n=t;let i=t.applyToLocalDocumentSet(r,l);return e.documentOverlayCache.saveOverlays(a,t.batchId,i)})}).then(()=>({batchId:n.batchId,changes:rp(r)}))}(n.localStore,t);n.sharedClientState.addPendingMutation(s.batchId),i=s.batchId,(e=n.Vc[n.currentUser.toKey()])||(e=new A(S)),e=e.insert(i,r),n.Vc[n.currentUser.toKey()]=e,await cb(n,s.changes),await uA(n.remoteStore)}catch(t){let e=u$(t,"Failed to persist write");r.reject(e)}}async function cd(e,t){try{let r=await function(e,t){let r=t.snapshotVersion,n=e.No;return e.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{var s,a,o;let l,u,c=e.Uo.newChangeBuffer({trackRemovals:!0});n=e.No;let h=[];
7t.targetChanges.forEach((s,a)=>{var o;let l=n.get(a);if(!l)return;h.push(e.A_.removeMatchingKeys(i,s.removedDocuments,a).next(()=>e.A_.addMatchingKeys(i,s.addedDocuments,a)));let u=l.withSequenceNumber(i.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(ei.EMPTY_BYTE_STRING,tB.min()).withLastLimboFreeSnapshotVersion(tB.min()):s.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(s.resumeToken,r)),n=n.insert(a,u),o=u,(0===l.resumeToken.approximateByteSize()||o.snapshotVersion.toMicroseconds()-l.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)&&h.push(e.A_.updateTargetData(i,u))});let d=rd,f=rv();if(t.documentUpdates.forEach(r=>{t.resolvedLimboDocuments.has(r)&&h.push(e.persistence.referenceDelegate.updateLimboDocument(i,r))}),h.push((s=i,a=c,o=t.documentUpdates,l=rv(),u=rv(),o.forEach(e=>l=l.add(e)),a.getEntries(s,l).next(e=>{let t=rd;return o.forEach((r,n)=>{let i=e.get(r);n.isFoundDocument()!==i.isFoundDocument()&&(u=u.add(r)),n.isNoDocument()&&n.version.isEqual(tB.min())?(a.removeEntry(r,n.readTime),t=t.insert(r,n)):!i.isValidDocument()||n.version.compareTo(i.version)>0||0===n.version.compareTo(i.version)&&i.hasPendingWrites?(a.addEntry(n),t=t.insert(r,n)):w(us,"Ignoring outdated watch update for ",r,". Current version:",i.version," Watch version:",n.version)}),{$o:t,Ko:u}})).next(e=>{d=e.$o,f=e.Ko})),!r.isEqual(tB.min())){let t=e.A_.getLastRemoteSnapshotVersion(i).next(t=>e.A_.setTargetsMetadata(i,i.currentSequenceNumber,r));h.push(t)}return nG.waitFor(h).next(()=>c.apply(i)).next(()=>e.localDocuments.getLocalViewOfDocuments(i,d,f)).next(()=>d)}).then(t=>(e.No=n,t))}(e.localStore,t);
7t.targetChanges.forEach((t,r)=>{let n=e.Ic.get(r);n&&(T(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?n.lc=!0:t.modifiedDocuments.size>0?T(n.lc,14607):t.removedDocuments.size>0&&(T(n.lc,42227),n.lc=!1))}),await cb(e,r,t)}catch(e){await nK(e)}}function cf(e,t,r){var n;if(e.isPrimaryClient&&0===r||!e.isPrimaryClient&&1===r){let r,i=[];e.hc.forEach((e,r)=>{let n=r.view.Du(t);n.snapshot&&i.push(n.snapshot)}),(n=e.eventManager).onlineState=t,r=!1,n.queries.forEach((e,n)=>{for(let e of n.wu)e.Du(t)&&(r=!0)}),r&&u5(n),i.length&&e.Ec.hn(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function cm(e,t,r){e.sharedClientState.updateQueryState(t,"rejected",r);let n=e.Ic.get(t),i=n&&n.key;if(i){let r=new A(Q.comparator);r=r.insert(i,tq.newNoDocument(i,tB.min()));let n=rv().add(i),s=new rS(tB.min(),new Map,new A(S),r,rd,n);await cd(e,s),e.Rc=e.Rc.remove(i),e.Ic.delete(t),cE(e)}else await uu(e.localStore,t,!1).then(()=>cv(e,t,r)).catch(nK)}async function cp(e,t){var r;let n=t.batch.batchId;try{let i=await (r=e.localStore,r.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let n=t.batch.keys(),i=r.Uo.newChangeBuffer({trackRemovals:!0});return(function(e,t,r,n){let i=r.batch,s=i.keys(),a=nG.resolve();return s.forEach(e=>{a=a.next(()=>n.getEntry(t,e)).next(t=>{let s=r.docVersions.get(e);T(null!==s,48541),0>t.version.compareTo(s)&&(i.applyToRemoteDocument(t,r),t.isValidDocument()&&(t.setReadTime(r.commitVersion),n.addEntry(t)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))})(r,e,t,i).next(()=>i.apply(e)).next(()=>r.mutationQueue.performConsistencyCheck(e)).next(()=>r.documentOverlayCache.removeOverlaysForBatchId(e,n,t.batch.batchId)).next(()=>r.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}(t))).next(()=>r.localDocuments.getDocuments(e,n))}));cw(e,n,null),cy(e,n),e.sharedClientState.updateMutationState(n,"acknowledged"),await cb(e,i)}catch(e){await nK(e)}}async function cg(e,t,r){var n;try{let i=await (n=e.localStore,n.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let r;
7return n.mutationQueue.lookupMutationBatch(e,t).next(t=>(T(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))}));cw(e,t,r),cy(e,t),e.sharedClientState.updateMutationState(t,"rejected",r),await cb(e,i)}catch(e){await nK(e)}}function cy(e,t){(e.dc.get(t)||[]).forEach(e=>{e.resolve()}),e.dc.delete(t)}function cw(e,t,r){let n=e.Vc[e.currentUser.toKey()];if(n){let i=n.get(t);i&&(r?i.reject(r):i.resolve(),n=n.remove(t)),e.Vc[e.currentUser.toKey()]=n}}function cv(e,t,r=null){for(let n of(e.sharedClientState.removeLocalQueryTarget(t),e.Tc.get(t)))e.hc.delete(n),r&&e.Ec.yc(n,r);e.Tc.delete(t),e.isPrimaryClient&&e.Ac.Xs(t).forEach(t=>{e.Ac.containsKey(t)||c_(e,t)})}function c_(e,t){e.Pc.delete(t.path.canonicalString());let r=e.Rc.get(t);null!==r&&(uw(e.remoteStore,r),e.Rc=e.Rc.remove(t),e.Ic.delete(r),cE(e))}function cx(e,t,r){for(let n of r)n instanceof u9?(e.Ac.addReference(n.key,t),function(e,t){let r=t.key,n=r.path.canonicalString();e.Rc.get(r)||e.Pc.has(n)||(w(ct,"New document in limbo: "+r),e.Pc.add(n),cE(e))}(e,n)):n instanceof u7?(w(ct,"Document no longer in limbo: "+n.key),e.Ac.removeReference(n.key,t),e.Ac.containsKey(n.key)||c_(e,n.key)):E(19791,{wc:n})}function cE(e){for(;e.Pc.size>0&&e.Rc.size<e.maxConcurrentLimboResolutions;){let t=e.Pc.values().next().value;e.Pc.delete(t);let r=new Q(B.fromString(t)),n=e.fc.next();e.Ic.set(n,new cn(r)),e.Rc=e.Rc.insert(r,n),uy(e.remoteStore,new oQ(re(t5(r.path)),n,"TargetPurposeLimboResolution",nz.yn))}}async function cb(e,t,r){let n=[],i=[],s=[];e.hc.isEmpty()||(e.hc.forEach((a,o)=>{s.push(e.gc(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=ut.fo(o.targetId,t);i.push(e)}}))}),await Promise.all(s),e.Ec.hn(n),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",r=>nG.forEach(t,t=>nG.forEach(t.Ao,n=>e.persistence.referenceDelegate.addReference(r,t.targetId,n)).next(()=>nG.forEach(t.Vo,n=>e.persistence.referenceDelegate.removeReference(r,t.targetId,n)))))}catch(e){if(!nZ(e))throw e;w(us,"Failed to update sequence numbers: "+e)}for(let r of t){let t=r.targetId;if(!r.fromCache){let r=e.No.get(t),n=r.snapshotVersion,i=r.withLastLimboFreeSnapshotVersion(n);e.No=e.No.insert(t,i)}}}(e.localStore,i))}async function cT(e,t){if(!e.currentUser.isEqual(t)){w(ct,"User change. New user:",t.toKey());let r=await uo(e.localStore,t);e.currentUser=t,e.dc.forEach(e=>{e.forEach(e=>{e.reject(new F(O.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.dc.clear(),e.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await cb(e,r.qo)}}function cI(e,t){let r=e.Ic.get(t);if(r&&r.lc)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.hc.get(t);r=r.unionWith(n.view.Yu)}return r}}function cS(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=cd.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=cI.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=cm.bind(null,e),e.Ec.hn=u3.bind(null,e.eventManager),e.Ec.yc=u6.bind(null,e.eventManager),e}function cN(e){return e.remoteStore.remoteSyncer.applySuccessfulWrite=cp.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=cg.bind(null,e),e}class cD{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=ni(e.databaseInfo.databaseId),this.sharedClientState=this.vc(e),this.persistence=this.Sc(e),await this.persistence.start(),this.localStore=this.Dc(e),this.gcScheduler=this.xc(e,this.localStore),this.indexBackfillerScheduler=this.Cc(e,this.localStore)}xc(e,t){return null}Cc(e,t){return null}Dc(e){var t,r;return t=this.persistence,r=new ui,new ua(t,r,e.initialUser,this.serializer)}Sc(e){return new l2(l3.w_,this.serializer)}vc(e){return new uW}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedCl
7ientState.shutdown(),await this.persistence.shutdown()}}cD.provider={build:()=>new cD};class cC extends cD{constructor(e){super(),this.cacheSizeBytes=e}xc(e,t){return T(this.persistence.referenceDelegate instanceof l6,46915),new n8(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Sc(e){let t=void 0!==this.cacheSizeBytes?nq.withCacheSize(this.cacheSizeBytes):nq.DEFAULT;return new l2(e=>l6.w_(e,t),this.serializer)}}class cA extends cD{constructor(e,t,r){super(),this.Fc=e,this.cacheSizeBytes=t,this.forceOwnership=r,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Fc.initialize(this,e),await cN(this.Fc.syncEngine),await uA(this.Fc.remoteStore),await this.persistence.X_(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Dc(e){var t,r;return t=this.persistence,r=new ui,new ua(t,r,e.initialUser,this.serializer)}xc(e,t){return new n8(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Cc(e,t){let r=new uG(t,this.persistence);return new uK(e.asyncQueue,r)}Sc(e){var t,r;let n,i=(t=e.databaseInfo.databaseId,r=e.databaseInfo.persistenceKey,n=t.projectId,t.isDefaultDatabase||(n+="."+t.database),"firestore/"+r+"/"+n+"/"),s=void 0!==this.cacheSizeBytes?nq.withCacheSize(this.cacheSizeBytes):nq.DEFAULT;return new ue(this.synchronizeTabs,i,e.clientId,s,e.asyncQueue,"undefined"!=typeof window?window:null,uH(),this.serializer,this.sharedClientState,!!this.forceOwnership)}vc(e){return new uW}}class cV{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=>cf(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=cT.bind(null,this.syncEngine),await uM(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new u0}createDatastore(e){var t;let r=ni(e.databaseInfo.databaseId),n=new nV(e.databaseInfo);return t=e.authCredentials,new nM(t,e.appCheckCredentials,n,r)}createRemoteStore(e){var t,r;return t=this.localStore,r=this.datastore,new uf(t,r,e.asyncQueue,e=>cf(this.syncEngine,e,0),nE.Je()?new nE:new n_)}createSyncEngine(e,t){return function(e,t,r,n,i,s,a){let o=new ci(e,t,r,n,i,s);return a&&(o.mc=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){await async function(e){w(ud,"RemoteStore shutting down."),e.ca.add(5),await up(e),e.Ea.shutdown(),e.ha.set("Unknown")}(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}cV.provider={build:()=>new cV};let ck="FirestoreClient";class cR{constructor(e,t,r,n,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this._databaseInfo=n,this.user=nu.UNAUTHENTICATED,this.clientId=I.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(r,async e=>{w(ck,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(r,e=>(w(ck,"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 nc;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=u$(r,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function cL(e,t){e.asyncQueue.verifyOperationInProgress(),w(ck,"Initializing OfflineComponentProvider");let r=e.configuration;await t.initialize(r);let n=r.initialUser;e.setCredentialChangeListener(async e=>{n.isEqual(e)||(await uo(t.localStore,e),n=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function cP(e,t){e.asyncQueue.verifyOperationInProgress();let r=await cO(e);w(ck,"Initializing OnlineComponentProvider"),await t.initialize(r,e.configuration),e.setCredentialChangeListener(e=>uF(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,r)=>uF(t.remoteStore,r)),e._onlineComponents=t}async function cO(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){w(ck,"Using user provided OfflineComponentProvider");try{await cL(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===O.FAILED_PRECONDITION||t.code===O.UNIMPLEMENT
7ED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code))throw t;_("Error using user provided cache. Falling back to memory cache: "+t),await cL(e,new cD)}}else w(ck,"Using default OfflineComponentProvider"),await cL(e,new cC(void 0));return e._offlineComponents}async function cF(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(w(ck,"Using user provided OnlineComponentProvider"),await cP(e,e._uninitializedComponentsProvider._online)):(w(ck,"Using default OnlineComponentProvider"),await cP(e,new cV))),e._onlineComponents}async function cM(e){let t=await cF(e),r=t.eventManager;return r.onListen=cs.bind(null,t.syncEngine),r.onUnlisten=cu.bind(null,t.syncEngine),r.onFirstRemoteStoreListen=ca.bind(null,t.syncEngine),r.onLastRemoteStoreUnlisten=cc.bind(null,t.syncEngine),r}function cU(e,t,r,n){let i=new uq(n),s=new u8(t,i,r);return e.asyncQueue.enqueueAndForget(async()=>u2(await cM(e),s)),()=>{i.Aa(),e.asyncQueue.enqueueAndForget(async()=>u4(await cM(e),s))}}function cB(e,t,r={}){let n=new nc;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,r,n,i){let s=new uq({next:o=>{s.Aa(),t.enqueueAndForget(()=>u4(e,a));let l=o.docs.has(r);!l&&o.fromCache?i.reject(new F(O.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&o.fromCache&&n&&"server"===n.source?i.reject(new F(O.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.)')):i.resolve(o)},error:e=>i.reject(e)}),a=new u8(t5(r.path),s,{includeMetadataChanges:!0,waitForSyncWhenOnline:!0});return u2(e,a)})(await cM(e),e.asyncQueue,t,r,n)),n.promise}function cq(e,t,r={}){let n=new nc;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,r,n,i){let s=new uq({next:r=>{s.Aa(),t.enqueueAndForget(()=>u4(e,a)),r.fromCache&&"server"===n.source?i.reject(new F(O.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.)')):i.resolve(r)},error:e=>i.reject(e)}),a=new u8(r instanceof ss?function(e,t){let r=function(e){let t=!1,r=[];for(let n of e)if(n instanceof sr)if(t=!0,n.orderings.some(e=>e.expr instanceof i$&&e.expr.fieldName===M))r.push(n);else{let e=n.orderings.map(e=>e);e.push(ij(M).ascending()),r.push(new sr(e,{}))}else n instanceof i7&&(t||(r.push(new sr([ij(M).ascending()],{})),t=!0)),r.push(n);return t||r.push(new sr([ij(M).ascending()],{})),r}(e.stages);if(e.userDataReader){let t=e.userDataReader.createContext(3,"toCorePipeline");r.forEach(e=>e._readUserData(t))}return new aL(e.userDataReader.serializer,r,void 0)}(r):r,s,{includeMetadataChanges:!0,waitForSyncWhenOnline:!0});return u2(e,a)})(await cM(e),e.asyncQueue,t,r,n)),n.promise}function cz(e,t){let r=new nc;return e.asyncQueue.enqueueAndForget(async()=>ch(await cF(e).then(e=>e.syncEngine),t,r)),r.promise}let c$="AsyncQueue";class cj{constructor(e=Promise.resolve()){this.Wc=[],this.Qc=!1,this.Gc=[],this.zc=null,this.jc=!1,this.Hc=!1,this.Jc=[],this.jt=new nk(this,"async_queue_retry"),this.Yc=()=>{let e=uH();e&&w(c$,"Visibility state changed to "+e.visibilityState),this.jt.qt()},this.Zc=e;let t=uH();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Yc)}get isShuttingDown(){return this.Qc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Xc(),this.el(e)}enterRestrictedMode(e){if(!this.Qc){this.Qc=!0,this.Hc=e||!1;let t=uH();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Yc)}}enqueue(e){if(this.Xc(),this.Qc)return new Promise(()=>{});let t=new nc;return this.el(()=>this.Qc&&this.Hc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Wc.push(e),this.tl()))}async tl(){if(0!==this.Wc.length){try{await this.Wc[0](),this.Wc.shift(),this.jt.reset()}catch(e){if(!nZ(e))throw e;w(c$,"Operation failed with retryable error: "+e)}this.Wc.length>0&&this.jt.Ut(()=>this.tl())}}el(e){let t=this.Zc.then(()=>(this.jc=!0,e().catch(e=>{throw this.zc=e,this.jc=!1,v("INTERNAL UNHANDLED ERROR: ",cK(e)),e}).then(e=>(this.jc=!1,e))));return this.Zc=t,t}enqueueAfterDelay(e,t,r){this.Xc(),this.Jc.indexOf(e)>-1&&(t=0);let n=uz.createAndSchedule(this,e,t,r,e=>this.nl(e));return this.Gc.push(n),n}Xc(){this.zc&&E(47125,{rl:cK(this.zc)})}verifyOperationInProgress(){}async il(){let e;do e=this.Zc,await e;while(e!==this.Zc)}sl(e){for(let t of this.Gc)if(t.timerId===e)return!0;return!1}_l(e){return this.il().then(()=>{for(let t of(this.Gc.sort((e,t)=>
7e.targetTimeMs-t.targetTimeMs),this.Gc))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.il()})}ol(e){this.Jc.push(e)}nl(e){let t=this.Gc.indexOf(e);this.Gc.splice(t,1)}}function cK(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}class cG extends it{constructor(e,t,r,n){super(e,t,r,n),this.type="firestore",this._queue=new cj,this._persistenceKey=n?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new cj(e),this._firestoreClient=void 0,await e}}}function cQ(e,t){let r="object"==typeof e?e:(0,a.Sx)(),n=(0,a.j6)(r,"firestore").getImmediate({identifier:"string"==typeof e?e:t||ey});if(!n._initialized){let e=(0,o.yU)("firestore");e&&function(e,t,r,n={}){e=Z(e,it);let i=(0,o.zJ)(t),s=e._getSettings(),a={...s,emulatorOptions:e._getEmulatorOptions()},l=`${t}:${r}`;i&&(0,o.gE)(`https://${l}`),s.host!==n7&&s.host!==l&&_("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let u={...s,host:l,ssl:i,emulatorOptions:n};if(!(0,o.bD)(u,a)&&(e._setSettings(u),n.mockUserToken)){let t,r;if("string"==typeof n.mockUserToken)t=n.mockUserToken,r=nu.MOCK_USER;else{t=(0,o.Fy)(n.mockUserToken,e._app?.options.projectId);let i=n.mockUserToken.sub||n.mockUserToken.user_id;if(!i)throw new F(O.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");r=new nu(i)}e._authCredentials=new nf(new nh(t,r))}}(n,...e)}return n}function cW(e){if(e._terminated)throw new F(O.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||cH(e),e._firestoreClient}function cH(e){var t,r,n,i;let s=e._freezeSettings(),a=(t=e._databaseId,r=e._app?.options.appId||"",n=e._persistenceKey,i=e._app?.options.apiKey,new eg(t,r,n,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,nv(s.experimentalLongPollingOptions),s.useFetchStreams,s.isUsingEmulator,i,s._customHeaders,s.grpcFlowControlWindow));e._componentsProvider||s.localCache?._offlineComponentProvider&&s.localCache?._onlineComponentProvider&&(e._componentsProvider={_offline:s.localCache._offlineComponentProvider,_online:s.localCache._onlineComponentProvider}),e._firestoreClient=new cR(e._authCredentials,e._appCheckCredentials,e._queue,a,e._componentsProvider&&function(e){let t=e?._online.build();return{_offline:e?._offline.build(t),_online:t}}(e._componentsProvider))}function cY(e,t){_("enableIndexedDbPersistence() will be deprecated
7in the future, you can use `FirestoreSettings.cache` instead.");let r=e._freezeSettings();return function(e,t,r){if((e=Z(e,cG))._firestoreClient||e._terminated)throw new F(O.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new F(O.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:r},cH(e)}(e,cV.provider,{build:e=>new cA(e,r.cacheSizeBytes,t?.forceOwnership)}),Promise.resolve()}class cX{convertValue(e,t="none"){switch(eC(e)){case 0:return null;case 1:return e.booleanValue;case 2:return eo(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(el(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 E(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let r={};return K(e,(e,n)=>{r[e]=this.convertValue(n,t)}),r}convertVectorValue(e){return new il(e.fields?.[eI].arrayValue?.values?.map(e=>eo(e.doubleValue)))}convertGeoPoint(e){return new nl(eo(e.latitude),eo(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let r=em(e);return null==r?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(ep(e));default:return null}}convertTimestamp(e){let t=ea(e);return new er(t.seconds,t.nanos)}convertDocumentKey(e,t){let r=B.fromString(e);T(ne(r),9688,{name:e});let n=new ew(r.get(1),r.get(3)),i=new Q(r.popFirst(5));return n.isEqual(t)||v(`Document ${i} 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.`),i}}class cJ extends cX{constructor(e){super(),this.firestore=e}convertBytes(e){return new ns(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new ii(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.