(window.webpackJsonp_N_E=window.webpackJsonp_N_E||[]).push([[38],{CCl1:function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return Vi})),n.d(t,"b",(function(){return Oi})),n.d(t,"c",(function(){return Do})),n.d(t,"d",(function(){return Ui})),n.d(t,"e",(function(){return vo})),n.d(t,"f",(function(){return Ro})),n.d(t,"g",(function(){return yo})),n.d(t,"h",(function(){return ho})),n.d(t,"i",(function(){return mo}));var r=n("WJvL"),s=n("IuUc"),i=n("5pEQ"),o=n("H9WU"),a=n("nEQb");const u="@firebase/firestore";class c{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}}c.UNAUTHENTICATED=new c(null),c.GOOGLE_CREDENTIALS=new c("google-credentials-uid"),c.FIRST_PARTY=new c("first-party-uid"),c.MOCK_USER=new c("mock-user");let l="10.5.2";const h=new i.b("@firebase/firestore");function d(){return h.logLevel}function f(e,...t){if(h.logLevel<=i.a.DEBUG){const n=t.map(p);h.debug(`Firestore (${l}): ${e}`,...n)}}function m(e,...t){if(h.logLevel<=i.a.ERROR){const n=t.map(p);h.error(`Firestore (${l}): ${e}`,...n)}}function g(e,...t){if(h.logLevel<=i.a.WARN){const n=t.map(p);h.warn(`Firestore (${l}): ${e}`,...n)}}function p(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function y(e="Unexpected state"){const t=`FIRESTORE (${l}) INTERNAL ASSERTION FAILED: `+e;throw m(t),new Error(t)}function w(e,t){e||y()}function v(e,t){return e}const _={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 E extends o.c{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class T{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class I{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class C{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(c.UNAUTHENTICATED)))}shutdown(){}}class A{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 S{constructor(e){this.t=e,this.currentUser=c.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let s=new T;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new T,e.enqueueRetryable((()=>r(this.currentUser)))};const i=()=>{const t=s;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},o=e=>{f("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),i()};this.t.onInit((e=>o(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(f("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new T)}}),0),i()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(f("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new I(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){const e=this.auth&&this.auth.getUid();return w(null===e||"string"==typeof e),new c(e)}}class N{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=c.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);const e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class b{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new N(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable((()=>t(c.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class D{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 k{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,t){const n=e=>{null!=e.error&&f("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const n=e.token!==this.R;return this.R=e.token,f("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{f("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit((e=>r(e))),setTimeout((()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?r(e):f("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(w("string"==typeof e.token),this.R=e.token,new D(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}function R(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let r=0;rt?1:0}function V(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}class O{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new E(_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new E(_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new E(_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new E(_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return O.fromMillis(Date.now())}static fromDate(e){return O.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new O(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?L(this.nanoseconds,e.nanoseconds):L(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class M{constructor(e){this.timestamp=e}static fromTimestamp(e){return new M(e)}static min(){return new M(new O(0,0))}static max(){return new M(new O(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class F{constructor(e,t,n){void 0===t?t=0:t>e.length&&y(),void 0===n?n=e.length-t:n>e.length-t&&y(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===F.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof F?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.lengths)return 1}return e.lengtht.length?1:0}}class P extends F{construct(e,t,n){return new P(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new E(_.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new P(t)}static emptyPath(){return new P([])}}const U=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class q extends F{construct(e,t,n){return new q(e,t,n)}static isValidIdentifier(e){return U.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),q.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new q(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const s=()=>{if(0===n.length)throw new E(_.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;r=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===P.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return P.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new B(new P(e.slice()))}}class ${constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}$.UNKNOWN_ID=-1;function z(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,s=M.fromTimestamp(1e9===r?new O(n+1,0):new O(n,r));return new K(s,B.empty(),t)}function G(e){return new K(e.readTime,e.key,-1)}class K{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new K(M.min(),B.empty(),-1)}static max(){return new K(M.max(),B.empty(),-1)}}function Q(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=B.comparator(e.documentKey,t.documentKey),0!==n?n:L(e.largestBatchId,t.largestBatchId))}const j="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class H{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function W(e){if(e.code!==_.FAILED_PRECONDITION||e.message!==j)throw e;f("LocalStore","Unexpectedly lost primary lease")}class Y{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&&y(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new Y(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof Y?t:Y.resolve(t)}catch(e){return Y.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):Y.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):Y.reject(t)}static resolve(e){return new Y(((t,n)=>{t(e)}))}static reject(e){return new Y(((t,n)=>{n(e)}))}static waitFor(e){return new Y(((t,n)=>{let r=0,s=0,i=!1;e.forEach((e=>{++r,e.next((()=>{++s,i&&s===r&&t()}),(e=>n(e)))})),i=!0,s===r&&t()}))}static or(e){let t=Y.resolve(!1);for(const n of e)t=t.next((e=>e?Y.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}static mapArray(e,t){return new Y(((n,r)=>{const s=e.length,i=new Array(s);let o=0;for(let a=0;a{i[u]=e,++o,o===s&&n(i)}),(e=>r(e)))}}))}static doWhile(e,t){return new Y(((n,r)=>{const s=()=>{!0===e()?t().next((()=>{s()}),r):n()};s()}))}}function X(e){return"IndexedDbTransactionError"===e.name}class J{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.se(e),this.oe=e=>t.writeSequenceNumber(e))}se(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.oe&&this.oe(e),e}}function Z(e){return null==e}function ee(e){return 0===e&&1/e==-1/0}function te(e){return"number"==typeof e&&Number.isInteger(e)&&!ee(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}J._e=-1;const ne=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],re=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],se=re;function ie(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function oe(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function ae(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ue{constructor(e,t){this.comparator=e,this.root=t||le.EMPTY}insert(e,t){return new ue(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,le.BLACK,null,null))}remove(e){return new ue(this.comparator,this.root.remove(e,this.comparator).copy(null,null,le.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new ce(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new ce(this.root,e,this.comparator,!1)}getReverseIterator(){return new ce(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new ce(this.root,e,this.comparator,!0)}}class ce{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class le{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:le.RED,this.left=null!=r?r:le.EMPTY,this.right=null!=s?s:le.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new le(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=s?s:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const s=n(e,r.key);return r=s<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===s?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return le.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return le.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,le.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,le.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw y();if(this.right.isRed())throw y();const e=this.left.check();if(e!==this.right.check())throw y();return e+(this.isRed()?0:1)}}le.EMPTY=null,le.RED=!0,le.BLACK=!1,le.EMPTY=new class{constructor(){this.size=0}get key(){throw y()}get value(){throw y()}get color(){throw y()}get left(){throw y()}get right(){throw y()}copy(e,t,n,r,s){return this}insert(e,t,n){return new le(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 he{constructor(e){this.comparator=e,this.data=new ue(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new de(this.data.getIterator())}getIteratorFrom(e){return new de(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size{t=t.add(e)})),t}isEqual(e){if(!(e instanceof he))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new he(this.comparator);return t.data=e,t}}class de{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class fe{constructor(e){this.fields=e,e.sort(q.comparator)}static empty(){return new fe([])}unionWith(e){let t=new he(q.comparator);for(const n of this.fields)t=t.add(n);for(const n of e)t=t.add(n);return new fe(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return V(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class me extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ge{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new me("Invalid base64 string: "+e):e}}(e);return new ge(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;neNe(e,t)))}function De(e,t){if(e===t)return 0;const n=Se(e),r=Se(t);if(n!==r)return L(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return L(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=we(e.integerValue||e.doubleValue),r=we(t.integerValue||t.doubleValue);return nr?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return ke(e.timestampValue,t.timestampValue);case 4:return ke(Te(e),Te(t));case 5:return L(e.stringValue,t.stringValue);case 6:return function(e,t){const n=ve(e),r=ve(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let s=0;st.mapValue.fields[e]=Ue(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Ue(e.arrayValue.values[n]);return t}return Object.assign({},e)}function qe(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}class Be{constructor(e){this.value=e}static empty(){return new Be({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n{if(!t.isImmediateParentOf(s)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=s.popLast()}e?n[s.lastSegment()]=Ue(e):r.push(s.lastSegment())}));const s=this.getFieldsMap(t);this.applyChanges(s,n,r)}delete(e){const t=this.field(e.popLast());Pe(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ne(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;ne[t]=n));for(const r of n)delete e[r]}clone(){return new Be(Ue(this.value))}}class $e{constructor(e,t,n,r,s,i,o){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=s,this.data=i,this.documentState=o}static newInvalidDocument(e){return new $e(e,0,M.min(),M.min(),M.min(),Be.empty(),0)}static newFoundDocument(e,t,n,r){return new $e(e,1,t,M.min(),n,r,0)}static newNoDocument(e,t){return new $e(e,2,t,M.min(),M.min(),Be.empty(),0)}static newUnknownDocument(e,t){return new $e(e,3,t,M.min(),M.min(),Be.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(M.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=Be.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Be.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=M.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 $e&&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 $e(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class ze{constructor(e,t){this.position=e,this.inclusive=t}}function Ge(e,t,n){let r=0;for(let s=0;s":return e>0;case">=":return e>=0;default:return y()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class Ye extends He{constructor(e,t){super(),this.filters=e,this.op=t,this.ue=null}static create(e,t){return new Ye(e,t)}matches(e){return Xe(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.ue||(this.ue=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.ue}getFilters(){return Object.assign([],this.filters)}}function Xe(e){return"and"===e.op}function Je(e){return Ze(e)&&Xe(e)}function Ze(e){for(const t of e.filters)if(t instanceof Ye)return!1;return!0}function et(e){if(e instanceof We)return e.field.canonicalString()+e.op.toString()+Re(e.value);if(Je(e))return e.filters.map((e=>et(e))).join(",");{const t=e.filters.map((e=>et(e))).join(",");return`${e.op}(${t})`}}function tt(e,t){return e instanceof We?function(e,t){return t instanceof We&&e.op===t.op&&e.field.isEqual(t.field)&&Ne(e.value,t.value)}(e,t):e instanceof Ye?function(e,t){return t instanceof Ye&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,r)=>e&&tt(n,t.filters[r])),!0)}(e,t):void y()}function nt(e){return e instanceof We?function(e){return`${e.field.canonicalString()} ${e.op} ${Re(e.value)}`}(e):e instanceof Ye?function(e){return e.op.toString()+" {"+e.getFilters().map(nt).join(" ,")+"}"}(e):"Filter"}class rt extends We{constructor(e,t,n){super(e,t,n),this.key=B.fromName(n.referenceValue)}matches(e){const t=B.comparator(e.key,this.key);return this.matchesComparison(t)}}class st extends We{constructor(e,t){super(e,"in",t),this.keys=ot("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class it extends We{constructor(e,t){super(e,"not-in",t),this.keys=ot("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function ot(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>B.fromName(e.referenceValue)))}class at extends We{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Oe(t)&&be(t.arrayValue,this.value)}}class ut extends We{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&be(this.value.arrayValue,t)}}class ct extends We{constructor(e,t){super(e,"not-in",t)}matches(e){if(be(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!be(this.value.arrayValue,t)}}class lt extends We{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Oe(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>be(this.value.arrayValue,e)))}}class ht{constructor(e,t=null,n=[],r=[],s=null,i=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=o,this.ce=null}}function dt(e,t=null,n=[],r=[],s=null,i=null,o=null){return new ht(e,t,n,r,s,i,o)}function ft(e){const t=v(e);if(null===t.ce){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>et(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),Z(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Re(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Re(e))).join(",")),t.ce=e}return t.ce}function mt(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc";(function(e){let t=new he(q.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(t=t.add(e.field))}))})),t})(t).forEach((r=>{e.has(r.canonicalString())||r.isKeyField()||t.le.push(new Qe(r,n))})),e.has(q.keyField().canonicalString())||t.le.push(new Qe(q.keyField(),n))}return t.le}function Tt(e){const t=v(e);return t.he||(t.he=It(t,Et(e))),t.he}function It(e,t){if("F"===e.limitType)return dt(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map((e=>{const t="desc"===e.dir?"asc":"desc";return new Qe(e.field,t)}));const n=e.endAt?new ze(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new ze(e.startAt.position,e.startAt.inclusive):null;return dt(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function Ct(e,t){const n=e.filters.concat([t]);return new pt(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function At(e,t,n){return new pt(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function St(e,t){return mt(Tt(e),Tt(t))&&e.limitType===t.limitType}function Nt(e){return`${ft(Tt(e))}|lt:${e.limitType}`}function bt(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>nt(e))).join(", ")}]`),Z(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Re(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Re(e))).join(",")),`Target(${t})`}(Tt(e))}; limitType=${e.limitType})`}function Dt(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):B.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of Et(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=Ge(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,Et(e),t))&&!(e.endAt&&!function(e,t,n){const r=Ge(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Et(e),t))}(e,t)}function kt(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Rt(e){return(t,n)=>{let r=!1;for(const s of Et(e)){const e=xt(s,t,n);if(0!==e)return e;r=r||s.field.isKeyField()}return 0}}function xt(e,t,n){const r=e.field.isKeyField()?B.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),s=n.data.field(e);return null!==r&&null!==s?De(r,s):y()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return y()}}class Lt{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[r,s]of n)if(this.equalsFn(r,e))return s}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let s=0;s{for(const[r,s]of n)e(r,s)}))}isEmpty(){return ae(this.inner)}size(){return this.innerSize}}const Vt=new ue(B.comparator);function Ot(){return Vt}const Mt=new ue(B.comparator);function Ft(...e){let t=Mt;for(const n of e)t=t.insert(n.key,n);return t}function Pt(e){let t=Mt;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Ut(){return Bt()}function qt(){return Bt()}function Bt(){return new Lt((e=>e.toString()),((e,t)=>e.isEqual(t)))}new ue(B.comparator);const $t=new he(B.comparator);function zt(...e){let t=$t;for(const n of e)t=t.add(n);return t}const Gt=new he(L);function Kt(){return Gt}function Qt(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:ee(t)?"-0":t}}function jt(e){return{integerValue:""+e}}function Ht(e,t){return te(t)?jt(t):Qt(e,t)}class Wt{constructor(){this._=void 0}}function Yt(e,t,n){return e instanceof Zt?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&_e(t)&&(t=Ee(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof en?tn(e,t):e instanceof nn?rn(e,t):function(e,t){const n=Jt(e,t),r=on(n)+on(e.Ie);return Ve(n)&&Ve(e.Ie)?jt(r):Qt(e.serializer,r)}(e,t)}function Xt(e,t,n){return e instanceof en?tn(e,t):e instanceof nn?rn(e,t):n}function Jt(e,t){return e instanceof sn?function(e){return Ve(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class Zt extends Wt{}class en extends Wt{constructor(e){super(),this.elements=e}}function tn(e,t){const n=an(t);for(const r of e.elements)n.some((e=>Ne(e,r)))||n.push(r);return{arrayValue:{values:n}}}class nn extends Wt{constructor(e){super(),this.elements=e}}function rn(e,t){let n=an(t);for(const r of e.elements)n=n.filter((e=>!Ne(e,r)));return{arrayValue:{values:n}}}class sn extends Wt{constructor(e,t){super(),this.serializer=e,this.Ie=t}}function on(e){return we(e.integerValue||e.doubleValue)}function an(e){return Oe(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class un{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new un}static exists(e){return new un(void 0,e)}static updateTime(e){return new un(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 cn(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class ln{}function hn(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new _n(e.key,un.none()):new gn(e.key,e.data,un.none());{const n=e.data,r=Be.empty();let s=new he(q.comparator);for(let e of t.fields)if(!s.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),s=s.add(e)}return new pn(e.key,r,new fe(s.toArray()),un.none())}}function dn(e,t,n){e instanceof gn?function(e,t,n){const r=e.value.clone(),s=wn(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof pn?function(e,t,n){if(!cn(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=wn(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(yn(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function fn(e,t,n,r){return e instanceof gn?function(e,t,n,r){if(!cn(e.precondition,t))return n;const s=e.value.clone(),i=vn(e.fieldTransforms,r,t);return s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null}(e,t,n,r):e instanceof pn?function(e,t,n,r){if(!cn(e.precondition,t))return n;const s=vn(e.fieldTransforms,r,t),i=t.data;return i.setAll(yn(e)),i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,r):function(e,t,n){return cn(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function mn(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&V(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof en&&t instanceof en||e instanceof nn&&t instanceof nn?V(e.elements,t.elements,Ne):e instanceof sn&&t instanceof sn?Ne(e.Ie,t.Ie):e instanceof Zt&&t instanceof Zt}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class gn extends ln{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class pn extends ln{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}getFieldMask(){return this.fieldMask}}function yn(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function wn(e,t,n){const r=new Map;w(e.length===n.length);for(let s=0;s{const s=e.get(r.key),i=s.overlayedDocument;let o=this.applyToLocalView(i,s.mutatedFields);o=t.has(r.key)?null:o;const a=hn(i,o);null!==a&&n.set(r.key,a),i.isValidDocument()||i.convertToNoDocument(M.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),zt())}isEqual(e){return this.batchId===e.batchId&&V(this.mutations,e.mutations,((e,t)=>mn(e,t)))&&V(this.baseMutations,e.baseMutations,((e,t)=>mn(e,t)))}}class Tn{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class In{constructor(e,t){this.count=e,this.unchangedNames=t}}var Cn,An;function Sn(e){if(void 0===e)return m("GRPC error has no .code"),_.UNKNOWN;switch(e){case Cn.OK:return _.OK;case Cn.CANCELLED:return _.CANCELLED;case Cn.UNKNOWN:return _.UNKNOWN;case Cn.DEADLINE_EXCEEDED:return _.DEADLINE_EXCEEDED;case Cn.RESOURCE_EXHAUSTED:return _.RESOURCE_EXHAUSTED;case Cn.INTERNAL:return _.INTERNAL;case Cn.UNAVAILABLE:return _.UNAVAILABLE;case Cn.UNAUTHENTICATED:return _.UNAUTHENTICATED;case Cn.INVALID_ARGUMENT:return _.INVALID_ARGUMENT;case Cn.NOT_FOUND:return _.NOT_FOUND;case Cn.ALREADY_EXISTS:return _.ALREADY_EXISTS;case Cn.PERMISSION_DENIED:return _.PERMISSION_DENIED;case Cn.FAILED_PRECONDITION:return _.FAILED_PRECONDITION;case Cn.ABORTED:return _.ABORTED;case Cn.OUT_OF_RANGE:return _.OUT_OF_RANGE;case Cn.UNIMPLEMENTED:return _.UNIMPLEMENTED;case Cn.DATA_LOSS:return _.DATA_LOSS;default:return y()}}(An=Cn||(Cn={}))[An.OK=0]="OK",An[An.CANCELLED=1]="CANCELLED",An[An.UNKNOWN=2]="UNKNOWN",An[An.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",An[An.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",An[An.NOT_FOUND=5]="NOT_FOUND",An[An.ALREADY_EXISTS=6]="ALREADY_EXISTS",An[An.PERMISSION_DENIED=7]="PERMISSION_DENIED",An[An.UNAUTHENTICATED=16]="UNAUTHENTICATED",An[An.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",An[An.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",An[An.ABORTED=10]="ABORTED",An[An.OUT_OF_RANGE=11]="OUT_OF_RANGE",An[An.UNIMPLEMENTED=12]="UNIMPLEMENTED",An[An.INTERNAL=13]="INTERNAL",An[An.UNAVAILABLE=14]="UNAVAILABLE",An[An.DATA_LOSS=15]="DATA_LOSS";let Nn=null;function bn(){return new TextEncoder}const Dn=new a.e([4294967295,4294967295],0);function kn(e){const t=bn().encode(e),n=new a.f;return n.update(t),new Uint8Array(n.digest())}function Rn(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),s=t.getUint32(8,!0),i=t.getUint32(12,!0);return[new a.e([n,r],0),new a.e([s,i],0)]}class xn{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Ln(`Invalid padding: ${t}`);if(n<0)throw new Ln(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new Ln(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Ln(`Invalid padding when bitmap length is 0: ${t}`);this.Te=8*e.length-t,this.Ee=a.e.fromNumber(this.Te)}de(e,t,n){let r=e.add(t.multiply(a.e.fromNumber(n)));return 1===r.compare(Dn)&&(r=new a.e([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Ee).toNumber()}Ae(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<i.insert(e))),i}insert(e){if(0===this.Te)return;const t=kn(e),[n,r]=Rn(t);for(let s=0;s0&&(this.Se=!0,this.ye=e)}ve(){let e=zt(),t=zt(),n=zt();return this.pe.forEach(((r,s)=>{switch(s){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:y()}})),new On(this.ye,this.we,e,t,n)}Fe(){this.Se=!1,this.pe=$n()}Me(e,t){this.Se=!0,this.pe=this.pe.insert(e,t)}xe(e){this.Se=!0,this.pe=this.pe.remove(e)}Oe(){this.ge+=1}Ne(){this.ge-=1}Be(){this.Se=!0,this.we=!0}}class qn{constructor(e){this.Le=e,this.ke=new Map,this.qe=Ot(),this.Qe=Bn(),this.Ke=new ue(L)}$e(e){for(const t of e.Ve)e.me&&e.me.isFoundDocument()?this.Ue(t,e.me):this.We(t,e.key,e.me);for(const t of e.removedTargetIds)this.We(t,e.key,e.me)}Ge(e){this.forEachTarget(e,(t=>{const n=this.ze(t);switch(e.state){case 0:this.je(t)&&n.Ce(e.resumeToken);break;case 1:n.Ne(),n.be||n.Fe(),n.Ce(e.resumeToken);break;case 2:n.Ne(),n.be||this.removeTarget(t);break;case 3:this.je(t)&&(n.Be(),n.Ce(e.resumeToken));break;case 4:this.je(t)&&(this.He(t),n.Ce(e.resumeToken));break;default:y()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ke.forEach(((e,n)=>{this.je(n)&&t(n)}))}Je(e){const t=e.targetId,n=e.fe.count,r=this.Ye(t);if(r){const s=r.target;if(gt(s))if(0===n){const e=new B(s.path);this.We(t,e,$e.newNoDocument(e,M.min()))}else w(1===n);else{const r=this.Ze(t);if(r!==n){const n=this.Xe(e),s=n?this.et(n,e,r):1;if(0!==s){this.He(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}null==Nn||Nn.tt(function(e,t,n,r,s){var i,o,a,u,c,l;const h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===s,hashCount:null!==(i=null==d?void 0:d.hashCount)&&void 0!==i?i:0,bitmapLength:null!==(u=null===(a=null===(o=null==d?void 0:d.bits)||void 0===o?void 0:o.bitmap)||void 0===a?void 0:a.length)&&void 0!==u?u:0,padding:null!==(l=null===(c=null==d?void 0:d.bits)||void 0===c?void 0:c.padding)&&void 0!==l?l:0,mightContain:e=>{var t;return null!==(t=null==r?void 0:r.mightContain(e))&&void 0!==t&&t}}),h}(r,e.fe,this.Le.nt(),n,s))}}}}Xe(e){const t=e.fe.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:r=0},hashCount:s=0}=t;let i,o;try{i=ve(n).toUint8Array()}catch(e){if(e instanceof me)return g("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{o=new xn(i,r,s)}catch(e){return g(e instanceof Ln?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===o.Te?null:o}et(e,t,n){return t.fe.count===n-this.rt(e,t.targetId)?0:2}rt(e,t){const n=this.Le.getRemoteKeysForTarget(t);let r=0;return n.forEach((n=>{const s=this.Le.nt(),i=`projects/${s.projectId}/databases/${s.database}/documents/${n.path.canonicalString()}`;e.mightContain(i)||(this.We(t,n,null),r++)})),r}it(e){const t=new Map;this.ke.forEach(((n,r)=>{const s=this.Ye(r);if(s){if(n.current&>(s.target)){const t=new B(s.target.path);null!==this.qe.get(t)||this.st(r,t)||this.We(r,t,$e.newNoDocument(t,e))}n.De&&(t.set(r,n.ve()),n.Fe())}}));let n=zt();this.Qe.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))})),this.qe.forEach(((t,n)=>n.setReadTime(e)));const r=new Vn(e,t,this.Ke,this.qe,n);return this.qe=Ot(),this.Qe=Bn(),this.Ke=new ue(L),r}Ue(e,t){if(!this.je(e))return;const n=this.st(e,t.key)?2:0;this.ze(e).Me(t.key,n),this.qe=this.qe.insert(t.key,t),this.Qe=this.Qe.insert(t.key,this.ot(t.key).add(e))}We(e,t,n){if(!this.je(e))return;const r=this.ze(e);this.st(e,t)?r.Me(t,1):r.xe(t),this.Qe=this.Qe.insert(t,this.ot(t).delete(e)),n&&(this.qe=this.qe.insert(t,n))}removeTarget(e){this.ke.delete(e)}Ze(e){const t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Oe(e){this.ze(e).Oe()}ze(e){let t=this.ke.get(e);return t||(t=new Un,this.ke.set(e,t)),t}ot(e){let t=this.Qe.get(e);return t||(t=new he(L),this.Qe=this.Qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||f("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){const t=this.ke.get(e);return t&&t.be?null:this.Le._t(e)}He(e){this.ke.set(e,new Un),this.Le.getRemoteKeysForTarget(e).forEach((t=>{this.We(e,t,null)}))}st(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function Bn(){return new ue(B.comparator)}function $n(){return new ue(B.comparator)}const zn={asc:"ASCENDING",desc:"DESCENDING"},Gn={"<":"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"},Kn={and:"AND",or:"OR"};class Qn{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function jn(e,t){return e.useProto3Json||Z(t)?t:{value:t}}function Hn(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 Wn(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function Yn(e){return w(!!e),M.fromTimestamp(function(e){const t=ye(e);return new O(t.seconds,t.nanos)}(e))}function Xn(e,t){return function(e){return new P(["projects",e.projectId,"databases",e.database])}(e).child("documents").child(t).canonicalString()}function Jn(e){const t=P.fromString(e);return w(mr(t)),t}function Zn(e,t){const n=Jn(t);if(n.get(1)!==e.databaseId.projectId)throw new E(_.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new E(_.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new B(rr(n))}function er(e,t){return Xn(e.databaseId,t)}function tr(e){const t=Jn(e);return 4===t.length?P.emptyPath():rr(t)}function nr(e){return new P(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function rr(e){return w(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function sr(e,t){return{documents:[er(e,t.path)]}}function ir(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=er(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=er(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);const s=function(e){if(0!==e.length)return fr(Ye.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);const i=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:hr(e.field),direction:ur(e.dir)}}(e)))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);const o=jn(e,t.limit);return null!==o&&(n.structuredQuery.limit=o),t.startAt&&(n.structuredQuery.startAt=function(e){return{before:e.inclusive,values:e.position}}(t.startAt)),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),n}function or(e){let t=tr(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(r>0){w(1===r);const e=n.from[0];e.allDescendants?s=e.collectionId:t=t.child(e.collectionId)}let i=[];n.where&&(i=function(e){const t=ar(e);return t instanceof Ye&&Je(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=function(e){return e.map((e=>function(e){return new Qe(dr(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(n.orderBy));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,Z(t)?null:t}(n.limit));let u=null;n.startAt&&(u=function(e){const t=!!e.before,n=e.values||[];return new ze(n,t)}(n.startAt));let c=null;return n.endAt&&(c=function(e){const t=!e.before,n=e.values||[];return new ze(n,t)}(n.endAt)),yt(t,s,o,i,a,"F",u,c)}function ar(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=dr(e.unaryFilter.field);return We.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=dr(e.unaryFilter.field);return We.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=dr(e.unaryFilter.field);return We.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const s=dr(e.unaryFilter.field);return We.create(s,"!=",{nullValue:"NULL_VALUE"});default:return y()}}(e):void 0!==e.fieldFilter?function(e){return We.create(dr(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return y()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return Ye.create(e.compositeFilter.filters.map((e=>ar(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return y()}}(e.compositeFilter.op))}(e):y()}function ur(e){return zn[e]}function cr(e){return Gn[e]}function lr(e){return Kn[e]}function hr(e){return{fieldPath:e.canonicalString()}}function dr(e){return q.fromServerFormat(e.fieldPath)}function fr(e){return e instanceof We?function(e){if("=="===e.op){if(Fe(e.value))return{unaryFilter:{field:hr(e.field),op:"IS_NAN"}};if(Me(e.value))return{unaryFilter:{field:hr(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Fe(e.value))return{unaryFilter:{field:hr(e.field),op:"IS_NOT_NAN"}};if(Me(e.value))return{unaryFilter:{field:hr(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:hr(e.field),op:cr(e.op),value:e.value}}}(e):e instanceof Ye?function(e){const t=e.getFilters().map((e=>fr(e)));return 1===t.length?t[0]:{compositeFilter:{op:lr(e.op),filters:t}}}(e):y()}function mr(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class gr{constructor(e,t,n,r,s=M.min(),i=M.min(),o=ge.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new gr(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new gr(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new gr(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new gr(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class pr{constructor(e){this.ut=e}}function yr(e){const t=or({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?At(t,t.limit,"L"):t}class wr{constructor(){}ht(e,t){this.Pt(e,t),t.It()}Pt(e,t){if("nullValue"in e)this.Tt(t,5);else if("booleanValue"in e)this.Tt(t,10),t.Et(e.booleanValue?1:0);else if("integerValue"in e)this.Tt(t,15),t.Et(we(e.integerValue));else if("doubleValue"in e){const n=we(e.doubleValue);isNaN(n)?this.Tt(t,13):(this.Tt(t,15),ee(n)?t.Et(0):t.Et(n))}else if("timestampValue"in e){const n=e.timestampValue;this.Tt(t,20),"string"==typeof n?t.dt(n):(t.dt(`${n.seconds||""}`),t.Et(n.nanos||0))}else if("stringValue"in e)this.At(e.stringValue,t),this.Rt(t);else if("bytesValue"in e)this.Tt(t,30),t.Vt(ve(e.bytesValue)),this.Rt(t);else if("referenceValue"in e)this.ft(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.Tt(t,45),t.Et(n.latitude||0),t.Et(n.longitude||0)}else"mapValue"in e?qe(e)?this.Tt(t,Number.MAX_SAFE_INTEGER):(this.gt(e.mapValue,t),this.Rt(t)):"arrayValue"in e?(this.yt(e.arrayValue,t),this.Rt(t)):y()}At(e,t){this.Tt(t,25),this.wt(e,t)}wt(e,t){t.dt(e)}gt(e,t){const n=e.fields||{};this.Tt(t,55);for(const r of Object.keys(n))this.At(r,t),this.Pt(n[r],t)}yt(e,t){const n=e.values||[];this.Tt(t,50);for(const r of n)this.Pt(r,t)}ft(e,t){this.Tt(t,37),B.fromName(e).path.forEach((e=>{this.Tt(t,60),this.wt(e,t)}))}Tt(e,t){e.Et(t)}Rt(e){e.Et(2)}}wr.St=new wr;class vr{constructor(){this.on=new _r}addToCollectionParentIndex(e,t){return this.on.add(t),Y.resolve()}getCollectionParents(e,t){return Y.resolve(this.on.getEntries(t))}addFieldIndex(e,t){return Y.resolve()}deleteFieldIndex(e,t){return Y.resolve()}deleteAllFieldIndexes(e){return Y.resolve()}createTargetIndexes(e,t){return Y.resolve()}getDocumentsMatchingTarget(e,t){return Y.resolve(null)}getIndexType(e,t){return Y.resolve(0)}getFieldIndexes(e,t){return Y.resolve([])}getNextCollectionGroupToUpdate(e){return Y.resolve(null)}getMinOffset(e,t){return Y.resolve(K.min())}getMinOffsetFromCollectionGroup(e,t){return Y.resolve(K.min())}updateCollectionGroup(e,t,n){return Y.resolve()}updateIndexEntries(e,t){return Y.resolve()}}class _r{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new he(P.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new he(P.comparator)).toArray()}}new Uint8Array(0);class Er{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Er(e,Er.DEFAULT_COLLECTION_PERCENTILE,Er.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}Er.DEFAULT_COLLECTION_PERCENTILE=10,Er.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Er.DEFAULT=new Er(41943040,Er.DEFAULT_COLLECTION_PERCENTILE,Er.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Er.DISABLED=new Er(-1,0,0);class Tr{constructor(e){this.xn=e}next(){return this.xn+=2,this.xn}static On(){return new Tr(0)}static Nn(){return new Tr(-1)}}class Ir{constructor(){this.changes=new Lt((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,$e.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?Y.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class Cr{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Ar{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((r=>(n=r,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&fn(n.mutation,e,fe.empty(),O.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,zt()).next((()=>t))))}getLocalViewOfDocuments(e,t,n=zt()){const r=Ut();return this.populateOverlays(e,r,t).next((()=>this.computeViews(e,t,r,n).next((e=>{let t=Ft();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=Ut();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,zt())))}populateOverlays(e,t,n){const r=[];return n.forEach((e=>{t.has(e)||r.push(e)})),this.documentOverlayCache.getOverlays(e,r).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,r){let s=Ot();const i=Bt(),o=Bt();return t.forEach(((e,t)=>{const o=n.get(t.key);r.has(t.key)&&(void 0===o||o.mutation instanceof pn)?s=s.insert(t.key,t):void 0!==o?(i.set(t.key,o.mutation.getFieldMask()),fn(o.mutation,t,o.mutation.getFieldMask(),O.now())):i.set(t.key,fe.empty())})),this.recalculateAndSaveOverlays(e,s).next((e=>(e.forEach(((e,t)=>i.set(e,t))),t.forEach(((e,t)=>{var n;return o.set(e,new Cr(t,null!==(n=i.get(e))&&void 0!==n?n:null))})),o)))}recalculateAndSaveOverlays(e,t){const n=Bt();let r=new ue(((e,t)=>e-t)),s=zt();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const s of e)s.keys().forEach((e=>{const i=t.get(e);if(null===i)return;let o=n.get(e)||fe.empty();o=s.applyToLocalView(i,o),n.set(e,o);const a=(r.get(s.batchId)||zt()).add(e);r=r.insert(s.batchId,a)}))})).next((()=>{const i=[],o=r.getReverseIterator();for(;o.hasNext();){const r=o.getNext(),a=r.key,u=r.value,c=qt();u.forEach((e=>{if(!s.has(e)){const r=hn(t.get(e),n.get(e));null!==r&&c.set(e,r),s=s.add(e)}})),i.push(this.documentOverlayCache.saveOverlays(e,a,c))}return Y.waitFor(i)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n,r){return function(e){return B.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):_t(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next((s=>{const i=r-s.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-s.size):Y.resolve(Ut());let o=-1,a=s;return i.next((t=>Y.forEach(t,((t,n)=>(o{a=a.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,s))).next((()=>this.computeViews(e,a,t,zt()))).next((e=>({batchId:o,changes:Pt(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new B(t)).next((e=>{let t=Ft();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){const s=t.collectionGroup;let i=Ft();return this.indexManager.getCollectionParents(e,s).next((o=>Y.forEach(o,(o=>{const a=function(e,t){return new pt(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,o.child(s));return this.getDocumentsMatchingCollectionQuery(e,a,n,r).next((e=>{e.forEach(((e,t)=>{i=i.insert(e,t)}))}))})).next((()=>i))))}getDocumentsMatchingCollectionQuery(e,t,n,r){let s;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((i=>(s=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,s,r)))).next((e=>{s.forEach(((t,n)=>{const r=n.getKey();null===e.get(r)&&(e=e.insert(r,$e.newInvalidDocument(r)))}));let n=Ft();return e.forEach(((e,r)=>{const i=s.get(e);void 0!==i&&fn(i.mutation,r,fe.empty(),O.now()),Dt(t,r)&&(n=n.insert(e,r))})),n}))}}class Sr{constructor(e){this.serializer=e,this.ur=new Map,this.cr=new Map}getBundleMetadata(e,t){return Y.resolve(this.ur.get(t))}saveBundleMetadata(e,t){return this.ur.set(t.id,function(e){return{id:e.id,version:e.version,createTime:Yn(e.createTime)}}(t)),Y.resolve()}getNamedQuery(e,t){return Y.resolve(this.cr.get(t))}saveNamedQuery(e,t){return this.cr.set(t.name,function(e){return{name:e.name,query:yr(e.bundledQuery),readTime:Yn(e.readTime)}}(t)),Y.resolve()}}class Nr{constructor(){this.overlays=new ue(B.comparator),this.lr=new Map}getOverlay(e,t){return Y.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Ut();return Y.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){return n.forEach(((n,r)=>{this.lt(e,t,r)})),Y.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.lr.get(n);return void 0!==r&&(r.forEach((e=>this.overlays=this.overlays.remove(e))),this.lr.delete(n)),Y.resolve()}getOverlaysForCollection(e,t,n){const r=Ut(),s=t.length+1,i=new B(t.child("")),o=this.overlays.getIteratorFrom(i);for(;o.hasNext();){const e=o.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return Y.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let s=new ue(((e,t)=>e-t));const i=this.overlays.getIterator();for(;i.hasNext();){const e=i.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=s.get(e.largestBatchId);null===t&&(t=Ut(),s=s.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=Ut(),a=s.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach(((e,t)=>o.set(e,t))),!(o.size()>=r)););return Y.resolve(o)}lt(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.lr.get(r.largestBatchId).delete(n.key);this.lr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new Tn(t,n));let s=this.lr.get(t);void 0===s&&(s=zt(),this.lr.set(t,s)),this.lr.set(t,s.add(n.key))}}class br{constructor(){this.hr=new he(Dr.Pr),this.Ir=new he(Dr.Tr)}isEmpty(){return this.hr.isEmpty()}addReference(e,t){const n=new Dr(e,t);this.hr=this.hr.add(n),this.Ir=this.Ir.add(n)}Er(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.dr(new Dr(e,t))}Ar(e,t){e.forEach((e=>this.removeReference(e,t)))}Rr(e){const t=new B(new P([])),n=new Dr(t,e),r=new Dr(t,e+1),s=[];return this.Ir.forEachInRange([n,r],(e=>{this.dr(e),s.push(e.key)})),s}Vr(){this.hr.forEach((e=>this.dr(e)))}dr(e){this.hr=this.hr.delete(e),this.Ir=this.Ir.delete(e)}mr(e){const t=new B(new P([])),n=new Dr(t,e),r=new Dr(t,e+1);let s=zt();return this.Ir.forEachInRange([n,r],(e=>{s=s.add(e.key)})),s}containsKey(e){const t=new Dr(e,0),n=this.hr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class Dr{constructor(e,t){this.key=e,this.gr=t}static Pr(e,t){return B.comparator(e.key,t.key)||L(e.gr,t.gr)}static Tr(e,t){return L(e.gr,t.gr)||B.comparator(e.key,t.key)}}class kr{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.pr=1,this.yr=new he(Dr.Pr)}checkEmpty(e){return Y.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const s=this.pr;this.pr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const i=new En(s,t,n,r);this.mutationQueue.push(i);for(const o of r)this.yr=this.yr.add(new Dr(o.key,s)),this.indexManager.addToCollectionParentIndex(e,o.key.path.popLast());return Y.resolve(i)}lookupMutationBatch(e,t){return Y.resolve(this.wr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.Sr(n),s=r<0?0:r;return Y.resolve(this.mutationQueue.length>s?this.mutationQueue[s]:null)}getHighestUnacknowledgedBatchId(){return Y.resolve(0===this.mutationQueue.length?-1:this.pr-1)}getAllMutationBatches(e){return Y.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Dr(t,0),r=new Dr(t,Number.POSITIVE_INFINITY),s=[];return this.yr.forEachInRange([n,r],(e=>{const t=this.wr(e.gr);s.push(t)})),Y.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new he(L);return t.forEach((e=>{const t=new Dr(e,0),r=new Dr(e,Number.POSITIVE_INFINITY);this.yr.forEachInRange([t,r],(e=>{n=n.add(e.gr)}))})),Y.resolve(this.br(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;B.isDocumentKey(s)||(s=s.child(""));const i=new Dr(new B(s),0);let o=new he(L);return this.yr.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.gr)),!0)}),i),Y.resolve(this.br(o))}br(e){const t=[];return e.forEach((e=>{const n=this.wr(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){w(0===this.Dr(t.batchId,"removed")),this.mutationQueue.shift();let n=this.yr;return Y.forEach(t.mutations,(r=>{const s=new Dr(r.key,t.batchId);return n=n.delete(s),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.yr=n}))}Fn(e){}containsKey(e,t){const n=new Dr(t,0),r=this.yr.firstAfterOrEqual(n);return Y.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,Y.resolve()}Dr(e,t){return this.Sr(e)}Sr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}wr(e){const t=this.Sr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Rr{constructor(e){this.Cr=e,this.docs=new ue(B.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),s=r?r.size:0,i=this.Cr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return Y.resolve(n?n.document.mutableCopy():$e.newInvalidDocument(t))}getEntries(e,t){let n=Ot();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():$e.newInvalidDocument(e))})),Y.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let s=Ot();const i=t.path,o=new B(i.child("")),a=this.docs.getIteratorFrom(o);for(;a.hasNext();){const{key:e,value:{document:o}}=a.getNext();if(!i.isPrefixOf(e.path))break;e.path.length>i.length+1||Q(G(o),n)<=0||(r.has(o.key)||Dt(t,o))&&(s=s.insert(o.key,o.mutableCopy()))}return Y.resolve(s)}getAllFromCollectionGroup(e,t,n,r){y()}vr(e,t){return Y.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new xr(this)}getSize(e){return Y.resolve(this.size)}}class xr extends Ir{constructor(e){super(),this._r=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.isValidDocument()?t.push(this._r.addEntry(e,r)):this._r.removeEntry(n)})),Y.waitFor(t)}getFromCache(e,t){return this._r.getEntry(e,t)}getAllFromCache(e,t){return this._r.getEntries(e,t)}}class Lr{constructor(e){this.persistence=e,this.Fr=new Lt((e=>ft(e)),mt),this.lastRemoteSnapshotVersion=M.min(),this.highestTargetId=0,this.Mr=0,this.Or=new br,this.targetCount=0,this.Nr=Tr.On()}forEachTarget(e,t){return this.Fr.forEach(((e,n)=>t(n))),Y.resolve()}getLastRemoteSnapshotVersion(e){return Y.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return Y.resolve(this.Mr)}allocateTargetId(e){return this.highestTargetId=this.Nr.next(),Y.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Mr&&(this.Mr=t),Y.resolve()}kn(e){this.Fr.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Nr=new Tr(t),this.highestTargetId=t),e.sequenceNumber>this.Mr&&(this.Mr=e.sequenceNumber)}addTargetData(e,t){return this.kn(t),this.targetCount+=1,Y.resolve()}updateTargetData(e,t){return this.kn(t),Y.resolve()}removeTargetData(e,t){return this.Fr.delete(t.target),this.Or.Rr(t.targetId),this.targetCount-=1,Y.resolve()}removeTargets(e,t,n){let r=0;const s=[];return this.Fr.forEach(((i,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Fr.delete(i),s.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)})),Y.waitFor(s).next((()=>r))}getTargetCount(e){return Y.resolve(this.targetCount)}getTargetData(e,t){const n=this.Fr.get(t)||null;return Y.resolve(n)}addMatchingKeys(e,t,n){return this.Or.Er(t,n),Y.resolve()}removeMatchingKeys(e,t,n){this.Or.Ar(t,n);const r=this.persistence.referenceDelegate,s=[];return r&&t.forEach((t=>{s.push(r.markPotentiallyOrphaned(e,t))})),Y.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.Or.Rr(t),Y.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Or.mr(t);return Y.resolve(n)}containsKey(e,t){return Y.resolve(this.Or.containsKey(t))}}class Vr{constructor(e,t){this.Br={},this.overlays={},this.Lr=new J(0),this.kr=!1,this.kr=!0,this.referenceDelegate=e(this),this.qr=new Lr(this),this.indexManager=new vr,this.remoteDocumentCache=function(e){return new Rr(e)}((e=>this.referenceDelegate.Qr(e))),this.serializer=new pr(t),this.Kr=new Sr(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.kr=!1,Promise.resolve()}get started(){return this.kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Nr,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Br[e.toKey()];return n||(n=new kr(t,this.referenceDelegate),this.Br[e.toKey()]=n),n}getTargetCache(){return this.qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Kr}runTransaction(e,t,n){f("MemoryPersistence","Starting transaction:",e);const r=new Or(this.Lr.next());return this.referenceDelegate.$r(),n(r).next((e=>this.referenceDelegate.Ur(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Wr(e,t){return Y.or(Object.values(this.Br).map((n=>()=>n.containsKey(e,t))))}}class Or extends H{constructor(e){super(),this.currentSequenceNumber=e}}class Mr{constructor(e){this.persistence=e,this.Gr=new br,this.zr=null}static jr(e){return new Mr(e)}get Hr(){if(this.zr)return this.zr;throw y()}addReference(e,t,n){return this.Gr.addReference(n,t),this.Hr.delete(n.toString()),Y.resolve()}removeReference(e,t,n){return this.Gr.removeReference(n,t),this.Hr.add(n.toString()),Y.resolve()}markPotentiallyOrphaned(e,t){return this.Hr.add(t.toString()),Y.resolve()}removeTarget(e,t){this.Gr.Rr(t.targetId).forEach((e=>this.Hr.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.Hr.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}$r(){this.zr=new Set}Ur(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Y.forEach(this.Hr,(n=>{const r=B.fromPath(n);return this.Jr(e,r).next((e=>{e||t.removeEntry(r,M.min())}))})).next((()=>(this.zr=null,t.apply(e))))}updateLimboDocument(e,t){return this.Jr(e,t).next((e=>{e?this.Hr.delete(t.toString()):this.Hr.add(t.toString())}))}Qr(e){return 0}Jr(e,t){return Y.or([()=>Y.resolve(this.Gr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Wr(e,t)])}}class Fr{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.ki=n,this.qi=r}static Qi(e,t){let n=zt(),r=zt();for(const s of t.docChanges)switch(s.type){case 0:n=n.add(s.doc.key);break;case 1:r=r.add(s.doc.key)}return new Fr(e,t.fromCache,n,r)}}class Pr{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class Ur{constructor(){this.Ki=!1,this.$i=!1,this.Ui=100,this.Wi=8}initialize(e,t){this.Gi=e,this.indexManager=t,this.Ki=!0}getDocumentsMatchingQuery(e,t,n,r){const s={result:null};return this.zi(e,t).next((e=>{s.result=e})).next((()=>{if(!s.result)return this.ji(e,t,r,n).next((e=>{s.result=e}))})).next((()=>{if(s.result)return;const n=new Pr;return this.Hi(e,t,n).next((r=>{if(s.result=r,this.$i)return this.Ji(e,t,n,r.size)}))})).next((()=>s.result))}Ji(e,t,n,r){return n.documentReadCountthis.Wi*r?(d()<=i.a.DEBUG&&f("QueryEngine","The SDK decides to create cache indexes for query:",bt(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,Tt(t))):Y.resolve())}zi(e,t){if(vt(t))return Y.resolve(null);let n=Tt(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=At(t,null,"F"),n=Tt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const s=zt(...r);return this.Gi.getDocuments(e,s).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const i=this.Yi(t,r);return this.Zi(t,i,s,n.readTime)?this.zi(e,At(t,null,"F")):this.Xi(e,i,t,n)}))))})))))}ji(e,t,n,r){return vt(t)||r.isEqual(M.min())?Y.resolve(null):this.Gi.getDocuments(e,n).next((s=>{const o=this.Yi(t,s);return this.Zi(t,o,n,r)?Y.resolve(null):(d()<=i.a.DEBUG&&f("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),bt(t)),this.Xi(e,o,t,z(r,-1)).next((e=>e)))}))}Yi(e,t){let n=new he(Rt(e));return t.forEach(((t,r)=>{Dt(e,r)&&(n=n.add(r))})),n}Zi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||s.version.compareTo(r)>0)}Hi(e,t,n){return d()<=i.a.DEBUG&&f("QueryEngine","Using full collection scan to execute query:",bt(t)),this.Gi.getDocumentsMatchingQuery(e,t,K.min(),n)}Xi(e,t,n,r){return this.Gi.getDocumentsMatchingQuery(e,n,r).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}class qr{constructor(e,t,n,r){this.persistence=e,this.es=t,this.serializer=r,this.ts=new ue(L),this.ns=new Lt((e=>ft(e)),mt),this.rs=new Map,this.ss=e.getRemoteDocumentCache(),this.qr=e.getTargetCache(),this.Kr=e.getBundleCache(),this.os(n)}os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Ar(this.ss,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ss.setIndexManager(this.indexManager),this.es.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.ts)))}}function Br(e,t,n,r){return new qr(e,t,n,r)}async function $r(e,t){const n=v(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next((s=>(r=s,n.os(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const s=[],i=[];let o=zt();for(const e of r){s.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){i.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return n.localDocuments.getDocuments(e,o).next((e=>({_s:e,removedBatchIds:s,addedBatchIds:i})))}))}))}function zr(e){const t=v(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.qr.getLastRemoteSnapshotVersion(e)))}function Gr(e,t,n){let r=zt(),s=zt();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Ot();return n.forEach(((n,i)=>{const o=e.get(n);i.isFoundDocument()!==o.isFoundDocument()&&(s=s.add(n)),i.isNoDocument()&&i.version.isEqual(M.min())?(t.removeEntry(n,i.readTime),r=r.insert(n,i)):!o.isValidDocument()||i.version.compareTo(o.version)>0||0===i.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(i),r=r.insert(n,i)):f("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",i.version)})),{us:r,cs:s}}))}function Kr(e,t){const n=v(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.qr.getTargetData(e,t).next((s=>s?(r=s,Y.resolve(r)):n.qr.allocateTargetId(e).next((s=>(r=new gr(t,s,"TargetPurposeListen",e.currentSequenceNumber),n.qr.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.ts.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.ts=n.ts.insert(e.targetId,e),n.ns.set(t,e.targetId)),e}))}async function Qr(e,t,n){const r=v(e),s=r.ts.get(t),i=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",i,(e=>r.persistence.referenceDelegate.removeTarget(e,s)))}catch(e){if(!X(e))throw e;f("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.ts=r.ts.remove(t),r.ns.delete(s.target)}function jr(e,t,n){const r=v(e);let s=M.min(),i=zt();return r.persistence.runTransaction("Execute query","readwrite",(e=>function(e,t,n){const r=v(e),s=r.ns.get(n);return void 0!==s?Y.resolve(r.ts.get(s)):r.qr.getTargetData(t,n)}(r,e,Tt(t)).next((t=>{if(t)return s=t.lastLimboFreeSnapshotVersion,r.qr.getMatchingKeysForTargetId(e,t.targetId).next((e=>{i=e}))})).next((()=>r.es.getDocumentsMatchingQuery(e,t,n?s:M.min(),n?i:zt()))).next((e=>(Hr(r,kt(t),e),{documents:e,ls:i})))))}function Hr(e,t,n){let r=e.rs.get(t)||M.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.rs.set(t,r)}class Wr{constructor(){this.activeTargetIds=Kt()}ds(e){this.activeTargetIds=this.activeTargetIds.add(e)}As(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Es(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Yr{constructor(){this.eo=new Wr,this.no={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.eo.ds(e),this.no[e]||"not-current"}updateQueryState(e,t,n){this.no[e]=t}removeLocalQueryTarget(e){this.eo.As(e)}isLocalQueryTarget(e){return this.eo.activeTargetIds.has(e)}clearQueryState(e){delete this.no[e]}getAllActiveQueryTargets(){return this.eo.activeTargetIds}isActiveQueryTarget(e){return this.eo.activeTargetIds.has(e)}start(){return this.eo=new Wr,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Xr{ro(e){}shutdown(){}}class Jr{constructor(){this.io=()=>this.so(),this.oo=()=>this._o(),this.ao=[],this.uo()}ro(e){this.ao.push(e)}shutdown(){window.removeEventListener("online",this.io),window.removeEventListener("offline",this.oo)}uo(){window.addEventListener("online",this.io),window.addEventListener("offline",this.oo)}so(){f("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.ao)e(0)}_o(){f("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.ao)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Zr=null;function es(){return null===Zr?Zr=268435456+Math.round(2147483648*Math.random()):Zr++,"0x"+Zr.toString(16)}const ts={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class ns{constructor(e){this.co=e.co,this.lo=e.lo}ho(e){this.Po=e}Io(e){this.To=e}onMessage(e){this.Eo=e}close(){this.lo()}send(e){this.co(e)}Ao(){this.Po()}Ro(e){this.To(e)}Vo(e){this.Eo(e)}}const rs="WebChannelConnection";class ss extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.mo=t+"://"+e.host,this.fo=`projects/${n}/databases/${r}`,this.po="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get yo(){return!1}wo(e,t,n,r,s){const i=es(),o=this.So(e,t);f("RestConnection",`Sending RPC '${e}' ${i}:`,o,n);const a={"google-cloud-resource-prefix":this.fo,"x-goog-request-params":this.po};return this.bo(a,r,s),this.Do(e,o,a,n).then((t=>(f("RestConnection",`Received RPC '${e}' ${i}: `,t),t)),(t=>{throw g("RestConnection",`RPC '${e}' ${i} failed with error: `,t,"url: ",o,"request:",n),t}))}Co(e,t,n,r,s,i){return this.wo(e,t,n,r,s)}bo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+l,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}So(e,t){const n=ts[e];return`${this.mo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Do(e,t,n,r){const s=es();return new Promise(((i,o)=>{const u=new a.i;u.setWithCredentials(!0),u.listenOnce(a.c.COMPLETE,(()=>{try{switch(u.getLastErrorCode()){case a.a.NO_ERROR:const t=u.getResponseJson();f(rs,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case a.a.TIMEOUT:f(rs,`RPC '${e}' ${s} timed out`),o(new E(_.DEADLINE_EXCEEDED,"Request time out"));break;case a.a.HTTP_ERROR:const n=u.getStatus();if(f(rs,`RPC '${e}' ${s} failed with status:`,n,"response text:",u.getResponseText()),n>0){let e=u.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(_).indexOf(t)>=0?t:_.UNKNOWN}(t.status);o(new E(e,t.message))}else o(new E(_.UNKNOWN,"Server responded with status "+u.getStatus()))}else o(new E(_.UNAVAILABLE,"Connection failed."));break;default:y()}}finally{f(rs,`RPC '${e}' ${s} completed.`)}}));const c=JSON.stringify(r);f(rs,`RPC '${e}' ${s} sending request:`,r),u.send(t,"POST",c,n,15)}))}vo(e,t,n){const r=es(),s=[this.mo,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=Object(a.j)(),o=Object(a.k)(),u={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},c=this.longPollingOptions.timeoutSeconds;void 0!==c&&(u.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(u.xmlHttpFactory=new a.d({})),this.bo(u.initMessageHeaders,t,n),u.encodeInitMessageHeaders=!0;const l=s.join("");f(rs,`Creating RPC '${e}' stream ${r}: ${l}`,u);const h=i.createWebChannel(l,u);let d=!1,m=!1;const p=new ns({co:t=>{m?f(rs,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(d||(f(rs,`Opening RPC '${e}' stream ${r} transport.`),h.open(),d=!0),f(rs,`RPC '${e}' stream ${r} sending:`,t),h.send(t))},lo:()=>h.close()}),y=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return y(h,a.h.EventType.OPEN,(()=>{m||f(rs,`RPC '${e}' stream ${r} transport opened.`)})),y(h,a.h.EventType.CLOSE,(()=>{m||(m=!0,f(rs,`RPC '${e}' stream ${r} transport closed`),p.Ro())})),y(h,a.h.EventType.ERROR,(t=>{m||(m=!0,g(rs,`RPC '${e}' stream ${r} transport errored:`,t),p.Ro(new E(_.UNAVAILABLE,"The operation could not be completed")))})),y(h,a.h.EventType.MESSAGE,(t=>{var n;if(!m){const s=t.data[0];w(!!s);const i=s,o=i.error||(null===(n=i[0])||void 0===n?void 0:n.error);if(o){f(rs,`RPC '${e}' stream ${r} received error:`,o);const t=o.status;let n=function(e){const t=Cn[e];if(void 0!==t)return Sn(t)}(t),s=o.message;void 0===n&&(n=_.INTERNAL,s="Unknown error status: "+t+" with message "+o.message),m=!0,p.Ro(new E(n,s)),h.close()}else f(rs,`RPC '${e}' stream ${r} received:`,s),p.Vo(s)}})),y(o,a.b.STAT_EVENT,(t=>{t.stat===a.g.PROXY?f(rs,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===a.g.NOPROXY&&f(rs,`RPC '${e}' stream ${r} detected no buffering proxy`)})),setTimeout((()=>{p.Ao()}),0),p}}function is(){return"undefined"!=typeof document?document:null}function os(e){return new Qn(e,!0)}class as{constructor(e,t,n=1e3,r=1.5,s=6e4){this.si=e,this.timerId=t,this.Fo=n,this.Mo=r,this.xo=s,this.Oo=0,this.No=null,this.Bo=Date.now(),this.reset()}reset(){this.Oo=0}Lo(){this.Oo=this.xo}ko(e){this.cancel();const t=Math.floor(this.Oo+this.qo()),n=Math.max(0,Date.now()-this.Bo),r=Math.max(0,t-n);r>0&&f("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Oo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.No=this.si.enqueueAfterDelay(this.timerId,r,(()=>(this.Bo=Date.now(),e()))),this.Oo*=this.Mo,this.Oothis.xo&&(this.Oo=this.xo)}Qo(){null!==this.No&&(this.No.skipDelay(),this.No=null)}cancel(){null!==this.No&&(this.No.cancel(),this.No=null)}qo(){return(Math.random()-.5)*this.Oo}}class us{constructor(e,t,n,r,s,i,o,a){this.si=e,this.Ko=n,this.$o=r,this.connection=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Uo=0,this.Wo=null,this.Go=null,this.stream=null,this.zo=new as(e,t)}jo(){return 1===this.state||5===this.state||this.Ho()}Ho(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Jo()}async stop(){this.jo()&&await this.close(0)}Yo(){this.state=0,this.zo.reset()}Zo(){this.Ho()&&null===this.Wo&&(this.Wo=this.si.enqueueAfterDelay(this.Ko,6e4,(()=>this.Xo())))}e_(e){this.t_(),this.stream.send(e)}async Xo(){if(this.Ho())return this.close(0)}t_(){this.Wo&&(this.Wo.cancel(),this.Wo=null)}n_(){this.Go&&(this.Go.cancel(),this.Go=null)}async close(e,t){this.t_(),this.n_(),this.zo.cancel(),this.Uo++,4!==e?this.zo.reset():t&&t.code===_.RESOURCE_EXHAUSTED?(m(t.toString()),m("Using maximum backoff delay to prevent overloading the backend."),this.zo.Lo()):t&&t.code===_.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.r_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Io(t)}r_(){}auth(){this.state=1;const e=this.i_(this.Uo),t=this.Uo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.Uo===t&&this.s_(e,n)}),(t=>{e((()=>{const e=new E(_.UNKNOWN,"Fetching auth token failed: "+t.message);return this.o_(e)}))}))}s_(e,t){const n=this.i_(this.Uo);this.stream=this.__(e,t),this.stream.ho((()=>{n((()=>(this.state=2,this.Go=this.si.enqueueAfterDelay(this.$o,1e4,(()=>(this.Ho()&&(this.state=3),Promise.resolve()))),this.listener.ho())))})),this.stream.Io((e=>{n((()=>this.o_(e)))})),this.stream.onMessage((e=>{n((()=>this.onMessage(e)))}))}Jo(){this.state=5,this.zo.ko((async()=>{this.state=0,this.start()}))}o_(e){return f("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}i_(e){return t=>{this.si.enqueueAndForget((()=>this.Uo===e?t():(f("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class cs extends us{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.serializer=s}__(e,t){return this.connection.vo("Listen",e,t)}onMessage(e){this.zo.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:y()}(t.targetChange.targetChangeType||"NO_CHANGE"),s=t.targetChange.targetIds||[],i=function(e,t){return e.useProto3Json?(w(void 0===t||"string"==typeof t),ge.fromBase64String(t||"")):(w(void 0===t||t instanceof Uint8Array),ge.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?_.UNKNOWN:Sn(e.code);return new E(t,e.message||"")}(o);n=new Pn(r,s,i,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const s=Zn(e,r.document.name),i=Yn(r.document.updateTime),o=r.document.createTime?Yn(r.document.createTime):M.min(),a=new Be({mapValue:{fields:r.document.fields}}),u=$e.newFoundDocument(s,i,o,a),c=r.targetIds||[],l=r.removedTargetIds||[];n=new Mn(c,l,u.key,u)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const s=Zn(e,r.document),i=r.readTime?Yn(r.readTime):M.min(),o=$e.newNoDocument(s,i),a=r.removedTargetIds||[];n=new Mn([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const s=Zn(e,r.document),i=r.removedTargetIds||[];n=new Mn([],i,s,null)}else{if(!("filter"in t))return y();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:s}=e,i=new In(r,s),o=e.targetId;n=new Fn(o,i)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return M.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?M.min():t.readTime?Yn(t.readTime):M.min()}(e);return this.listener.a_(t,n)}u_(e){const t={};t.database=nr(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=gt(r)?{documents:sr(e,r)}:{query:ir(e,r)},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=Wn(e,t.resumeToken);const r=jn(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(M.min())>0){n.readTime=Hn(e,t.snapshotVersion.toTimestamp());const r=jn(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);const n=function(e,t){const n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return y()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.e_(t)}c_(e){const t={};t.database=nr(this.serializer),t.removeTarget=e,this.e_(t)}}class ls extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.d_=!1}A_(){if(this.d_)throw new E(_.FAILED_PRECONDITION,"The client has already been terminated.")}wo(e,t,n){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([r,s])=>this.connection.wo(e,t,n,r,s))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new E(_.UNKNOWN,e.toString())}))}Co(e,t,n,r){return this.A_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,i])=>this.connection.Co(e,t,n,s,i,r))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new E(_.UNKNOWN,e.toString())}))}terminate(){this.d_=!0}}class hs{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.V_=0,this.m_=null,this.f_=!0}g_(){0===this.V_&&(this.p_("Unknown"),this.m_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.m_=null,this.y_("Backend didn't respond within 10 seconds."),this.p_("Offline"),Promise.resolve()))))}w_(e){"Online"===this.state?this.p_("Unknown"):(this.V_++,this.V_>=1&&(this.S_(),this.y_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.p_("Offline")))}set(e){this.S_(),this.V_=0,"Online"===e&&(this.f_=!1),this.p_(e)}p_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}y_(e){const t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.f_?(m(t),this.f_=!1):f("OnlineStateTracker",t)}S_(){null!==this.m_&&(this.m_.cancel(),this.m_=null)}}class ds{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.b_=[],this.D_=new Map,this.C_=new Set,this.v_=[],this.F_=s,this.F_.ro((e=>{n.enqueueAndForget((async()=>{Es(this)&&(f("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=v(e);t.C_.add(4),await ms(t),t.M_.set("Unknown"),t.C_.delete(4),await fs(t)}(this))}))})),this.M_=new hs(n,r)}}async function fs(e){if(Es(e))for(const t of e.v_)await t(!0)}async function ms(e){for(const t of e.v_)await t(!1)}function gs(e,t){const n=v(e);n.D_.has(t.targetId)||(n.D_.set(t.targetId,t),_s(n)?vs(n):Ds(n).Ho()&&ys(n,t))}function ps(e,t){const n=v(e),r=Ds(n);n.D_.delete(t),r.Ho()&&ws(n,t),0===n.D_.size&&(r.Ho()?r.Zo():Es(n)&&n.M_.set("Unknown"))}function ys(e,t){if(e.x_.Oe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(M.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}Ds(e).u_(t)}function ws(e,t){e.x_.Oe(t),Ds(e).c_(t)}function vs(e){e.x_=new qn({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),_t:t=>e.D_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),Ds(e).start(),e.M_.g_()}function _s(e){return Es(e)&&!Ds(e).jo()&&e.D_.size>0}function Es(e){return 0===v(e).C_.size}function Ts(e){e.x_=void 0}async function Is(e){e.D_.forEach(((t,n)=>{ys(e,t)}))}async function Cs(e,t){Ts(e),_s(e)?(e.M_.w_(t),vs(e)):e.M_.set("Unknown")}async function As(e,t,n){if(e.M_.set("Online"),t instanceof Pn&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.D_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.D_.delete(r),e.x_.removeTarget(r))}(e,t)}catch(n){f("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await Ss(e,n)}else if(t instanceof Mn?e.x_.$e(t):t instanceof Fn?e.x_.Je(t):e.x_.Ge(t),!n.isEqual(M.min()))try{const t=await zr(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.x_.it(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const s=e.D_.get(r);s&&e.D_.set(r,s.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach(((t,n)=>{const r=e.D_.get(t);if(!r)return;e.D_.set(t,r.withResumeToken(ge.EMPTY_BYTE_STRING,r.snapshotVersion)),ws(e,t);const s=new gr(r.target,t,n,r.sequenceNumber);ys(e,s)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){f("RemoteStore","Failed to raise snapshot:",t),await Ss(e,t)}}async function Ss(e,t,n){if(!X(t))throw t;e.C_.add(1),await ms(e),e.M_.set("Offline"),n||(n=()=>zr(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{f("RemoteStore","Retrying IndexedDB access"),await n(),e.C_.delete(1),await fs(e)}))}async function Ns(e,t){const n=v(e);n.asyncQueue.verifyOperationInProgress(),f("RemoteStore","RemoteStore received new credentials");const r=Es(n);n.C_.add(3),await ms(n),r&&n.M_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.C_.delete(3),await fs(n)}async function bs(e,t){const n=v(e);t?(n.C_.delete(2),await fs(n)):t||(n.C_.add(2),await ms(n),n.M_.set("Unknown"))}function Ds(e){return e.O_||(e.O_=function(e,t,n){const r=v(e);return r.A_(),new cs(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{ho:Is.bind(null,e),Io:Cs.bind(null,e),a_:As.bind(null,e)}),e.v_.push((async t=>{t?(e.O_.Yo(),_s(e)?vs(e):e.M_.set("Unknown")):(await e.O_.stop(),Ts(e))}))),e.O_}class ks{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,this.deferred=new T,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,s){const i=Date.now()+n,o=new ks(e,t,i,r,s);return o.start(n),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new E(_.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Rs(e,t){if(m("AsyncQueue",`${t}: ${e}`),X(e))return new E(_.UNAVAILABLE,`${t}: ${e}`);throw e}class xs{constructor(e){this.comparator=e?(t,n)=>e(t,n)||B.comparator(t.key,n.key):(e,t)=>B.comparator(e.key,t.key),this.keyedMap=Ft(),this.sortedSet=new ue(this.comparator)}static emptySet(e){return new xs(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof xs))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new xs;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class Ls{constructor(){this.B_=new ue(B.comparator)}track(e){const t=e.doc.key,n=this.B_.get(t);n?0!==e.type&&3===n.type?this.B_=this.B_.insert(t,e):3===e.type&&1!==n.type?this.B_=this.B_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.B_=this.B_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.B_=this.B_.remove(t):1===e.type&&2===n.type?this.B_=this.B_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.B_=this.B_.insert(t,{type:2,doc:e.doc}):y():this.B_=this.B_.insert(t,e)}L_(){const e=[];return this.B_.inorderTraversal(((t,n)=>{e.push(n)})),e}}class Vs{constructor(e,t,n,r,s,i,o,a,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,s){const i=[];return t.forEach((e=>{i.push({type:0,doc:e})})),new Vs(e,t,xs.emptySet(t),i,n,r,!0,!1,s)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&St(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;rNt(e)),St),this.onlineState="Unknown",this.q_=new Set}}async function Fs(e,t){const n=v(e),r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new Os),s)try{i.k_=await n.onListen(r)}catch(e){const n=Rs(e,`Initialization of query '${bt(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.Q_(n.onlineState),i.k_&&t.K_(i.k_)&&Bs(n)}async function Ps(e,t){const n=v(e),r=t.query;let s=!1;const i=n.queries.get(r);if(i){const e=i.listeners.indexOf(t);e>=0&&(i.listeners.splice(e,1),s=0===i.listeners.length)}if(s)return n.queries.delete(r),n.onUnlisten(r)}function Us(e,t){const n=v(e);let r=!1;for(const s of t){const e=s.query,t=n.queries.get(e);if(t){for(const e of t.listeners)e.K_(s)&&(r=!0);t.k_=s}}r&&Bs(n)}function qs(e,t,n){const r=v(e),s=r.queries.get(t);if(s)for(const i of s.listeners)i.onError(n);r.queries.delete(t)}function Bs(e){e.q_.forEach((e=>{e.next()}))}class $s{constructor(e,t,n){this.query=e,this.U_=t,this.W_=!1,this.G_=null,this.onlineState="Unknown",this.options=n||{}}K_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new Vs(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.W_?this.z_(e)&&(this.U_.next(e),t=!0):this.j_(e,this.onlineState)&&(this.H_(e),t=!0),this.G_=e,t}onError(e){this.U_.error(e)}Q_(e){this.onlineState=e;let t=!1;return this.G_&&!this.W_&&this.j_(this.G_,e)&&(this.H_(this.G_),t=!0),t}j_(e,t){if(!e.fromCache)return!0;const n="Offline"!==t;return(!this.options.J_||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}z_(e){if(e.docChanges.length>0)return!0;const t=this.G_&&this.G_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}H_(e){e=Vs.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.W_=!0,this.U_.next(e)}}class zs{constructor(e){this.key=e}}class Gs{constructor(e){this.key=e}}class Ks{constructor(e,t){this.query=e,this.ia=t,this.sa=null,this.hasCachedResults=!1,this.current=!1,this.oa=zt(),this.mutatedKeys=zt(),this._a=Rt(e),this.aa=new xs(this._a)}get ua(){return this.ia}ca(e,t){const n=t?t.la:new Ls,r=t?t.aa:this.aa;let s=t?t.mutatedKeys:this.mutatedKeys,i=r,o=!1;const a="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,u="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const c=r.get(e),l=Dt(this.query,t)?t:null,h=!!c&&this.mutatedKeys.has(c.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;c&&l?c.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.ha(c,l)||(n.track({type:2,doc:l}),f=!0,(a&&this._a(l,a)>0||u&&this._a(l,u)<0)&&(o=!0)):!c&&l?(n.track({type:0,doc:l}),f=!0):c&&!l&&(n.track({type:1,doc:c}),f=!0,(a||u)&&(o=!0)),f&&(l?(i=i.add(l),s=d?s.add(e):s.delete(e)):(i=i.delete(e),s=s.delete(e)))})),null!==this.query.limit)for(;i.size>this.query.limit;){const e="F"===this.query.limitType?i.last():i.first();i=i.delete(e.key),s=s.delete(e.key),n.track({type:1,doc:e})}return{aa:i,la:n,Zi:o,mutatedKeys:s}}ha(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){const r=this.aa;this.aa=e.aa,this.mutatedKeys=e.mutatedKeys;const s=e.la.L_();s.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return y()}};return n(e)-n(t)}(e.type,t.type)||this._a(e.doc,t.doc))),this.Pa(n);const i=t?this.Ia():[],o=0===this.oa.size&&this.current?1:0,a=o!==this.sa;return this.sa=o,0!==s.length||a?{snapshot:new Vs(this.query,e.aa,r,s,e.mutatedKeys,0===o,a,!1,!!n&&n.resumeToken.approximateByteSize()>0),Ta:i}:{Ta:i}}Q_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({aa:this.aa,la:new Ls,mutatedKeys:this.mutatedKeys,Zi:!1},!1)):{Ta:[]}}Ea(e){return!this.ia.has(e)&&!!this.aa.has(e)&&!this.aa.get(e).hasLocalMutations}Pa(e){e&&(e.addedDocuments.forEach((e=>this.ia=this.ia.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.ia=this.ia.delete(e))),this.current=e.current)}Ia(){if(!this.current)return[];const e=this.oa;this.oa=zt(),this.aa.forEach((e=>{this.Ea(e.key)&&(this.oa=this.oa.add(e.key))}));const t=[];return e.forEach((e=>{this.oa.has(e)||t.push(new Gs(e))})),this.oa.forEach((n=>{e.has(n)||t.push(new zs(n))})),t}da(e){this.ia=e.ls,this.oa=zt();const t=this.ca(e.documents);return this.applyChanges(t,!0)}Aa(){return Vs.fromInitialDocuments(this.query,this.aa,this.mutatedKeys,0===this.sa,this.hasCachedResults)}}class Qs{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class js{constructor(e){this.key=e,this.Ra=!1}}class Hs{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.Va={},this.ma=new Lt((e=>Nt(e)),St),this.fa=new Map,this.ga=new Set,this.pa=new ue(B.comparator),this.ya=new Map,this.wa=new br,this.Sa={},this.ba=new Map,this.Da=Tr.Nn(),this.onlineState="Unknown",this.Ca=void 0}get isPrimaryClient(){return!0===this.Ca}}async function Ws(e,t){const n=ci(e);let r,s;const i=n.ma.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.Aa();else{const e=await Kr(n.localStore,Tt(t)),i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await Ys(n,t,r,"current"===i,e.resumeToken),n.isPrimaryClient&&gs(n.remoteStore,e)}return s}async function Ys(e,t,n,r,s){e.va=(t,n,r)=>async function(e,t,n,r){let s=t.view.ca(n);s.Zi&&(s=await jr(e.localStore,t.query,!1).then((({documents:e})=>t.view.ca(e,s))));const i=r&&r.targetChanges.get(t.targetId),o=t.view.applyChanges(s,e.isPrimaryClient,i);return ri(e,t.targetId,o.Ta),o.snapshot}(e,t,n,r);const i=await jr(e.localStore,t,!0),o=new Ks(t,i.ls),a=o.ca(i.documents),u=On.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,s),c=o.applyChanges(a,e.isPrimaryClient,u);ri(e,n,c.Ta);const l=new Qs(t,n,o);return e.ma.set(t,l),e.fa.has(n)?e.fa.get(n).push(t):e.fa.set(n,[t]),c.snapshot}async function Xs(e,t){const n=v(e),r=n.ma.get(t),s=n.fa.get(r.targetId);if(s.length>1)return n.fa.set(r.targetId,s.filter((e=>!St(e,t)))),void n.ma.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await Qr(n.localStore,r.targetId,!1).then((()=>{n.sharedClientState.clearQueryState(r.targetId),ps(n.remoteStore,r.targetId),ti(n,r.targetId)})).catch(W)):(ti(n,r.targetId),await Qr(n.localStore,r.targetId,!0))}async function Js(e,t){const n=v(e);try{const e=await function(e,t){const n=v(e),r=t.snapshotVersion;let s=n.ts;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const i=n.ss.newChangeBuffer({trackRemovals:!0});s=n.ts;const o=[];t.targetChanges.forEach(((i,a)=>{const u=s.get(a);if(!u)return;o.push(n.qr.removeMatchingKeys(e,i.removedDocuments,a).next((()=>n.qr.addMatchingKeys(e,i.addedDocuments,a))));let c=u.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?c=c.withResumeToken(ge.EMPTY_BYTE_STRING,M.min()).withLastLimboFreeSnapshotVersion(M.min()):i.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(i.resumeToken,r)),s=s.insert(a,c),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(u,c,i)&&o.push(n.qr.updateTargetData(e,c))}));let a=Ot(),u=zt();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push(Gr(e,i,t.documentUpdates).next((e=>{a=e.us,u=e.cs}))),!r.isEqual(M.min())){const t=n.qr.getLastRemoteSnapshotVersion(e).next((t=>n.qr.setTargetsMetadata(e,e.currentSequenceNumber,r)));o.push(t)}return Y.waitFor(o).next((()=>i.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,a,u))).next((()=>a))})).then((e=>(n.ts=s,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.ya.get(t);r&&(w(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.Ra=!0:e.modifiedDocuments.size>0?w(r.Ra):e.removedDocuments.size>0&&(w(r.Ra),r.Ra=!1))})),await oi(n,e,t)}catch(e){await W(e)}}function Zs(e,t,n){const r=v(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.ma.forEach(((n,r)=>{const s=r.view.Q_(t);s.snapshot&&e.push(s.snapshot)})),function(e,t){const n=v(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const s of n.listeners)s.Q_(t)&&(r=!0)})),r&&Bs(n)}(r.eventManager,t),e.length&&r.Va.a_(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function ei(e,t,n){const r=v(e);r.sharedClientState.updateQueryState(t,"rejected",n);const s=r.ya.get(t),i=s&&s.key;if(i){let e=new ue(B.comparator);e=e.insert(i,$e.newNoDocument(i,M.min()));const n=zt().add(i),s=new Vn(M.min(),new Map,new ue(L),e,n);await Js(r,s),r.pa=r.pa.remove(i),r.ya.delete(t),ii(r)}else await Qr(r.localStore,t,!1).then((()=>ti(r,t,n))).catch(W)}function ti(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.fa.get(t))e.ma.delete(r),n&&e.Va.Fa(r,n);e.fa.delete(t),e.isPrimaryClient&&e.wa.Rr(t).forEach((t=>{e.wa.containsKey(t)||ni(e,t)}))}function ni(e,t){e.ga.delete(t.path.canonicalString());const n=e.pa.get(t);null!==n&&(ps(e.remoteStore,n),e.pa=e.pa.remove(t),e.ya.delete(n),ii(e))}function ri(e,t,n){for(const r of n)r instanceof zs?(e.wa.addReference(r.key,t),si(e,r)):r instanceof Gs?(f("SyncEngine","Document no longer in limbo: "+r.key),e.wa.removeReference(r.key,t),e.wa.containsKey(r.key)||ni(e,r.key)):y()}function si(e,t){const n=t.key,r=n.path.canonicalString();e.pa.get(n)||e.ga.has(r)||(f("SyncEngine","New document in limbo: "+n),e.ga.add(r),ii(e))}function ii(e){for(;e.ga.size>0&&e.pa.size{o.push(r.va(a,t,n).then((e=>{if((e||n)&&r.isPrimaryClient&&r.sharedClientState.updateQueryState(a.targetId,(null==e?void 0:e.fromCache)?"not-current":"current"),e){s.push(e);const t=Fr.Qi(a.targetId,e);i.push(t)}})))})),await Promise.all(o),r.Va.a_(s),await async function(e,t){const n=v(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>Y.forEach(t,(t=>Y.forEach(t.ki,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>Y.forEach(t.qi,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!X(e))throw e;f("LocalStore","Failed to update sequence numbers: "+e)}for(const r of t){const e=r.targetId;if(!r.fromCache){const t=n.ts.get(e),r=t.snapshotVersion,s=t.withLastLimboFreeSnapshotVersion(r);n.ts=n.ts.insert(e,s)}}}(r.localStore,i))}async function ai(e,t){const n=v(e);if(!n.currentUser.isEqual(t)){f("SyncEngine","User change. New user:",t.toKey());const e=await $r(n.localStore,t);n.currentUser=t,function(e,t){e.ba.forEach((e=>{e.forEach((e=>{e.reject(new E(_.CANCELLED,t))}))})),e.ba.clear()}(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await oi(n,e._s)}}function ui(e,t){const n=v(e),r=n.ya.get(t);if(r&&r.Ra)return zt().add(r.key);{let e=zt();const r=n.fa.get(t);if(!r)return e;for(const t of r){const r=n.ma.get(t);e=e.unionWith(r.view.ua)}return e}}function ci(e){const t=v(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Js.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=ui.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=ei.bind(null,t),t.Va.a_=Us.bind(null,t.eventManager),t.Va.Fa=qs.bind(null,t.eventManager),t}class li{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=os(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return Br(this.persistence,new Ur,e.initialUser,this.serializer)}createPersistence(e){return new Vr(Mr.jr,this.serializer)}createSharedClientState(e){return new Yr}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class hi{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=>Zs(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=ai.bind(null,this.syncEngine),await bs(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Ms}createDatastore(e){const t=os(e.databaseInfo.databaseId),n=function(e){return new ss(e)}(e.databaseInfo);return function(e,t,n,r){return new ls(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,r,s){return new ds(e,t,n,r,s)}(this.localStore,this.datastore,e.asyncQueue,(e=>Zs(this.syncEngine,e,0)),Jr.D()?new Jr:new Xr)}createSyncEngine(e,t){return function(e,t,n,r,s,i,o){const a=new Hs(e,t,n,r,s,i);return o&&(a.Ca=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=v(e);f("RemoteStore","RemoteStore shutting down."),t.C_.add(5),await ms(t),t.F_.shutdown(),t.M_.set("Unknown")}(this.remoteStore)}}class di{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Oa(this.observer.next,e)}error(e){this.observer.error?this.Oa(this.observer.error,e):m("Uncaught Error in snapshot listener:",e.toString())}Na(){this.muted=!0}Oa(e,t){this.muted||setTimeout((()=>{this.muted||e(t)}),0)}}class fi{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=c.UNAUTHENTICATED,this.clientId=x.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,(async e=>{f("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(f("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new E(_.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const e=new T;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=Rs(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function mi(e,t){e.asyncQueue.verifyOperationInProgress(),f("FirestoreClient","Initializing OfflineComponentProvider");const n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await $r(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function gi(e,t){e.asyncQueue.verifyOperationInProgress();const n=await yi(e);f("FirestoreClient","Initializing OnlineComponentProvider");const r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener((e=>Ns(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Ns(t.remoteStore,n))),e._onlineComponents=t}function pi(e){return"FirebaseError"===e.name?e.code===_.FAILED_PRECONDITION||e.code===_.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function yi(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){f("FirestoreClient","Using user provided OfflineComponentProvider");try{await mi(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!pi(n))throw n;g("Error using user provided cache. Falling back to memory cache: "+n),await mi(e,new li)}}else f("FirestoreClient","Using default OfflineComponentProvider"),await mi(e,new li);return e._offlineComponents}async function wi(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(f("FirestoreClient","Using user provided OnlineComponentProvider"),await gi(e,e._uninitializedComponentsProvider._online)):(f("FirestoreClient","Using default OnlineComponentProvider"),await gi(e,new hi))),e._onlineComponents}async function vi(e){const t=await wi(e),n=t.eventManager;return n.onListen=Ws.bind(null,t.syncEngine),n.onUnlisten=Xs.bind(null,t.syncEngine),n}function _i(e,t,n={}){const r=new T;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,s){const i=new di({next:i=>{t.enqueueAndForget((()=>Ps(e,o)));const a=i.docs.has(n);!a&&i.fromCache?s.reject(new E(_.UNAVAILABLE,"Failed to get document because the client is offline.")):a&&i.fromCache&&r&&"server"===r.source?s.reject(new E(_.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):s.resolve(i)},error:e=>s.reject(e)}),o=new $s(wt(n.path),i,{includeMetadataChanges:!0,J_:!0});return Fs(e,o)}(await vi(e),e.asyncQueue,t,n,r))),r.promise}function Ei(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Ti=new Map;function Ii(e,t,n){if(!n)throw new E(_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Ci(e){if(!B.isDocumentKey(e))throw new E(_.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Ai(e){if(B.isDocumentKey(e))throw new E(_.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Si(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":y()}function Ni(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new E(_.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Si(e);throw new E(_.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function bi(e,t){if(t<=0)throw new E(_.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Di{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new E(_.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new E(_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,r){if(!0===t&&!0===r)throw new E(_.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Ei(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new E(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new E(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new E(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function(e,t){return e.timeoutSeconds===t.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class ki{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Di({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new E(_.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new E(_.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Di(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new C;switch(e.type){case"firstParty":return new b(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new E(_.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Ti.get(e);t&&(f("ComponentProvider","Removing Datastore"),Ti.delete(e),t.terminate())}(this),Promise.resolve()}}class Ri{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Ri(this.firestore,e,this._query)}}class xi{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Li(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new xi(this.firestore,e,this._key)}}class Li extends Ri{constructor(e,t,n){super(e,t,wt(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new xi(this.firestore,null,new B(e))}withConverter(e){return new Li(this.firestore,e,this._path)}}function Vi(e,t,...n){if(e=Object(o.j)(e),Ii("collection","path",t),e instanceof ki){const r=P.fromString(t,...n);return Ai(r),new Li(e,null,r)}{if(!(e instanceof xi||e instanceof Li))throw new E(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(P.fromString(t,...n));return Ai(r),new Li(e.firestore,null,r)}}function Oi(e,t,...n){if(e=Object(o.j)(e),1===arguments.length&&(t=x.newId()),Ii("doc","path",t),e instanceof ki){const r=P.fromString(t,...n);return Ci(r),new xi(e,null,new B(r))}{if(!(e instanceof xi||e instanceof Li))throw new E(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(P.fromString(t,...n));return Ci(r),new xi(e.firestore,e instanceof Li?e.converter:null,new B(r))}}class Mi{constructor(){this.Ja=Promise.resolve(),this.Ya=[],this.Za=!1,this.Xa=[],this.eu=null,this.tu=!1,this.nu=!1,this.ru=[],this.zo=new as(this,"async_queue_retry"),this.iu=()=>{const e=is();e&&f("AsyncQueue","Visibility state changed to "+e.visibilityState),this.zo.Qo()};const e=is();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.iu)}get isShuttingDown(){return this.Za}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.su(),this.ou(e)}enterRestrictedMode(e){if(!this.Za){this.Za=!0,this.nu=e||!1;const t=is();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.iu)}}enqueue(e){if(this.su(),this.Za)return new Promise((()=>{}));const t=new T;return this.ou((()=>this.Za&&this.nu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Ya.push(e),this._u())))}async _u(){if(0!==this.Ya.length){try{await this.Ya[0](),this.Ya.shift(),this.zo.reset()}catch(e){if(!X(e))throw e;f("AsyncQueue","Operation failed with retryable error: "+e)}this.Ya.length>0&&this.zo.ko((()=>this._u()))}}ou(e){const t=this.Ja.then((()=>(this.tu=!0,e().catch((e=>{this.eu=e,this.tu=!1;throw m("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e})).then((e=>(this.tu=!1,e))))));return this.Ja=t,t}enqueueAfterDelay(e,t,n){this.su(),this.ru.indexOf(e)>-1&&(t=0);const r=ks.createAndSchedule(this,e,t,n,(e=>this.au(e)));return this.Xa.push(r),r}su(){this.eu&&y()}verifyOperationInProgress(){}async uu(){let e;do{e=this.Ja,await e}while(e!==this.Ja)}cu(e){for(const t of this.Xa)if(t.timerId===e)return!0;return!1}lu(e){return this.uu().then((()=>{this.Xa.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.Xa)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.uu()}))}hu(e){this.ru.push(e)}au(e){const t=this.Xa.indexOf(e);this.Xa.splice(t,1)}}function Fi(e){return function(e,t){if("object"!=typeof e||null===e)return!1;const n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return!0;return!1}(e,["next","error","complete"])}class Pi extends ki{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new Mi,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||Bi(this),this._firestoreClient.terminate()}}function Ui(e,t){const n="object"==typeof e?e:Object(r.e)(),s="string"==typeof e?e:t||"(default)",i=Object(r.b)(n,"firestore").getImmediate({identifier:s});if(!i._initialized){const e=Object(o.i)("firestore");e&&function(e,t,n,r={}){var s;const i=(e=Ni(e,ki))._getSettings(),a=`${t}:${n}`;if("firestore.googleapis.com"!==i.host&&i.host!==a&&g("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},i),{host:a,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=c.MOCK_USER;else{t=Object(o.f)(r.mockUserToken,null===(s=e._app)||void 0===s?void 0:s.options.projectId);const i=r.mockUserToken.sub||r.mockUserToken.user_id;if(!i)throw new E(_.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new c(i)}e._authCredentials=new A(new I(t,n))}}(i,...e)}return i}function qi(e){return e._firestoreClient||Bi(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Bi(e){var t,n,r;const s=e._freezeSettings(),i=function(e,t,n,r){return new Ie(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Ei(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,s);e._firestoreClient=new fi(e._authCredentials,e._appCheckCredentials,e._queue,i),(null===(n=s.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=s.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:s.localCache.kind,_offline:s.localCache._offlineComponentProvider,_online:s.localCache._onlineComponentProvider})}class $i{constructor(e){this._byteString=e}static fromBase64String(e){try{return new $i(ge.fromBase64String(e))}catch(e){throw new E(_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new $i(ge.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class zi{constructor(...e){for(let t=0;t90)throw new E(_.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new E(_.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return L(this._lat,e._lat)||L(this._long,e._long)}}const Qi=/^__.*__$/;function ji(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw y()}}class Hi{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===s&&this.Pu(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get Iu(){return this.settings.Iu}Tu(e){return new Hi(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Eu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Tu({path:n,du:!1});return r.Au(e),r}Ru(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Tu({path:n,du:!1});return r.Pu(),r}Vu(e){return this.Tu({path:void 0,du:!0})}mu(e){return so(e,this.settings.methodName,this.settings.fu||!1,this.path,this.settings.gu)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}Pu(){if(this.path)for(let e=0;e0&&t.fieldMask.push(t.path):oe(e,((e,r)=>{const s=Ji(r,t.Eu(e));null!=s&&(n[e]=s)})),{mapValue:{fields:n}}}function eo(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof O||e instanceof Ki||e instanceof $i||e instanceof xi||e instanceof Gi)}function to(e,t,n){if(!eo(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=Si(n);throw"an object"===r?t.mu(e+" a custom object"):t.mu(e+" "+r)}}const no=new RegExp("[~\\*/\\[\\]]");function ro(e,t,n){if(t.search(no)>=0)throw so(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new zi(...t.split("."))._internalPath}catch(r){throw so(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function so(e,t,n,r,s){const i=r&&!r.isEmpty(),o=void 0!==s;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let u="";return(i||o)&&(u+=" (found",i&&(u+=` in field ${r}`),o&&(u+=` in document ${s}`),u+=")"),new E(_.INVALID_ARGUMENT,a+e+u)}class io{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new xi(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new oo(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const t=this._document.data.field(ao("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class oo extends io{data(){return super.data()}}function ao(e,t){return"string"==typeof t?ro(e,t):t instanceof zi?t._internalPath:t._delegate._internalPath}function uo(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new E(_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class co{}class lo extends co{}function ho(e,t,...n){let r=[];t instanceof co&&r.push(t),r=r.concat(n),function(e){const t=e.filter((e=>e instanceof go)).length,n=e.filter((e=>e instanceof fo)).length;if(t>1||t>0&&n>0)throw new E(_.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const s of r)e=s._apply(e);return e}class fo extends lo{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new fo(e,t,n)}_apply(e){const t=this._parse(e);return To(e._query,t),new Ri(e.firestore,e.converter,Ct(e._query,t))}_parse(e){const t=Yi(e.firestore);return function(e,t,n,r,s,i,o){let a;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new E(_.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){Eo(o,i);const t=[];for(const n of o)t.push(_o(r,e,n));a={arrayValue:{values:t}}}else a=_o(r,e,o)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||Eo(o,i),a=Xi(n,t,o,"in"===i||"not-in"===i);return We.create(s,i,a)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function mo(e,t,n){const r=t,s=ao("where",e);return fo._create(s,r,n)}class go extends co{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new go(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:Ye.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const s of r)To(n,s),n=Ct(n,s)}(e._query,t),new Ri(e.firestore,e.converter,Ct(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class po extends lo{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new po(e,t)}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new E(_.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new E(_.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Qe(t,n)}(e._query,this._field,this._direction);return new Ri(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new pt(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}function yo(e,t="asc"){const n=t,r=ao("orderBy",e);return po._create(r,n)}class wo extends lo{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new wo(e,t,n)}_apply(e){return new Ri(e.firestore,e.converter,At(e._query,this._limit,this._limitType))}}function vo(e){return bi("limit",e),wo._create("limit",e,"F")}function _o(e,t,n){if("string"==typeof(n=Object(o.j)(n))){if(""===n)throw new E(_.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!_t(t)&&-1!==n.indexOf("/"))throw new E(_.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);const r=t.path.child(P.fromString(n));if(!B.isDocumentKey(r))throw new E(_.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Le(e,new B(r))}if(n instanceof xi)return Le(e,n._key);throw new E(_.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Si(n)}.`)}function Eo(e,t){if(!Array.isArray(e)||0===e.length)throw new E(_.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function To(e,t){const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==n)throw n===t.op?new E(_.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new E(_.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class Io{convertValue(e,t="none"){switch(Se(e)){case 0:return null;case 1:return e.booleanValue;case 2:return we(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(ve(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw y()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const n={};return oe(e,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertGeoPoint(e){return new Ki(we(e.latitude),we(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=Ee(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Te(e));default:return null}}convertTimestamp(e){const t=ye(e);return new O(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=P.fromString(e);w(mr(n));const r=new Ce(n.get(1),n.get(3)),s=new B(n.popFirst(5));return r.isEqual(t)||m(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}class Co{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Ao extends io{constructor(e,t,n,r,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new So(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){const n=this._document.data.field(ao("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class So extends Ao{data(e={}){return super.data(e)}}class No{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Co(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new So(this._firestore,this._userDataWriter,n.key,n,new Co(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new E(_.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>{const r=new So(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Co(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new So(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Co(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let s=-1,i=-1;return 0!==t.type&&(s=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),i=n.indexOf(t.doc.key)),{type:bo(t.type),doc:r,oldIndex:s,newIndex:i}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function bo(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return y()}}function Do(e){e=Ni(e,xi);const t=Ni(e.firestore,Pi);return _i(qi(t),e._key).then((n=>xo(t,e,n)))}class ko extends Io{constructor(e){super(),this.firestore=e}convertBytes(e){return new $i(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new xi(this.firestore,null,t)}}function Ro(e,...t){var n,r,s;e=Object(o.j)(e);let i={includeMetadataChanges:!1},a=0;"object"!=typeof t[a]||Fi(t[a])||(i=t[a],a++);const u={includeMetadataChanges:i.includeMetadataChanges};if(Fi(t[a])){const e=t[a];t[a]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[a+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[a+2]=null===(s=e.complete)||void 0===s?void 0:s.bind(e)}let c,l,h;if(e instanceof xi)l=Ni(e.firestore,Pi),h=wt(e._key.path),c={next:n=>{t[a]&&t[a](xo(l,e,n))},error:t[a+1],complete:t[a+2]};else{const n=Ni(e,Ri);l=Ni(n.firestore,Pi),h=n._query;const r=new ko(l);c={next:e=>{t[a]&&t[a](new No(l,r,n,e))},error:t[a+1],complete:t[a+2]},uo(e._query)}return function(e,t,n,r){const s=new di(r),i=new $s(t,s,n);return e.asyncQueue.enqueueAndForget((async()=>Fs(await vi(e),i))),()=>{s.Na(),e.asyncQueue.enqueueAndForget((async()=>Ps(await vi(e),i)))}}(qi(l),h,u,c)}function xo(e,t,n){const r=n.docs.get(t._key),s=new ko(e);return new Ao(e,s,t._key,r,new Co(n.hasPendingWrites,n.fromCache),t.converter)}new WeakMap;!function(e,t=!0){!function(e){l=e}(r.a),Object(r.c)(new s.a("firestore",((e,{instanceIdentifier:n,options:r})=>{const s=e.getProvider("app").getImmediate(),i=new Pi(new S(e.getProvider("auth-internal")),new k(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new E(_.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ce(e.options.projectId,t)}(s,n),s);return r=Object.assign({useFetchStreams:t},r),i._setSettings(r),i}),"PUBLIC").setMultipleInstances(!0)),Object(r.h)(u,"4.3.2",e),Object(r.h)(u,"4.3.2","esm2017")}()}).call(this,n("8oxB"))}}]);