1/*! For license information please see 7112840a-108507f23e595f1b6f71.js.LICENSE.txt */ 2"use strict";(self.webpackChunkadac_motorsport=self.webpackChunkadac_motorsport||[]).push([[9883],{15790:function(e,t,n){n.d(t,{GG:function(){return Ta},H9:function(){return Co},P:function(){return aa},_M:function(){return ca},gS:function(){return Sa},kd:function(){return Ca},mZ:function(){return Ia},rJ:function(){return Io}});var s=n(78461),r=n(5125),i=n(63424),o=n(36743),a=n(82429),u=n(81853);const c="@firebase/firestore";class l{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}l.UNAUTHENTICATED=new l(null),l.GOOGLE_CREDENTIALS=new l("google-credentials-uid"),l.FIRST_PARTY=new l("first-party-uid"),l.MOCK_USER=new l("mock-user");let h="10.14.0";const d=new i.Vy("@firebase/firestore");function f(){return d.logLevel}function m(e,...t){if(d.logLevel<=i.$b.DEBUG){const n=t.map(y);d.debug(`Firestore (${h}): ${e}`,...n)}}function p(e,...t){if(d.logLevel<=i.$b.ERROR){const n=t.map(y);d.error(`Firestore (${h}): ${e}`,...n)}}function g(e,...t){if(d.logLevel<=i.$b.WARN){const n=t.map(y);d.warn(`Firestore (${h}): ${e}`,...n)}}function y(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function v(e="Unexpected state"){const t=`FIRESTORE (${h}) INTERNAL ASSERTION FAILED: `+e;throw p(t),new Error(t)}function w(e,t){e||v()}function _(e,t){return e}const E={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class T extends o.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class I{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class C{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class S{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(l.UNAUTHENTICATED))}shutdown(){}}class A{constructor(e){this.t=e,this.currentUser=l.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){w(void 0===this.o);let n=this.i;const s=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let r=new I;this.o=()=>{this.i++,this.currentUser=this.u(),r.resolve(),r=new I,e.enqueueRetryable(()=>s(this.currentUser))};const i=()=>{const t=r;e.enqueueRetryable(async()=>{await t.promise,await s(this.currentUser)})},o=e=>{m("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(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):(m("FirebaseAuthCredentialsProvider","Auth not yet detected"),r.resolve(),r=new I)}},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?(m("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new C(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const e=this.auth&&this.auth.getUid();return w(null===e||"string"==typeof e),new l(e)}}class N{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=l.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(l.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){w(void 0===this.o);const n=e=>{null!=e.error&&m("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,m("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};const s=e=>{m("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>s(e)),setTimeout(()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?s(e):m("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.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}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 s=0;s<e;
2s++)n[s]=Math.floor(256*Math.random());return n}class x{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=62*Math.floor(256/62);let n="";for(;n.length<20;){const s=R(40);for(let r=0;r<s.length;++r)n.length<20&&s[r]<t&&(n+=e.charAt(s[r]%62))}return n}}function L(e,t){return e<t?-1:e>t?1:0}function V(e,t,n){return e.length===t.length&&e.every((e,s)=>n(e,t[s]))}class M{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new T(E.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new T(E.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new T(E.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new T(E.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return M.fromMillis(Date.now())}static fromDate(e){return M.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new M(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 O{constructor(e){this.timestamp=e}static fromTimestamp(e){return new O(e)}static min(){return new O(new M(0,0))}static max(){return new O(new M(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&&v(),void 0===n?n=e.length-t:n>e.length-t&&v(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===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.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let s=0;s<n;s++){const n=e.get(s),r=t.get(s);if(n<r)return-1;if(n>r)return 1}return e.length<t.length?-1:e.length>t.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()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new T(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="",s=0;const r=()=>{if(0===n.length)throw new T(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(;s<e.length;){const t=e[s];if("\\"===t){if(s+1===e.length)throw new T(E.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[s+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new T(E.INVALID_ARGUMENT,"Path has invali
2d escape sequence: "+e);n+=t,s+=2}else"`"===t?(i=!i,s++):"."!==t||i?(n+=t,s++):(r(),s++)}if(r(),i)throw new T(E.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new q(t)}static emptyPath(){return new q([])}}class B{constructor(e){this.path=e}static fromPath(e){return new B(P.fromString(e))}static fromName(e){return new B(P.fromString(e).popFirst(5))}static empty(){return new B(P.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===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,s){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=s}}$.UNKNOWN_ID=-1;function K(e,t){const n=e.toTimestamp().seconds,s=e.toTimestamp().nanoseconds+1,r=O.fromTimestamp(1e9===s?new M(n+1,0):new M(n,s));return new Q(r,B.empty(),t)}function z(e){return new Q(e.readTime,e.key,-1)}class Q{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Q(O.min(),B.empty(),-1)}static max(){return new Q(O.max(),B.empty(),-1)}}function G(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 W{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function H(e){if(e.code!==E.FAILED_PRECONDITION||e.message!==j)throw e;m("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&&v(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new Y((n,s)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,s)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,s)}})}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 s=0,r=0,i=!1;e.forEach(e=>{++s,e.next(()=>{++r,i&&r===s&&t()},e=>n(e))}),i=!0,r===s&&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,s)=>{n.push(t.call(this,e,s))}),this.waitFor(n)}static mapArray(e,t){return new Y((n,s)=>{const r=e.length,i=new Array(r);let o=0;for(let a=0;a<r;a++){const u=a;t(e[u]).next(e=>{i[u]=e,++o,o===r&&n(i)},e=>s(e))}})}static doWhile(e,t){return new Y((n,s)=>{const r=()=>{!0===e()?t().next(()=>{r()},s):n()};r()})}}function X(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}function J(e){return"IndexedDbTransactionError"===e.name}class Z{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ie(e),this.se=e=>t.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.se&&this.se(e),e}}function ee(e){return null==e}function te(e){return 0===e&&1/e==-1/0}function ne(e){return"number"==typeof e&&Number.isInteger(e)&&!te(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}Z.oe=-1;
vendor: 5,445 bytes, line 2
2const se=["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"],ie=re,oe=[...ie,"indexConfiguration","indexState","indexEntries"];function ae(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ue(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function ce(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class le{constructor(e,t){this.comparator=e,this.root=t||de.EMPTY}insert(e,t){return new le(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,de.BLACK,null,null))}remove(e){return new le(this.comparator,this.root.remove(e,this.comparator).copy(null,null,de.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 s=this.comparator(e,n.key);if(0===s)return t+n.left.size;s<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 he(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new he(this.root,e,this.comparator,!1)}getReverseIterator(){return new he(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new he(this.root,e,this.comparator,!0)}}class he{constructor(e,t,n,s){this.isReverse=s,this.nodeStack=[];let r=1;for(;!e.isEmpty();)if(r=t?n(e.key,t):1,t&&s&&(r*=-1),r<0)e=this.isReverse?e.left:e.right;else{if(0===r){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 de{constructor(e,t,n,s,r){this.key=e,this.value=t,this.color=null!=n?n:de.RED,this.left=null!=s?s:de.EMPTY,this.right=null!=r?r:de.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,s,r){return new de(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=s?s:this.left,null!=r?r: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 s=this;const r=n(e,s.key);return s=r<0?s.copy(null,null,null,s.left.insert(e,t,n),null):0===r?s.copy(null,t,null,null,null):s.copy(null,null,null,null,s.right.insert(e,t,n)),s.fixUp()}removeMin(){if(this.left.isEmpty())return de.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,s=this;if(t(e,s.key)<0)s.left.isEmpty()||s.left.isRed()||s.left.left.isRed()||(s=s.moveRedLeft()),s=s.copy(null,null,null,s.left.remove(e,t),null);else{if(s.left.isRed()&&(s=s.rotateRight()),s.right.isEmpty()||s.right.isRed()||s.right.left.isRed()||(s=s.moveRedRight()),0===t(e,s.key)){if(s.right.isEmpty())return de.EMPTY;n=s.right.min(),s=s.copy(n.key,n.value,null,null,s.right.removeMin())}s=s.copy(null,null,null,null,s.right.remove(e,t))}return s.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,de.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,de.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw v();if(this.right.isRed())throw v();const e=this.left.check();if(e!==this.right.check())throw v();return e+(this.isRed()?0:1)}}
2de.EMPTY=null,de.RED=!0,de.BLACK=!1,de.EMPTY=new class{constructor(){this.size=0}get key(){throw v()}get value(){throw v()}get color(){throw v()}get left(){throw v()}get right(){throw v()}copy(e,t,n,s,r){return this}insert(e,t,n){return new de(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 fe{constructor(e){this.comparator=e,this.data=new le(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 s=n.getNext();if(this.comparator(s.key,e[1])>=0)return;t(s.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 me(this.data.getIterator())}getIteratorFrom(e){return new me(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof fe))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,s=n.getNext().key;if(0!==this.comparator(e,s))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 fe(this.comparator);return t.data=e,t}}class me{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class pe{constructor(e){this.fields=e,e.sort(q.comparator)}static empty(){return new pe([])}unionWith(e){let t=new fe(q.comparator);for(const n of this.fields)t=t.add(n);for(const n of e)t=t.add(n);return new pe(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 ge extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ye{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 ge("Invalid base64 string: "+e):e}}(e);return new ye(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new ye(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return L(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ye.EMPTY_BYTE_STRING=new ye("");const ve=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function we(e){if(w(!!e),"string"==typeof e){let t=0;const n=ve.exec(e);if(w(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const s=new Date(e);return{seconds:Math.floor(s.getTime()/1e3),nanos:t}}return{seconds:_e(e.seconds),nanos:_e(e.nanos)}}function _e(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ee(e){return"string"==typeof e?ye.fromBase64String(e):ye.fromUint8Array(e)}function Te(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function Ie(e){const t=e.mapValue.fields.__previous_value__;return Te(t)?Ie(t):t}function Ce(e){const t=we(e.mapValue.fields.__local_write_time__.timestampValue);return new M(t.seconds,t.nanos)}class Se{constructor(e,t,n,s,r,i,o,a,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=s,this.ssl=r,this.forceLongPolling=i,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=u}}class Ae{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Ae("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Ae&&e.projectId===this.projectId&&e.database===this.database}}const Ne={mapValue:{fields:{__type__:{stringValue:"__max__"}}}};function be(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?Te(e)?4:ze(e)?9007199254740991:$e(e)?10:11:v()}function De(e,t){if(e===t)return!0;const n=be(e);if(n!==be(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Ce(e).isEqual(Ce(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=we(e.timestampValue),s=we(t.timestampValue);return n.seconds===s.seconds&&n.nanos===s.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return Ee(e.bytesValue).isEqual(Ee(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return _e(e.geoPointValue.latitude)===_e(t.geoPointValue.latitude)&&_e(e.geoPointValue.longitude)===_e(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return _e(e.integerValue)===_e(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=_e(e.doubleValue),s=_e(t.doubleValue);return n===s?te(n)===te(s):isNaN(n)&&isNaN(s)}return!1}(e,t);case 9:return V(e.arrayValue.values||[],t.arrayValue.values||[],De);case 10:case 11:return function(e,t){const n=e.mapValue.fields||{},s=t.mapValue.fields||{};if(ae(n)!==ae(s))return!1;for(const r in n)if(n.hasOwnProperty(r)&&(void 0===s[r]||!De(n[r],s[r])))return!1;return!0}(e,t);default:return v()}}function ke(e,t){return void 0!==(e.values||[]).find(e=>De(e,t))}function Re(e,t){if(e===t)return 0;const n=be(e),s=be(t);if(n!==s)return L(n,s);switch(n){case 0:case 9007199254740991:return 0;case 1:return L(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=_e(e.integerValue||e.doubleValue),s=_e(t.integerValue||t.doubleValue);return n<s?-1:n>s?1:n===s?0:isNaN(n)?isNaN(s)?0:-1:1}(e,t);case 3:return xe(e.timestampValue,t.timestampValue);case 4:return xe(Ce(e),Ce(t));case 5:return L(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ee(e),s=Ee(t);return n.compareTo(s)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),s=t.split("/");for(let r=0;r<n.length&&r<s.length;r++){const e=L(n[r],s[r]);if(0!==e)return e}return L(n.length,s.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=L(_e(e.latitude),_e(t.latitude));return 0!==n?n:L(_e(e.longitude),_e(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return Le(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,s,r,i;const o=e.fields||{},a=t.fields||{},u=null===(n=o.value)||void 0===n?void 0:n.arrayValue,c=null===(s=a.value)||void 0===s?void 0:s.arrayValue,l=L((null===(r=null==u?void 0:u.values)||void 0===r?void 0:r.length)||0,(null===(i=null==c?void 0:c.values)||void 0===i?void 0:i.length)||0);return 0!==l?l:Le(u,c)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===Ne.mapValue&&t===Ne.mapValue)return 0;if(e===Ne.mapValue)return 1;if(t===Ne.mapValue)return-1;const n=e.fields||{},s=Object.keys(n),r=t.fields||{},i=Object.keys(r);s.sort(),i.sort();for(let o=0;o<s.length&&o<i.length;++o){const e=L(s[o],i[o]);if(0!==e)return e;const t=Re(n[s[o]],r[i[o]]);if(0!==t)return t}return L(s.length,i.length)}(e.mapValue,t.mapValue);default:throw v()}}function xe(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return L(e,t);const n=we(e),s=we(t),r=L(n.seconds,s.seconds);return 0!==r?r:L(n.nanos,s.nanos)}function Le(e,t){const n=e.values||[],s=t.values||[];for(let r=0;r<n.length&&r<s.length;++r){const e=Re(n[r],s[r]);if(e)return e}return L(n.length,s.length)}function Ve(e){return Me(e)}function Me(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=we(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return Ee(e).toBase64()}
2(e.bytesValue):"referenceValue"in e?function(e){return B.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const s of e.values||[])n?n=!1:t+=",",t+=Me(s);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",s=!0;for(const r of t)s?s=!1:n+=",",n+=`${r}:${Me(e.fields[r])}`;return n+"}"}(e.mapValue):v()}function Oe(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Fe(e){return!!e&&"integerValue"in e}function Pe(e){return!!e&&"arrayValue"in e}function Ue(e){return!!e&&"nullValue"in e}function qe(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Be(e){return!!e&&"mapValue"in e}function $e(e){var t,n;return"__vector__"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function Ke(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return ue(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=Ke(n)),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Ke(e.arrayValue.values[n]);return t}return Object.assign({},e)}function ze(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}class Qe{constructor(e){this.value=e}static empty(){return new Qe({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!Be(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Ke(t)}setAll(e){let t=q.emptyPath(),n={},s=[];e.forEach((e,r)=>{if(!t.isImmediateParentOf(r)){const e=this.getFieldsMap(t);this.applyChanges(e,n,s),n={},s=[],t=r.popLast()}e?n[r.lastSegment()]=Ke(e):s.push(r.lastSegment())});const r=this.getFieldsMap(t);this.applyChanges(r,n,s)}delete(e){const t=this.field(e.popLast());Be(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return De(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let s=t.mapValue.fields[e.get(n)];Be(s)&&s.mapValue.fields||(s={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=s),t=s}return t.mapValue.fields}applyChanges(e,t,n){ue(t,(t,n)=>e[t]=n);for(const s of n)delete e[s]}clone(){return new Qe(Ke(this.value))}}function Ge(e){const t=[];return ue(e.fields,(e,n)=>{const s=new q([e]);if(Be(n)){const e=Ge(n.mapValue).fields;if(0===e.length)t.push(s);else for(const n of e)t.push(s.child(n))}else t.push(s)}),new pe(t)}class je{constructor(e,t,n,s,r,i,o){this.key=e,this.documentType=t,this.version=n,this.readTime=s,this.createTime=r,this.data=i,this.documentState=o}static newInvalidDocument(e){return new je(e,0,O.min(),O.min(),O.min(),Qe.empty(),0)}static newFoundDocument(e,t,n,s){return new je(e,1,t,O.min(),n,s,0)}static newNoDocument(e,t){return new je(e,2,t,O.min(),O.min(),Qe.empty(),0)}static newUnknownDocument(e,t){return new je(e,3,t,O.min(),O.min(),Qe.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(O.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=Qe.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Qe.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=O.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 je&&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 je(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}})`}}
2class We{constructor(e,t){this.position=e,this.inclusive=t}}function He(e,t,n){let s=0;for(let r=0;r<e.position.length;r++){const i=t[r],o=e.position[r];if(s=i.field.isKeyField()?B.comparator(B.fromName(o.referenceValue),n.key):Re(o,n.data.field(i.field)),"desc"===i.dir&&(s*=-1),0!==s)break}return s}function Ye(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!De(e.position[n],t.position[n]))return!1;return!0}class Xe{constructor(e,t="asc"){this.field=e,this.dir=t}}function Je(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class Ze{}class et extends Ze{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new ut(e,t,n):"array-contains"===t?new dt(e,n):"in"===t?new ft(e,n):"not-in"===t?new mt(e,n):"array-contains-any"===t?new pt(e,n):new et(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new ct(e,n):new lt(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Re(t,this.value)):null!==t&&be(this.value)===be(t)&&this.matchesComparison(Re(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return v()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class tt extends Ze{constructor(e,t){super(),this.filters=e,this.op=t,this.ae=null}static create(e,t){return new tt(e,t)}matches(e){return nt(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function nt(e){return"and"===e.op}function st(e){return rt(e)&&nt(e)}function rt(e){for(const t of e.filters)if(t instanceof tt)return!1;return!0}function it(e){if(e instanceof et)return e.field.canonicalString()+e.op.toString()+Ve(e.value);if(st(e))return e.filters.map(e=>it(e)).join(",");{const t=e.filters.map(e=>it(e)).join(",");return`${e.op}(${t})`}}function ot(e,t){return e instanceof et?function(e,t){return t instanceof et&&e.op===t.op&&e.field.isEqual(t.field)&&De(e.value,t.value)}(e,t):e instanceof tt?function(e,t){return t instanceof tt&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce((e,n,s)=>e&&ot(n,t.filters[s]),!0)}(e,t):void v()}function at(e){return e instanceof et?function(e){return`${e.field.canonicalString()} ${e.op} ${Ve(e.value)}`}(e):e instanceof tt?function(e){return e.op.toString()+" {"+e.getFilters().map(at).join(" ,")+"}"}(e):"Filter"}class ut extends et{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 ct extends et{constructor(e,t){super(e,"in",t),this.keys=ht("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class lt extends et{constructor(e,t){super(e,"not-in",t),this.keys=ht("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function ht(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>B.fromName(e.referenceValue))}class dt extends et{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Pe(t)&&ke(t.arrayValue,this.value)}}class ft extends et{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&ke(this.value.arrayValue,t)}}class mt extends et{constructor(e,t){super(e,"not-in",t)}matches(e){if(ke(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!ke(this.value.arrayValue,t)}}class pt extends et{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Pe(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>ke(this.value.arrayValue,e))}}class gt{constructor(e,t=null,n=[],s=[],r=null,i=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=s,this.limit=r,this.startAt=i,this.endAt=o,this.ue=null}}function yt(e,t=null,n=[],s=[],r=null,i=null,o=null){return new gt(e,t,n,s,r,i,o)}function vt(e){const t=_(e);if(null===t.ue){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>it(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),ee(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ve(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ve(e)).join(",")),t.ue=e}return t.ue}function wt(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!Je(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!ot(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Ye(e.startAt,t.startAt)&&Ye(e.endAt,t.endAt)}function _t(e){return B.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class Et{constructor(e,t=null,n=[],s=[],r=null,i="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=s,this.limit=r,this.limitType=i,this.startAt=o,this.endAt=a,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function Tt(e,t,n,s,r,i,o,a){return new Et(e,t,n,s,r,i,o,a)}function It(e){return new Et(e)}function Ct(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function St(e){return null!==e.collectionGroup}function At(e){const t=_(e);if(null===t.ce){t.ce=[];const e=new Set;for(const r of t.explicitOrderBy)t.ce.push(r),e.add(r.field.canonicalString());const n=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc",s=function(e){let t=new fe(q.comparator);
2return e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t}(t);s.forEach(s=>{e.has(s.canonicalString())||s.isKeyField()||t.ce.push(new Xe(s,n))}),e.has(q.keyField().canonicalString())||t.ce.push(new Xe(q.keyField(),n))}return t.ce}function Nt(e){const t=_(e);return t.le||(t.le=bt(t,At(e))),t.le}function bt(e,t){if("F"===e.limitType)return yt(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 Xe(e.field,t)});const n=e.endAt?new We(e.endAt.position,e.endAt.inclusive):null,s=e.startAt?new We(e.startAt.position,e.startAt.inclusive):null;return yt(e.path,e.collectionGroup,t,e.filters,e.limit,n,s)}}function Dt(e,t){const n=e.filters.concat([t]);return new Et(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function kt(e,t,n){return new Et(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Rt(e,t){return wt(Nt(e),Nt(t))&&e.limitType===t.limitType}function xt(e){return`${vt(Nt(e))}|lt:${e.limitType}`}function Lt(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=>at(e)).join(", ")}]`),ee(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=>Ve(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ve(e)).join(",")),`Target(${t})`}(Nt(e))}; limitType=${e.limitType})`}function Vt(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 At(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 s=He(e,t,n);return e.inclusive?s<=0:s<0}(e.startAt,At(e),t))&&!(e.endAt&&!function(e,t,n){const s=He(e,t,n);return e.inclusive?s>=0:s>0}(e.endAt,At(e),t))}(e,t)}function Mt(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Ot(e){return(t,n)=>{let s=!1;for(const r of At(e)){const e=Ft(r,t,n);if(0!==e)return e;s=s||r.field.isKeyField()}return 0}}function Ft(e,t,n){const s=e.field.isKeyField()?B.comparator(t.key,n.key):function(e,t,n){const s=t.data.field(e),r=n.data.field(e);return null!==s&&null!==r?Re(s,r):v()}(e.field,t,n);switch(e.dir){case"asc":return s;case"desc":return-1*s;default:return v()}}class Pt{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[s,r]of n)if(this.equalsFn(s,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),s=this.inner[n];if(void 0===s)return this.inner[n]=[[e,t]],void this.innerSize++;for(let r=0;r<s.length;r++)if(this.equalsFn(s[r][0],e))return void(s[r]=[e,t]);s.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let s=0;s<n.length;s++)if(this.equalsFn(n[s][0],e))return 1===n.length?delete this.inner[t]:n.splice(s,1),this.innerSize--,!0;return!1}forEach(e){ue(this.inner,(t,n)=>{for(const[s,r]of n)e(s,r)})}isEmpty(){return ce(this.inner)}size(){return this.innerSize}}const Ut=new le(B.comparator);function qt(){return Ut}const Bt=new le(B.comparator);function $t(...e){let t=Bt;for(const n of e)t=t.insert(n.key,n);return t}function Kt(e){let t=Bt;return e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t}function zt(){return Gt()}function Qt(){return Gt()}function Gt(){return new Pt(e=>e.toString(),(e,t)=>e.isEqual(t))}const jt=new le(B.comparator),Wt=new fe(B.comparator);function Ht(...e){let t=Wt;for(const n of e)t=t.add(n);return t}const Yt=new fe(L);function Xt(){return Yt}function Jt(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:te(t)?"-0":t}}function Zt(e){return{integerValue:""+e}}function en(e,t){return ne(t)?Zt(t):Jt(e,t)}class tn{constructor(){this._=void 0}}function nn(e,t,n){return e instanceof on?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&Te(t)&&(t=Ie(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof an?un(e,t):e instanceof cn?ln(e,t):function(e,t){const n=rn(e,t),s=dn(n)+dn(e.Pe);return Fe(n)&&Fe(e.Pe)?Zt(s):Jt(e.serializer,s)}(e,t)}function sn(e,t,n){return e instanceof an?un(e,t):e instanceof cn?ln(e,t):n}function rn(e,t){return e instanceof hn?function(e){return Fe(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class on extends tn{}class an extends tn{constructor(e){super(),this.elements=e}}function un(e,t){const n=fn(t);for(const s of e.elements)n.some(e=>De(e,s))||n.push(s);return{arrayValue:{values:n}}}class cn extends tn{constructor(e){super(),this.elements=e}}function ln(e,t){let n=fn(t);for(const s of e.elements)n=n.filter(e=>!De(e,s));return{arrayValue:{values:n}}}
2class hn extends tn{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function dn(e){return _e(e.integerValue||e.doubleValue)}function fn(e){return Pe(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class mn{constructor(e,t){this.version=e,this.transformResults=t}}class pn{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new pn}static exists(e){return new pn(void 0,e)}static updateTime(e){return new pn(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 gn(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class yn{}function vn(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new bn(e.key,pn.none()):new In(e.key,e.data,pn.none());{const n=e.data,s=Qe.empty();let r=new fe(q.comparator);for(let e of t.fields)if(!r.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?s.delete(e):s.set(e,t),r=r.add(e)}return new Cn(e.key,s,new pe(r.toArray()),pn.none())}}function wn(e,t,n){e instanceof In?function(e,t,n){const s=e.value.clone(),r=An(e.fieldTransforms,t,n.transformResults);s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):e instanceof Cn?function(e,t,n){if(!gn(e.precondition,t))return void t.convertToUnknownDocument(n.version);const s=An(e.fieldTransforms,t,n.transformResults),r=t.data;r.setAll(Sn(e)),r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function _n(e,t,n,s){return e instanceof In?function(e,t,n,s){if(!gn(e.precondition,t))return n;const r=e.value.clone(),i=Nn(e.fieldTransforms,s,t);return r.setAll(i),t.convertToFoundDocument(t.version,r).setHasLocalMutations(),null}(e,t,n,s):e instanceof Cn?function(e,t,n,s){if(!gn(e.precondition,t))return n;const r=Nn(e.fieldTransforms,s,t),i=t.data;return i.setAll(Sn(e)),i.setAll(r),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,s):function(e,t,n){return gn(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function En(e,t){let n=null;for(const s of e.fieldTransforms){const e=t.data.field(s.field),r=rn(s.transform,e||null);null!=r&&(null===n&&(n=Qe.empty()),n.set(s.field,r))}return n||null}function Tn(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 an&&t instanceof an||e instanceof cn&&t instanceof cn?V(e.elements,t.elements,De):e instanceof hn&&t instanceof hn?De(e.Pe,t.Pe):e instanceof on&&t instanceof on}(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 In extends yn{constructor(e,t,n,s=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=s,this.type=0}getFieldMask(){return null}}class Cn extends yn{constructor(e,t,n,s,r=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=s,this.fieldTransforms=r,this.type=1}getFieldMask(){return this.fieldMask}}function Sn(e){const t=new Map;return e.fieldMask.fields.forEach(n=>{if(!n.isEmpty()){const s=e.data.field(n);t.set(n,s)}}),t}function An(e,t,n){const s=new Map;w(e.length===n.length);for(let r=0;r<n.length;r++){const i=e[r],o=i.transform,a=t.data.field(i.field);s.set(i.field,sn(o,a,n[r]))}return s}function Nn(e,t,n){const s=new Map;for(const r of e){const e=r.transform,i=n.data.field(r.field);s.set(r.field,nn(e,i,t))}return s}class bn extends yn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Dn extends yn{constructor(e,t){super(),this.key=e,this.prec
2ondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class kn{constructor(e,t,n,s){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=s}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let s=0;s<this.mutations.length;s++){const t=this.mutations[s];t.key.isEqual(e.key)&&wn(t,e,n[s])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=_n(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=_n(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=Qt();return this.mutations.forEach(s=>{const r=e.get(s.key),i=r.overlayedDocument;let o=this.applyToLocalView(i,r.mutatedFields);o=t.has(s.key)?null:o;const a=vn(i,o);null!==a&&n.set(s.key,a),i.isValidDocument()||i.convertToNoDocument(O.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Ht())}isEqual(e){return this.batchId===e.batchId&&V(this.mutations,e.mutations,(e,t)=>Tn(e,t))&&V(this.baseMutations,e.baseMutations,(e,t)=>Tn(e,t))}}class Rn{constructor(e,t,n,s){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=s}static from(e,t,n){w(e.mutations.length===n.length);let s=jt;const r=e.mutations;for(let i=0;i<r.length;i++)s=s.insert(r[i].key,n[i].version);return new Rn(e,t,n,s)}}class xn{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 Ln{constructor(e,t){this.count=e,this.unchangedNames=t}}var Vn,Mn;function On(e){switch(e){default:return v();case E.CANCELLED:case E.UNKNOWN:case E.DEADLINE_EXCEEDED:case E.RESOURCE_EXHAUSTED:case E.INTERNAL:case E.UNAVAILABLE:case E.UNAUTHENTICATED:return!1;case E.INVALID_ARGUMENT:case E.NOT_FOUND:case E.ALREADY_EXISTS:case E.PERMISSION_DENIED:case E.FAILED_PRECONDITION:case E.ABORTED:case E.OUT_OF_RANGE:case E.UNIMPLEMENTED:case E.DATA_LOSS:return!0}}function Fn(e){if(void 0===e)return p("GRPC error has no .code"),E.UNKNOWN;switch(e){case Vn.OK:return E.OK;case Vn.CANCELLED:return E.CANCELLED;case Vn.UNKNOWN:return E.UNKNOWN;case Vn.DEADLINE_EXCEEDED:return E.DEADLINE_EXCEEDED;case Vn.RESOURCE_EXHAUSTED:return E.RESOURCE_EXHAUSTED;case Vn.INTERNAL:return E.INTERNAL;case Vn.UNAVAILABLE:return E.UNAVAILABLE;case Vn.UNAUTHENTICATED:return E.UNAUTHENTICATED;case Vn.INVALID_ARGUMENT:return E.INVALID_ARGUMENT;case Vn.NOT_FOUND:return E.NOT_FOUND;case Vn.ALREADY_EXISTS:return E.ALREADY_EXISTS;case Vn.PERMISSION_DENIED:return E.PERMISSION_DENIED;case Vn.FAILED_PRECONDITION:return E.FAILED_PRECONDITION;case Vn.ABORTED:return E.ABORTED;case Vn.OUT_OF_RANGE:return E.OUT_OF_RANGE;case Vn.UNIMPLEMENTED:return E.UNIMPLEMENTED;case Vn.DATA_LOSS:return E.DATA_LOSS;default:return v()}}(Mn=Vn||(Vn={}))[Mn.OK=0]="OK",Mn[Mn.CANCELLED=1]="CANCELLED",Mn[Mn.UNKNOWN=2]="UNKNOWN",Mn[Mn.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Mn[Mn.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Mn[Mn.NOT_FOUND=5]="NOT_FOUND",Mn[Mn.ALREADY_EXISTS=6]="ALREADY_EXISTS",Mn[Mn.PERMISSION_DENIED=7]="PERMISSION_DENIED",Mn[Mn.UNAUTHENTICATED=16]="UNAUTHENTICATED",Mn[Mn.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Mn[Mn.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Mn[Mn.ABORTED=10]="ABORTED",Mn[Mn.OUT_OF_RANGE=11]="OUT_OF_RANGE",Mn[Mn.UNIMPLEMENTED=12]="UNIMPLEMENTED",Mn[Mn.INTERNAL=13]="INTERNAL",Mn[Mn.UNAVAILABLE=14]="UNAVAILABLE",Mn[Mn.DATA_LOSS=15]="DATA_LOSS";let Pn=null;function Un(){return new TextEncoder}const qn=new a.jz([4294967295,4294967295],0);function Bn(e){const t=Un().encode(e),n=new a.VV;return n.update(t),new Uint8Array(n.digest())}function $n(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),s=t.getUint32(4,!0),r=t.getUint32(8,!0),i=t.getUint32(12,!0);return[new a.jz([n,s],0),new a.jz([r,i],0)]}class Kn{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new zn(`Invalid padding: ${t}`);if(n<0)throw new zn(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new zn(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new zn(`Invalid padding when bitmap length is 0: ${t}`);this.Ie=8*e.length-t,this.Te=a.jz.fromNumber(this.Ie)}Ee(e,t,n){let s=e.add(t.multiply(a.jz.fromNumber(n)));return 1===s.compare(qn)&&(s=new a.jz([s.getBits(0),s.getBits(1)],0)),s.modulo(this.Te).toNumber()}de(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ie)return!1;const t=Bn(e),[n,s]=$n(t);for(let r=0;r<this.hashCount;r++){const e=this.Ee(n,s,r);if(!this.de(e))return!1}return!0}static create(e,t,n){const s=e%8==0?0:8-e%8,r=new Uint8Array(Math.ceil(e/8)),i=new Kn(r,s,t);
2return n.forEach(e=>i.insert(e)),i}insert(e){if(0===this.Ie)return;const t=Bn(e),[n,s]=$n(t);for(let r=0;r<this.hashCount;r++){const e=this.Ee(n,s,r);this.Ae(e)}}Ae(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class zn extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Qn{constructor(e,t,n,s,r){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=s,this.resolvedLimboDocuments=r}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const s=new Map;return s.set(e,Gn.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Qn(O.min(),s,new le(L),qt(),Ht())}}class Gn{constructor(e,t,n,s,r){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=s,this.removedDocuments=r}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new Gn(n,t,Ht(),Ht(),Ht())}}class jn{constructor(e,t,n,s){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=s}}class Wn{constructor(e,t){this.targetId=e,this.me=t}}class Hn{constructor(e,t,n=ye.EMPTY_BYTE_STRING,s=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=s}}class Yn{constructor(){this.fe=0,this.ge=Zn(),this.pe=ye.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){e.approximateByteSize()>0&&(this.we=!0,this.pe=e)}ve(){let e=Ht(),t=Ht(),n=Ht();return this.ge.forEach((s,r)=>{switch(r){case 0:e=e.add(s);break;case 2:t=t.add(s);break;case 1:n=n.add(s);break;default:v()}}),new Gn(this.pe,this.ye,e,t,n)}Ce(){this.we=!1,this.ge=Zn()}Fe(e,t){this.we=!0,this.ge=this.ge.insert(e,t)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){this.fe-=1,w(this.fe>=0)}Ne(){this.we=!0,this.ye=!0}}class Xn{constructor(e){this.Le=e,this.Be=new Map,this.ke=qt(),this.qe=Jn(),this.Qe=new le(L)}Ke(e){for(const t of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.$e(t,e.Ve):this.Ue(t,e.key,e.Ve);for(const t of e.removedTargetIds)this.Ue(t,e.key,e.Ve)}We(e){this.forEachTarget(e,t=>{const n=this.Ge(t);switch(e.state){case 0:this.ze(t)&&n.De(e.resumeToken);break;case 1:n.Oe(),n.Se||n.Ce(),n.De(e.resumeToken);break;case 2:n.Oe(),n.Se||this.removeTarget(t);break;case 3:this.ze(t)&&(n.Ne(),n.De(e.resumeToken));break;case 4:this.ze(t)&&(this.je(t),n.De(e.resumeToken));break;default:v()}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Be.forEach((e,n)=>{this.ze(n)&&t(n)})}He(e){const t=e.targetId,n=e.me.count,s=this.Je(t);if(s){const r=s.target;if(_t(r))if(0===n){const e=new B(r.path);this.Ue(t,e,je.newNoDocument(e,O.min()))}else w(1===n);else{const s=this.Ye(t);if(s!==n){const n=this.Ze(e),r=n?this.Xe(n,e,s):1;if(0!==r){this.je(t);const e=2===r?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Qe=this.Qe.insert(t,e)}null==Pn||Pn.et(function(e,t,n,s,r){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===r,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==s?void 0:s.mightContain(e))&&void 0!==t&&t}}),h}(s,e.me,this.Le.tt(),n,r))}}}}Ze(e){const t=e.me.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:s=0},hashCount:r=0}=t;let i,o;try{i=Ee(n).toUint8Array()}catch(e){if(e instanceof ge)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 Kn(i,s,r)}catch(e){return g(e instanceof zn?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===o.Ie?null:o}Xe(e,t,n){return t.me.count===n-this.nt(e,t.targetId)?0:2}nt(e,t){const n=this.Le.getRemoteKeysForTarget(t);let s=0;
2return n.forEach(n=>{const r=this.Le.tt(),i=`projects/${r.projectId}/databases/${r.database}/documents/${n.path.canonicalString()}`;e.mightContain(i)||(this.Ue(t,n,null),s++)}),s}rt(e){const t=new Map;this.Be.forEach((n,s)=>{const r=this.Je(s);if(r){if(n.current&&_t(r.target)){const t=new B(r.target.path);null!==this.ke.get(t)||this.it(s,t)||this.Ue(s,t,je.newNoDocument(t,e))}n.be&&(t.set(s,n.ve()),n.Ce())}});let n=Ht();this.qe.forEach((e,t)=>{let s=!0;t.forEachWhile(e=>{const t=this.Je(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(s=!1,!1)}),s&&(n=n.add(e))}),this.ke.forEach((t,n)=>n.setReadTime(e));const s=new Qn(e,t,this.Qe,this.ke,n);return this.ke=qt(),this.qe=Jn(),this.Qe=new le(L),s}$e(e,t){if(!this.ze(e))return;const n=this.it(e,t.key)?2:0;this.Ge(e).Fe(t.key,n),this.ke=this.ke.insert(t.key,t),this.qe=this.qe.insert(t.key,this.st(t.key).add(e))}Ue(e,t,n){if(!this.ze(e))return;const s=this.Ge(e);this.it(e,t)?s.Fe(t,1):s.Me(t),this.qe=this.qe.insert(t,this.st(t).delete(e)),n&&(this.ke=this.ke.insert(t,n))}removeTarget(e){this.Be.delete(e)}Ye(e){const t=this.Ge(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}xe(e){this.Ge(e).xe()}Ge(e){let t=this.Be.get(e);return t||(t=new Yn,this.Be.set(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new fe(L),this.qe=this.qe.insert(e,t)),t}ze(e){const t=null!==this.Je(e);return t||m("WatchChangeAggregator","Detected inactive target",e),t}Je(e){const t=this.Be.get(e);return t&&t.Se?null:this.Le.ot(e)}je(e){this.Be.set(e,new Yn),this.Le.getRemoteKeysForTarget(e).forEach(t=>{this.Ue(e,t,null)})}it(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function Jn(){return new le(B.comparator)}function Zn(){return new le(B.comparator)}const es={asc:"ASCENDING",desc:"DESCENDING"},ts={"<":"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"},ns={and:"AND",or:"OR"};class ss{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function rs(e,t){return e.useProto3Json||ee(t)?t:{value:t}}function is(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 os(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function as(e,t){return is(e,t.toTimestamp())}function us(e){return w(!!e),O.fromTimestamp(function(e){const t=we(e);return new M(t.seconds,t.nanos)}(e))}function cs(e,t){return ls(e,t).canonicalString()}function ls(e,t){const n=function(e){return new P(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===t?n:n.child(t)}function hs(e){const t=P.fromString(e);return w(Rs(t)),t}function ds(e,t){return cs(e.databaseId,t.path)}function fs(e,t){const n=hs(t);if(n.get(1)!==e.databaseId.projectId)throw new T(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 T(E.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new B(ys(n))}function ms(e,t){return cs(e.databaseId,t)}function ps(e){const t=hs(e);return 4===t.length?P.emptyPath():ys(t)}function gs(e){return new P(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function ys(e){return w(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function vs(e,t,n){return{name:ds(e,t),fields:n.value.mapValue.fields}}function ws(e,t){let n;if(t instanceof In)n={update:vs(e,t.key,t.value)};else if(t instanceof bn)n={delete:ds(e,t.key)};else if(t instanceof Cn)n={update:vs(e,t.key,t.data),updateMask:ks(t.fieldMask)};else{if(!(t instanceof Dn))return v();n={verify:ds(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e,t){const n=t.transform;if(n instanceof on)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof an)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof cn)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof hn)return{fieldPath:t.field.canonicalString(),increment:n.Pe};
2throw v()}(0,e))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:as(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:v()}(e,t.precondition)),n}function _s(e,t){return{documents:[ms(e,t.path)]}}function Es(e,t){const n={structuredQuery:{}},s=t.path;let r;null!==t.collectionGroup?(r=s,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(r=s.popLast(),n.structuredQuery.from=[{collectionId:s.lastSegment()}]),n.parent=ms(e,r);const i=function(e){if(0!==e.length)return Ds(tt.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);const o=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:Ns(e.field),direction:Cs(e.dir)}}(e))}(t.orderBy);o&&(n.structuredQuery.orderBy=o);const a=rs(e,t.limit);return null!==a&&(n.structuredQuery.limit=a),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)),{_t:n,parent:r}}function Ts(e){let t=ps(e.parent);const n=e.structuredQuery,s=n.from?n.from.length:0;let r=null;if(s>0){w(1===s);const e=n.from[0];e.allDescendants?r=e.collectionId:t=t.child(e.collectionId)}let i=[];n.where&&(i=function(e){const t=Is(e);return t instanceof tt&&st(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=function(e){return e.map(e=>function(e){return new Xe(bs(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,ee(t)?null:t}(n.limit));let u=null;n.startAt&&(u=function(e){const t=!!e.before,n=e.values||[];return new We(n,t)}(n.startAt));let c=null;return n.endAt&&(c=function(e){const t=!e.before,n=e.values||[];return new We(n,t)}(n.endAt)),Tt(t,r,o,i,a,"F",u,c)}function Is(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=bs(e.unaryFilter.field);return et.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=bs(e.unaryFilter.field);return et.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const s=bs(e.unaryFilter.field);return et.create(s,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const r=bs(e.unaryFilter.field);return et.create(r,"!=",{nullValue:"NULL_VALUE"});default:return v()}}(e):void 0!==e.fieldFilter?function(e){return et.create(bs(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return v()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return tt.create(e.compositeFilter.filters.map(e=>Is(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return v()}}(e.compositeFilter.op))}(e):v()}function Cs(e){return es[e]}function Ss(e){return ts[e]}function As(e){return ns[e]}function Ns(e){return{fieldPath:e.canonicalString()}}function bs(e){return q.fromServerFormat(e.fieldPath)}function Ds(e){return e instanceof et?function(e){if("=="===e.op){if(qe(e.value))return{unaryFilter:{field:Ns(e.field),op:"IS_NAN"}};if(Ue(e.value))return{unaryFilter:{field:Ns(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(qe(e.value))return{unaryFilter:{field:Ns(e.field),op:"IS_NOT_NAN"}};if(Ue(e.value))return{unaryFilter:{field:Ns(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Ns(e.field),op:Ss(e.op),value:e.value}}}(e):e instanceof tt?function(e){const t=e.getFilters().map(e=>Ds(e));return 1===t.length?t[0]:{compositeFilter:{op:As(e.op),filters:t}}}(e):v()}function ks(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}function Rs(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class xs{constructor(e,t,n,s,r=O.min(),i=O.min(),o=ye.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=s,this.snapshotVersion=r,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new xs(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new xs(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new xs(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new xs(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Ls{constructor(e){this.ct=e}}function Vs(e){const t=Ts({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?kt(t,t.limit,"L"):t}class Ms{constructor(){}
2It(e,t){this.Tt(e,t),t.Et()}Tt(e,t){if("nullValue"in e)this.dt(t,5);else if("booleanValue"in e)this.dt(t,10),t.At(e.booleanValue?1:0);else if("integerValue"in e)this.dt(t,15),t.At(_e(e.integerValue));else if("doubleValue"in e){const n=_e(e.doubleValue);isNaN(n)?this.dt(t,13):(this.dt(t,15),te(n)?t.At(0):t.At(n))}else if("timestampValue"in e){let n=e.timestampValue;this.dt(t,20),"string"==typeof n&&(n=we(n)),t.Rt(`${n.seconds||""}`),t.At(n.nanos||0)}else if("stringValue"in e)this.Vt(e.stringValue,t),this.ft(t);else if("bytesValue"in e)this.dt(t,30),t.gt(Ee(e.bytesValue)),this.ft(t);else if("referenceValue"in e)this.yt(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.dt(t,45),t.At(n.latitude||0),t.At(n.longitude||0)}else"mapValue"in e?ze(e)?this.dt(t,Number.MAX_SAFE_INTEGER):$e(e)?this.wt(e.mapValue,t):(this.St(e.mapValue,t),this.ft(t)):"arrayValue"in e?(this.bt(e.arrayValue,t),this.ft(t)):v()}Vt(e,t){this.dt(t,25),this.Dt(e,t)}Dt(e,t){t.Rt(e)}St(e,t){const n=e.fields||{};this.dt(t,55);for(const s of Object.keys(n))this.Vt(s,t),this.Tt(n[s],t)}wt(e,t){var n,s;const r=e.fields||{};this.dt(t,53);const i="value",o=(null===(s=null===(n=r[i].arrayValue)||void 0===n?void 0:n.values)||void 0===s?void 0:s.length)||0;this.dt(t,15),t.At(_e(o)),this.Vt(i,t),this.Tt(r[i],t)}bt(e,t){const n=e.values||[];this.dt(t,50);for(const s of n)this.Tt(s,t)}yt(e,t){this.dt(t,37),B.fromName(e).path.forEach(e=>{this.dt(t,60),this.Dt(e,t)})}dt(e,t){e.At(t)}ft(e){e.At(2)}}Ms.vt=new Ms;class Os{constructor(){this.un=new Fs}addToCollectionParentIndex(e,t){return this.un.add(t),Y.resolve()}getCollectionParents(e,t){return Y.resolve(this.un.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(Q.min())}getMinOffsetFromCollectionGroup(e,t){return Y.resolve(Q.min())}updateCollectionGroup(e,t,n){return Y.resolve()}updateIndexEntries(e,t){return Y.resolve()}}class Fs{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),s=this.index[t]||new fe(P.comparator),r=!s.has(n);return this.index[t]=s.add(n),r}has(e){const t=e.lastSegment(),n=e.popLast(),s=this.index[t];return s&&s.has(n)}getEntries(e){return(this.index[e]||new fe(P.comparator)).toArray()}}new Uint8Array(0);class Ps{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Ps(e,Ps.DEFAULT_COLLECTION_PERCENTILE,Ps.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}Ps.DEFAULT_COLLECTION_PERCENTILE=10,Ps.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ps.DEFAULT=new Ps(41943040,Ps.DEFAULT_COLLECTION_PERCENTILE,Ps.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ps.DISABLED=new Ps(-1,0,0);class Us{constructor(e){this.Ln=e}next(){return this.Ln+=2,this.Ln}static Bn(){return new Us(0)}static kn(){return new Us(-1)}}class qs{constructor(){this.changes=new Pt(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,je.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 Bs{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class $s{constructor(e,t,n,s){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=s}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next(s=>(n=s,this.remoteDocumentCache.getEntry(e,t))).next(e=>(null!==n&&_n(n.mutation,e,pe.empty(),M.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,Ht()).next(()=>t))}getLocalViewOfDocuments(e,t,n=Ht()){const s=zt();return this.populateOverlays(e,s,t).next(()=>this.computeViews(e,t,s,n).next(e=>{let t=$t();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){const n=zt();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Ht()))}populateOverlays(e,t,n){const s=[];
2return n.forEach(e=>{t.has(e)||s.push(e)}),this.documentOverlayCache.getOverlays(e,s).next(e=>{e.forEach((e,n)=>{t.set(e,n)})})}computeViews(e,t,n,s){let r=qt();const i=Gt(),o=Gt();return t.forEach((e,t)=>{const o=n.get(t.key);s.has(t.key)&&(void 0===o||o.mutation instanceof Cn)?r=r.insert(t.key,t):void 0!==o?(i.set(t.key,o.mutation.getFieldMask()),_n(o.mutation,t,o.mutation.getFieldMask(),M.now())):i.set(t.key,pe.empty())}),this.recalculateAndSaveOverlays(e,r).next(e=>(e.forEach((e,t)=>i.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new Bs(t,null!==(n=i.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(e,t){const n=Gt();let s=new le((e,t)=>e-t),r=Ht();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(const r of e)r.keys().forEach(e=>{const i=t.get(e);if(null===i)return;let o=n.get(e)||pe.empty();o=r.applyToLocalView(i,o),n.set(e,o);const a=(s.get(r.batchId)||Ht()).add(e);s=s.insert(r.batchId,a)})}).next(()=>{const i=[],o=s.getReverseIterator();for(;o.hasNext();){const s=o.getNext(),a=s.key,u=s.value,c=Qt();u.forEach(e=>{if(!r.has(e)){const s=vn(t.get(e),n.get(e));null!==s&&c.set(e,s),r=r.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,s){return function(e){return B.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):St(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,s):this.getDocumentsMatchingCollectionQuery(e,t,n,s)}getNextDocuments(e,t,n,s){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,s).next(r=>{const i=s-r.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,s-r.size):Y.resolve(zt());let o=-1,a=r;return i.next(t=>Y.forEach(t,(t,n)=>(o<n.largestBatchId&&(o=n.largestBatchId),r.get(t)?Y.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{a=a.insert(t,e)}))).next(()=>this.populateOverlays(e,t,r)).next(()=>this.computeViews(e,a,t,Ht())).next(e=>({batchId:o,changes:Kt(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new B(t)).next(e=>{let t=$t();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,s){const r=t.collectionGroup;let i=$t();return this.indexManager.getCollectionParents(e,r).next(o=>Y.forEach(o,o=>{const a=function(e,t){return new Et(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,o.child(r));return this.getDocumentsMatchingCollectionQuery(e,a,n,s).next(e=>{e.forEach((e,t)=>{i=i.insert(e,t)})})}).next(()=>i))}getDocumentsMatchingCollectionQuery(e,t,n,s){let r;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(i=>(r=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,r,s))).next(e=>{r.forEach((t,n)=>{const s=n.getKey();null===e.get(s)&&(e=e.insert(s,je.newInvalidDocument(s)))});let n=$t();return e.forEach((e,s)=>{const i=r.get(e);void 0!==i&&_n(i.mutation,s,pe.empty(),M.now()),Vt(t,s)&&(n=n.insert(e,s))}),n})}}class Ks{constructor(e){this.serializer=e,this.hr=new Map,this.Pr=new Map}getBundleMetadata(e,t){return Y.resolve(this.hr.get(t))}saveBundleMetadata(e,t){return this.hr.set(t.id,function(e){return{id:e.id,version:e.version,createTime:us(e.createTime)}}(t)),Y.resolve()}getNamedQuery(e,t){return Y.resolve(this.Pr.get(t))}saveNamedQuery(e,t){return this.Pr.set(t.name,function(e){return{name:e.name,query:Vs(e.bundledQuery),readTime:us(e.readTime)}}(t)),Y.resolve()}}class zs{constructor(){this.overlays=new le(B.comparator),this.Ir=new Map}getOverlay(e,t){return Y.resolve(this.overlays.get(t))}getOverlays(e,t){const n=zt();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,s)=>{this.ht(e,t,s)}),Y.resolve()}removeOverlaysForBatchId(e,t,n){const s=this.Ir.get(n);
2return void 0!==s&&(s.forEach(e=>this.overlays=this.overlays.remove(e)),this.Ir.delete(n)),Y.resolve()}getOverlaysForCollection(e,t,n){const s=zt(),r=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===r&&e.largestBatchId>n&&s.set(e.getKey(),e)}return Y.resolve(s)}getOverlaysForCollectionGroup(e,t,n,s){let r=new le((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=r.get(e.largestBatchId);null===t&&(t=zt(),r=r.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=zt(),a=r.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach((e,t)=>o.set(e,t)),!(o.size()>=s)););return Y.resolve(o)}ht(e,t,n){const s=this.overlays.get(n.key);if(null!==s){const e=this.Ir.get(s.largestBatchId).delete(n.key);this.Ir.set(s.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new xn(t,n));let r=this.Ir.get(t);void 0===r&&(r=Ht(),this.Ir.set(t,r)),this.Ir.set(t,r.add(n.key))}}class Qs{constructor(){this.sessionToken=ye.EMPTY_BYTE_STRING}getSessionToken(e){return Y.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,Y.resolve()}}class Gs{constructor(){this.Tr=new fe(js.Er),this.dr=new fe(js.Ar)}isEmpty(){return this.Tr.isEmpty()}addReference(e,t){const n=new js(e,t);this.Tr=this.Tr.add(n),this.dr=this.dr.add(n)}Rr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Vr(new js(e,t))}mr(e,t){e.forEach(e=>this.removeReference(e,t))}gr(e){const t=new B(new P([])),n=new js(t,e),s=new js(t,e+1),r=[];return this.dr.forEachInRange([n,s],e=>{this.Vr(e),r.push(e.key)}),r}pr(){this.Tr.forEach(e=>this.Vr(e))}Vr(e){this.Tr=this.Tr.delete(e),this.dr=this.dr.delete(e)}yr(e){const t=new B(new P([])),n=new js(t,e),s=new js(t,e+1);let r=Ht();return this.dr.forEachInRange([n,s],e=>{r=r.add(e.key)}),r}containsKey(e){const t=new js(e,0),n=this.Tr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class js{constructor(e,t){this.key=e,this.wr=t}static Er(e,t){return B.comparator(e.key,t.key)||L(e.wr,t.wr)}static Ar(e,t){return L(e.wr,t.wr)||B.comparator(e.key,t.key)}}class Ws{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Sr=1,this.br=new fe(js.Er)}checkEmpty(e){return Y.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,s){const r=this.Sr;this.Sr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const i=new kn(r,t,n,s);this.mutationQueue.push(i);for(const o of s)this.br=this.br.add(new js(o.key,r)),this.indexManager.addToCollectionParentIndex(e,o.key.path.popLast());return Y.resolve(i)}lookupMutationBatch(e,t){return Y.resolve(this.Dr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,s=this.vr(n),r=s<0?0:s;return Y.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return Y.resolve(0===this.mutationQueue.length?-1:this.Sr-1)}getAllMutationBatches(e){return Y.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new js(t,0),s=new js(t,Number.POSITIVE_INFINITY),r=[];return this.br.forEachInRange([n,s],e=>{const t=this.Dr(e.wr);r.push(t)}),Y.resolve(r)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new fe(L);return t.forEach(e=>{const t=new js(e,0),s=new js(e,Number.POSITIVE_INFINITY);this.br.forEachInRange([t,s],e=>{n=n.add(e.wr)})}),Y.resolve(this.Cr(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,s=n.length+1;let r=n;B.isDocumentKey(r)||(r=r.child(""));const i=new js(new B(r),0);let o=new fe(L);return this.br.forEachWhile(e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===s&&(o=o.add(e.wr)),!0)},i),Y.resolve(this.Cr(o))}Cr(e){const t=[];return e.forEach(e=>{const n=this.Dr(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){w(0===this.Fr(t.batchId,"removed")),this.mutationQueue.shift();let n=this.br;return Y.forEach(t.mutations,s=>{const r=new js(s.key,t.batchId);return n=n.delete(r),this.referenceDelegate.markPotentiallyOrphaned(e,s.key)}).next(()=>{this.br=n})}On(e){}containsKey(e,t){const n=new js(t,0),s=this.br.firstAfterOrEqual(n);return Y.resolve(t.isEqual(s&&s.key))}
2performConsistencyCheck(e){return this.mutationQueue.length,Y.resolve()}Fr(e,t){return this.vr(e)}vr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Dr(e){const t=this.vr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Hs{constructor(e){this.Mr=e,this.docs=new le(B.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,s=this.docs.get(n),r=s?s.size:0,i=this.Mr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-r,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():je.newInvalidDocument(t))}getEntries(e,t){let n=qt();return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():je.newInvalidDocument(e))}),Y.resolve(n)}getDocumentsMatchingQuery(e,t,n,s){let r=qt();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>
2i.length+1||G(z(o),n)<=0||(s.has(o.key)||Vt(t,o))&&(r=r.insert(o.key,o.mutableCopy()))}return Y.resolve(r)}getAllFromCollectionGroup(e,t,n,s){v()}Or(e,t){return Y.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Ys(this)}getSize(e){return Y.resolve(this.size)}}class Ys extends qs{constructor(e){super(),this.cr=e}applyChanges(e){const t=[];return this.changes.forEach((n,s)=>{s.isValidDocument()?t.push(this.cr.addEntry(e,s)):this.cr.removeEntry(n)}),Y.waitFor(t)}getFromCache(e,t){return this.cr.getEntry(e,t)}getAllFromCache(e,t){return this.cr.getEntries(e,t)}}class Xs{constructor(e){this.persistence=e,this.Nr=new Pt(e=>vt(e),wt),this.lastRemoteSnapshotVersion=O.min(),this.highestTargetId=0,this.Lr=0,this.Br=new Gs,this.targetCount=0,this.kr=Us.Bn()}forEachTarget(e,t){return this.Nr.forEach((e,n)=>t(n)),Y.resolve()}getLastRemoteSnapshotVersion(e){return Y.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return Y.resolve(this.Lr)}allocateTargetId(e){return this.highestTargetId=this.kr.next(),Y.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Lr&&(this.Lr=t),Y.resolve()}Kn(e){this.Nr.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.kr=new Us(t),this.highestTargetId=t),e.sequenceNumber>this.Lr&&(this.Lr=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.Nr.delete(t.target),this.Br.gr(t.targetId),this.targetCount-=1,Y.resolve()}removeTargets(e,t,n){let s=0;const r=[];return this.Nr.forEach((i,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Nr.delete(i),r.push(this.removeMatchingKeysForTargetId(e,o.targetId)),s++)}),Y.waitFor(r).next(()=>s)}getTargetCount(e){return Y.resolve(this.targetCount)}getTargetData(e,t){const n=this.Nr.get(t)||null;return Y.resolve(n)}addMatchingKeys(e,t,n){return this.Br.Rr(t,n),Y.resolve()}removeMatchingKeys(e,t,n){this.Br.mr(t,n);const s=this.persistence.referenceDelegate,r=[];return s&&t.forEach(t=>{r.push(s.markPotentiallyOrphaned(e,t))}),Y.waitFor(r)}removeMatchingKeysForTargetId(e,t){return this.Br.gr(t),Y.resolve()}getMatchingKeysForTargetId(e,t){const n=this.Br.yr(t);return Y.resolve(n)}containsKey(e,t){return Y.resolve(this.Br.containsKey(t))}}class Js{constructor(e,t){this.qr={},this.overlays={},this.Qr=new Z(0),this.Kr=!1,this.Kr=!0,this.$r=new Qs,this.referenceDelegate=e(this),this.Ur=new Xs(this),this.indexManager=new Os,this.remoteDocumentCache=function(e){return new Hs(e)}(e=>this.referenceDelegate.Wr(e)),this.serializer=new Ls(t),this.Gr=new Ks(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 zs,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.qr[e.toKey()];return n||(n=new Ws(t,this.referenceDelegate),this.qr[e.toKey()]=n),n}getGlobalsCache(){return this.$r}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Gr}runTransaction(e,t,n){m("MemoryPersistence","Starting transaction:",e);const s=new Zs(this.Qr.next());return this.referenceDelegate.zr(),n(s).next(e=>this.referenceDelegate.jr(s).next(()=>e)).toPromise().then(e=>(s.raiseOnCommittedEvent(),e))}Hr(e,t){return Y.or(Object.values(this.qr).map(n=>()=>n.containsKey(e,t)))}}class Zs extends W{constructor(e){super(),this.currentSequenceNumber=e}}class er{constructor(e){this.persistence=e,this.Jr=new Gs,this.Yr=null}static Zr(e){return new er(e)}get Xr(){if(this.Yr)return this.Yr;throw v()}addReference(e,t,n){return this.Jr.addReference(n,t),this.Xr.delete(n.toString()),Y.resolve()}removeReference(e,t,n){return this.Jr.removeReference(n,t),this.Xr.add(n.toString()),Y.resolve()}markPotentiallyOrphaned(e,t){return this.Xr.add(t.toString()),Y.resolve()}
2removeTarget(e,t){this.Jr.gr(t.targetId).forEach(e=>this.Xr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Xr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}zr(){this.Yr=new Set}jr(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Y.forEach(this.Xr,n=>{const s=B.fromPath(n);return this.ei(e,s).next(e=>{e||t.removeEntry(s,O.min())})}).next(()=>(this.Yr=null,t.apply(e)))}updateLimboDocument(e,t){return this.ei(e,t).next(e=>{e?this.Xr.delete(t.toString()):this.Xr.add(t.toString())})}Wr(e){return 0}ei(e,t){return Y.or([()=>Y.resolve(this.Jr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Hr(e,t)])}}class tr{constructor(e,t,n,s){this.targetId=e,this.fromCache=t,this.$i=n,this.Ui=s}static Wi(e,t){let n=Ht(),s=Ht();for(const r of t.docChanges)switch(r.type){case 0:n=n.add(r.doc.key);break;case 1:s=s.add(r.doc.key)}return new tr(e,t.fromCache,n,s)}}class nr{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class sr{constructor(){this.Gi=!1,this.zi=!1,this.ji=100,this.Hi=(0,o.nr)()?8:X((0,o.ZQ)())>0?6:4}initialize(e,t){this.Ji=e,this.indexManager=t,this.Gi=!0}getDocumentsMatchingQuery(e,t,n,s){const r={result:null};return this.Yi(e,t).next(e=>{r.result=e}).next(()=>{if(!r.result)return this.Zi(e,t,s,n).next(e=>{r.result=e})}).next(()=>{if(r.result)return;const n=new nr;return this.Xi(e,t,n).next(s=>{if(r.result=s,this.zi)return this.es(e,t,n,s.size)})}).next(()=>r.result)}es(e,t,n,s){return n.documentReadCount<this.ji?(f()<=i.$b.DEBUG&&m("QueryEngine","SDK will not create cache indexes for query:",Lt(t),"since it only creates cache indexes for collection contains","more than or equal to",this.ji,"documents"),Y.resolve()):(f()<=i.$b.DEBUG&&m("QueryEngine","Query:",Lt(t),"scans",n.documentReadCount,"local documents and returns",s,"documents as results."),n.documentReadCount>this.Hi*s?(f()<=i.$b.DEBUG&&m("QueryEngine","The SDK decides to create cache indexes for query:",Lt(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,Nt(t))):Y.resolve())}Yi(e,t){if(Ct(t))return Y.resolve(null);let n=Nt(t);return this.indexManager.getIndexType(e,n).next(s=>0===s?null:(null!==t.limit&&1===s&&(t=kt(t,null,"F"),n=Nt(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next(s=>{const r=Ht(...s);return this.Ji.getDocuments(e,r).next(s=>this.indexManager.getMinOffset(e,n).next(n=>{const i=this.ts(t,s);return this.ns(t,i,r,n.readTime)?this.Yi(e,kt(t,null,"F")):this.rs(e,i,t,n)}))})))}Zi(e,t,n,s){return Ct(t)||s.isEqual(O.min())?Y.resolve(null):this.Ji.getDocuments(e,n).next(r=>{const o=this.ts(t,r);return this.ns(t,o,n,s)?Y.resolve(null):(f()<=i.$b.DEBUG&&m("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Lt(t)),this.rs(e,o,t,K(s,-1)).next(e=>e))})}ts(e,t){let n=new fe(Ot(e));return t.forEach((t,s)=>{Vt(e,s)&&(n=n.add(s))}),n}ns(e,t,n,s){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const r="F"===e.limitType?t.last():t.first();return!!r&&(r.hasPendingWrites||r.version.compareTo(s)>0)}Xi(e,t,n){return f()<=i.$b.DEBUG&&m("QueryEngine","Using full collection scan to execute query:",Lt(t)),this.Ji.getDocumentsMatchingQuery(e,t,Q.min(),n)}rs(e,t,n,s){return this.Ji.getDocumentsMatchingQuery(e,n,s).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}class rr{constructor(e,t,n,s){this.persistence=e,this.ss=t,this.serializer=s,this.os=new le(L),this._s=new Pt(e=>vt(e),wt),this.us=new Map,this.cs=e.getRemoteDocumentCache(),this.Ur=e.getTargetCache(),this.Gr=e.getBundleCache(),this.ls(n)}ls(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new $s(this.cs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.cs.setIndexManager(this.indexManager),this.ss.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.os))}}function ir(e,t,n,s){return new rr(e,t,n,s)}async function or(e,t){const n=_(e);return await n.persistence.runTransaction("Handle user change","readonly",e=>{let s;
2return n.mutationQueue.getAllMutationBatches(e).next(r=>(s=r,n.ls(t),n.mutationQueue.getAllMutationBatches(e))).next(t=>{const r=[],i=[];let o=Ht();for(const e of s){r.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=>({hs:e,removedBatchIds:r,addedBatchIds:i}))})})}function ar(e){const t=_(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Ur.getLastRemoteSnapshotVersion(e))}function ur(e,t,n){let s=Ht(),r=Ht();return n.forEach(e=>s=s.add(e)),t.getEntries(e,s).next(e=>{let s=qt();return n.forEach((n,i)=>{const o=e.get(n);i.isFoundDocument()!==o.isFoundDocument()&&(r=r.add(n)),i.isNoDocument()&&i.version.isEqual(O.min())?(t.removeEntry(n,i.readTime),s=s.insert(n,i)):!o.isValidDocument()||i.version.compareTo(o.version)>0||0===i.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(i),s=s.insert(n,i)):m("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",i.version)}),{Ps:s,Is:r}})}function cr(e,t){const n=_(e);return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}function lr(e,t){const n=_(e);return n.persistence.runTransaction("Allocate target","readwrite",e=>{let s;return n.Ur.getTargetData(e,t).next(r=>r?(s=r,Y.resolve(s)):n.Ur.allocateTargetId(e).next(r=>(s=new xs(t,r,"TargetPurposeListen",e.currentSequenceNumber),n.Ur.addTargetData(e,s).next(()=>s))))}).then(e=>{const s=n.os.get(e.targetId);return(null===s||e.snapshotVersion.compareTo(s.snapshotVersion)>0)&&(n.os=n.os.insert(e.targetId,e),n._s.set(t,e.targetId)),e})}async function hr(e,t,n){const s=_(e),r=s.os.get(t),i=n?"readwrite":"readwrite-primary";try{n||await s.persistence.runTransaction("Release target",i,e=>s.persistence.referenceDelegate.removeTarget(e,r))}catch(e){if(!J(e))throw e;m("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}s.os=s.os.remove(t),s._s.delete(r.target)}function dr(e,t,n){const s=_(e);let r=O.min(),i=Ht();return s.persistence.runTransaction("Execute query","readwrite",e=>function(e,t,n){const s=_(e),r=s._s.get(n);return void 0!==r?Y.resolve(s.os.get(r)):s.Ur.getTargetData(t,n)}(s,e,Nt(t)).next(t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,s.Ur.getMatchingKeysForTargetId(e,t.targetId).next(e=>{i=e})}).next(()=>s.ss.getDocumentsMatchingQuery(e,t,n?r:O.min(),n?i:Ht())).next(e=>(fr(s,Mt(t),e),{documents:e,Ts:i})))}function fr(e,t,n){let s=e.us.get(t)||O.min();n.forEach((e,t)=>{t.readTime.compareTo(s)>0&&(s=t.readTime)}),e.us.set(t,s)}class mr{constructor(){this.activeTargetIds=Xt()}fs(e){this.activeTargetIds=this.activeTargetIds.add(e)}gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Vs(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class pr{constructor(){this.so=new mr,this.oo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.so.fs(e),this.oo[e]||"not-current"}updateQueryState(e,t,n){this.oo[e]=t}removeLocalQueryTarget(e){this.so.gs(e)}isLocalQueryTarget(e){return this.so.activeTargetIds.has(e)}clearQueryState(e){delete this.oo[e]}getAllActiveQueryTargets(){return this.so.activeTargetIds}isActiveQueryTarget(e){return this.so.activeTargetIds.has(e)}start(){return this.so=new mr,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class gr{_o(e){}shutdown(){}}class yr{constructor(){this.ao=()=>this.uo(),this.co=()=>this.lo(),this.ho=[],this.Po()}_o(e){this.ho.push(e)}shutdown(){window.removeEventListener("online",this.ao),window.removeEventListener("offline",this.co)}Po(){window.addEventListener("online",this.ao),window.addEventListener("offline",this.co)}uo(){m("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.ho)e(0)}lo(){m("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.ho)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let vr=null;function wr(){return null===vr?vr=268435456+Math.round(2147483648*Math.random()):vr++,"0x"+vr.toString(16)}const _r={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
2Query:"runAggregationQuery"};class Er{constructor(e){this.Io=e.Io,this.To=e.To}Eo(e){this.Ao=e}Ro(e){this.Vo=e}mo(e){this.fo=e}onMessage(e){this.po=e}close(){this.To()}send(e){this.Io(e)}yo(){this.Ao()}wo(){this.Vo()}So(e){this.fo(e)}bo(e){this.po(e)}}const Tr="WebChannelConnection";class Ir extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),s=encodeURIComponent(this.databaseId.database);this.Do=t+"://"+e.host,this.vo=`projects/${n}/databases/${s}`,this.Co="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${s}`}get Fo(){return!1}Mo(e,t,n,s,r){const i=wr(),o=this.xo(e,t.toUriEncodedString());m("RestConnection",`Sending RPC '${e}' ${i}:`,o,n);const a={"google-cloud-resource-prefix":this.vo,"x-goog-request-params":this.Co};return this.Oo(a,s,r),this.No(e,o,a,n).then(t=>(m("RestConnection",`Received RPC '${e}' ${i}: `,t),t),t=>{throw g("RestConnection",`RPC '${e}' ${i} failed with error: `,t,"url: ",o,"request:",n),t})}Lo(e,t,n,s,r,i){return this.Mo(e,t,n,s,r)}Oo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+h,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((t,n)=>e[n]=t),n&&n.headers.forEach((t,n)=>e[n]=t)}xo(e,t){const n=_r[e];return`${this.Do}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}No(e,t,n,s){const r=wr();return new Promise((i,o)=>{const a=new u.ZS;a.setWithCredentials(!0),a.listenOnce(u.Bx.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case u.O4.NO_ERROR:const t=a.getResponseJson();m(Tr,`XHR for RPC '${e}' ${r} received:`,JSON.stringify(t)),i(t);break;case u.O4.TIMEOUT:m(Tr,`RPC '${e}' ${r} timed out`),o(new T(E.DEADLINE_EXCEEDED,"Request time out"));break;case u.O4.HTTP_ERROR:const n=a.getStatus();if(m(Tr,`RPC '${e}' ${r} failed with status:`,n,"response text:",a.getResponseText()),n>0){let e=a.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(E).indexOf(t)>=0?t:E.UNKNOWN}(t.status);o(new T(e,t.message))}else o(new T(E.UNKNOWN,"Server responded with status "+a.getStatus()))}else o(new T(E.UNAVAILABLE,"Connection failed."));break;default:v()}}finally{m(Tr,`RPC '${e}' ${r} completed.`)}});const c=JSON.stringify(s);m(Tr,`RPC '${e}' ${r} sending request:`,s),a.send(t,"POST",c,n,15)})}
2Bo(e,t,n){const s=wr(),r=[this.Do,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=(0,u.fF)(),o=(0,u.Ao)(),a={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&&(a.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(a.useFetchStreams=!0),this.Oo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;const l=r.join("");m(Tr,`Creating RPC '${e}' stream ${s}: ${l}`,a);const h=i.createWebChannel(l,a);let d=!1,f=!1;const p=new Er({Io:t=>{f?m(Tr,`Not sending because RPC '${e}' stream ${s} is closed:`,t):(d||(m(Tr,`Opening RPC '${e}' stream ${s} transport.`),h.open(),d=!0),m(Tr,`RPC '${e}' stream ${s} sending:`,t),h.send(t))},To:()=>h.close()}),y=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return y(h,u.iO.EventType.OPEN,()=>{f||(m(Tr,`RPC '${e}' stream ${s} transport opened.`),p.yo())}),y(h,u.iO.EventType.CLOSE,()=>{f||(f=!0,m(Tr,`RPC '${e}' stream ${s} transport closed`),p.So())}),y(h,u.iO.EventType.ERROR,t=>{f||(f=!0,g(Tr,`RPC '${e}' stream ${s} transport errored:`,t),p.So(new T(E.UNAVAILABLE,"The operation could not be completed")))}),y(h,u.iO.EventType.MESSAGE,t=>{var n;if(!f){const r=t.data[0];w(!!r);const i=r,o=i.error||(null===(n=i[0])||void 0===n?void 0:n.error);if(o){m(Tr,`RPC '${e}' stream ${s} received error:`,o);const t=o.status;let n=function(e){const t=Vn[e];if(void 0!==t)return Fn(t)}(t),r=o.message;void 0===n&&(n=E.INTERNAL,r="Unknown error status: "+t+" with message "+o.message),f=!0,p.So(new T(n,r)),h.close()}else m(Tr,`RPC '${e}' stream ${s} received:`,r),p.bo(r)}}),y(o,u.Jh.STAT_EVENT,t=>{t.stat===u.ro.PROXY?m(Tr,`RPC '${e}' stream ${s} detected buffering proxy`):t.stat===u.ro.NOPROXY&&m(Tr,`RPC '${e}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{p.wo()},0),p}}function Cr(){return"undefined"!=typeof document?document:null}function Sr(e){return new ss(e,!0)}class Ar{constructor(e,t,n=1e3,s=1.5,r=6e4){this.ui=e,this.timerId=t,this.ko=n,this.qo=s,this.Qo=r,this.Ko=0,this.$o=null,this.Uo=Date.now(),this.reset()}reset(){this.Ko=0}Wo(){this.Ko=this.Qo}Go(e){this.cancel();const t=Math.floor(this.Ko+this.zo()),n=Math.max(0,Date.now()-this.Uo),s=Math.max(0,t-n);s>0&&m("ExponentialBackoff",`Backing off for ${s} ms (base delay: ${this.Ko} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.$o=this.ui.enqueueAfterDelay(this.timerId,s,()=>(this.Uo=Date.now(),e())),this.Ko*=this.qo,this.Ko<this.ko&&(this.Ko=this.ko),this.Ko>this.Qo&&(this.Ko=this.Qo)}jo(){null!==this.$o&&(this.$o.skipDelay(),this.$o=null)}
2cancel(){null!==this.$o&&(this.$o.cancel(),this.$o=null)}zo(){return(Math.random()-.5)*this.Ko}}class Nr{constructor(e,t,n,s,r,i,o,a){this.ui=e,this.Ho=n,this.Jo=s,this.connection=r,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Yo=0,this.Zo=null,this.Xo=null,this.stream=null,this.e_=0,this.t_=new Ar(e,t)}n_(){return 1===this.state||5===this.state||this.r_()}r_(){return 2===this.state||3===this.state}start(){this.e_=0,4!==this.state?this.auth():this.i_()}async stop(){this.n_()&&await this.close(0)}s_(){this.state=0,this.t_.reset()}o_(){this.r_()&&null===this.Zo&&(this.Zo=this.ui.enqueueAfterDelay(this.Ho,6e4,()=>this.__()))}a_(e){this.u_(),this.stream.send(e)}async __(){if(this.r_())return this.close(0)}u_(){this.Zo&&(this.Zo.cancel(),this.Zo=null)}c_(){this.Xo&&(this.Xo.cancel(),this.Xo=null)}async close(e,t){this.u_(),this.c_(),this.t_.cancel(),this.Yo++,4!==e?this.t_.reset():t&&t.code===E.RESOURCE_EXHAUSTED?(p(t.toString()),p("Using maximum backoff delay to prevent overloading the backend."),this.t_.Wo()):t&&t.code===E.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.l_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.mo(t)}l_(){}auth(){this.state=1;const e=this.h_(this.Yo),t=this.Yo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.Yo===t&&this.P_(e,n)},t=>{e(()=>{const e=new T(E.UNKNOWN,"Fetching auth token failed: "+t.message);return this.I_(e)})})}P_(e,t){const n=this.h_(this.Yo);this.stream=this.T_(e,t),this.stream.Eo(()=>{n(()=>this.listener.Eo())}),this.stream.Ro(()=>{n(()=>(this.state=2,this.Xo=this.ui.enqueueAfterDelay(this.Jo,1e4,()=>(this.r_()&&(this.state=3),Promise.resolve())),this.listener.Ro()))}),this.stream.mo(e=>{n(()=>this.I_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.e_?this.E_(e):this.onNext(e))})}i_(){this.state=5,this.t_.Go(async()=>{this.state=0,this.start()})}I_(e){return m("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}h_(e){return t=>{this.ui.enqueueAndForget(()=>this.Yo===e?t():(m("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class br extends Nr{constructor(e,t,n,s,r,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,s,i),this.serializer=r}T_(e,t){return this.connection.Bo("Listen",e,t)}E_(e){return this.onNext(e)}onNext(e){this.t_.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const s=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:v()}(t.targetChange.targetChangeType||"NO_CHANGE"),r=t.targetChange.targetIds||[],i=function(e,t){return e.useProto3Json?(w(void 0===t||"string"==typeof t),ye.fromBase64String(t||"")):(w(void 0===t||t instanceof Buffer||t instanceof Uint8Array),ye.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?E.UNKNOWN:Fn(e.code);return new T(t,e.message||"")}(o);n=new Hn(s,r,i,a||null)}else if("documentChange"in t){t.documentChange;const s=t.documentChange;s.document,s.document.name,s.document.updateTime;const r=fs(e,s.document.name),i=us(s.document.updateTime),o=s.document.createTime?us(s.document.createTime):O.min(),a=new Qe({mapValue:{fields:s.document.fields}}),u=je.newFoundDocument(r,i,o,a),c=s.targetIds||[],l=s.removedTargetIds||[];n=new jn(c,l,u.key,u)}else if("documentDelete"in t){t.documentDelete;const s=t.documentDelete;s.document;const r=fs(e,s.document),i=s.readTime?us(s.readTime):O.min(),o=je.newNoDocument(r,i),a=s.removedTargetIds||[];n=new jn([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const s=t.documentRemove;s.document;const r=fs(e,s.document),i=s.removedTargetIds||[];n=new jn([],i,r,null)}else{if(!("filter"in t))return v();{t.filter;const e=t.filter;e.targetId;const{count:s=0,unchangedNames:r}=e,i=new Ln(s,r),o=e.targetId;n=new Wn(o,i)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return O.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?O.min():t.readTime?us(t.readTime):O.min()}(e);return this.listener.d_(t,n)}A_(e){const t={};t.database=gs(this.serializer),t.addTarget=function(e,t){let n;const s=t.target;
2if(n=_t(s)?{documents:_s(e,s)}:{query:Es(e,s)._t},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=os(e,t.resumeToken);const s=rs(e,t.expectedCount);null!==s&&(n.expectedCount=s)}else if(t.snapshotVersion.compareTo(O.min())>0){n.readTime=is(e,t.snapshotVersion.toTimestamp());const s=rs(e,t.expectedCount);null!==s&&(n.expectedCount=s)}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 v()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.a_(t)}R_(e){const t={};t.database=gs(this.serializer),t.removeTarget=e,this.a_(t)}}class Dr extends Nr{constructor(e,t,n,s,r,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,s,i),this.serializer=r}get V_(){return this.e_>0}start(){this.lastStreamToken=void 0,super.start()}l_(){this.V_&&this.m_([])}T_(e,t){return this.connection.Bo("Write",e,t)}E_(e){return w(!!e.streamToken),this.lastStreamToken=e.streamToken,w(!e.writeResults||0===e.writeResults.length),this.listener.f_()}onNext(e){w(!!e.streamToken),this.lastStreamToken=e.streamToken,this.t_.reset();const t=function(e,t){return e&&e.length>0?(w(void 0!==t),e.map(e=>function(e,t){let n=e.updateTime?us(e.updateTime):us(t);return n.isEqual(O.min())&&(n=us(t)),new mn(n,e.transformResults||[])}(e,t))):[]}(e.writeResults,e.commitTime),n=us(e.commitTime);return this.listener.g_(n,t)}p_(){const e={};e.database=gs(this.serializer),this.a_(e)}m_(e){const t={streamToken:this.lastStreamToken,writes:e.map(e=>ws(this.serializer,e))};this.a_(t)}}class kr extends class{}{constructor(e,t,n,s){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=s,this.y_=!1}w_(){if(this.y_)throw new T(E.FAILED_PRECONDITION,"The client has already been terminated.")}Mo(e,t,n,s){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([r,i])=>this.connection.Mo(e,ls(t,n),s,r,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===E.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new T(E.UNKNOWN,e.toString())})}Lo(e,t,n,s,r){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,o])=>this.connection.Lo(e,ls(t,n),s,i,o,r)).catch(e=>{throw"FirebaseError"===e.name?(e.code===E.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new T(E.UNKNOWN,e.toString())})}terminate(){this.y_=!0,this.connection.terminate()}}class Rr{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.S_=0,this.b_=null,this.D_=!0}v_(){0===this.S_&&(this.C_("Unknown"),this.b_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.b_=null,this.F_("Backend didn't respond within 10 seconds."),this.C_("Offline"),Promise.resolve())))}M_(e){"Online"===this.state?this.C_("Unknown"):(this.S_++,this.S_>=1&&(this.x_(),this.F_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.C_("Offline")))}set(e){this.x_(),this.S_=0,"Online"===e&&(this.D_=!1),this.C_(e)}C_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}F_(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.D_?(p(t),this.D_=!1):m("OnlineStateTracker",t)}x_(){null!==this.b_&&(this.b_.cancel(),this.b_=null)}}class xr{constructor(e,t,n,s,r){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.O_=[],this.N_=new Map,this.L_=new Set,this.B_=[],this.k_=r,this.k_._o(e=>{n.enqueueAndForget(async()=>{Br(this)&&(m("RemoteStore","Restarting streams for network reach
2ability change."),await async function(e){const t=_(e);t.L_.add(4),await Vr(t),t.q_.set("Unknown"),t.L_.delete(4),await Lr(t)}(this))})}),this.q_=new Rr(n,s)}}async function Lr(e){if(Br(e))for(const t of e.B_)await t(!0)}async function Vr(e){for(const t of e.B_)await t(!1)}function Mr(e,t){const n=_(e);n.N_.has(t.targetId)||(n.N_.set(t.targetId,t),qr(n)?Ur(n):oi(n).r_()&&Fr(n,t))}function Or(e,t){const n=_(e),s=oi(n);n.N_.delete(t),s.r_()&&Pr(n,t),0===n.N_.size&&(s.r_()?s.o_():Br(n)&&n.q_.set("Unknown"))}function Fr(e,t){if(e.Q_.xe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(O.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}oi(e).A_(t)}function Pr(e,t){e.Q_.xe(t),oi(e).R_(t)}function Ur(e){e.Q_=new Xn({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),ot:t=>e.N_.get(t)||null,tt:()=>e.datastore.serializer.databaseId}),oi(e).start(),e.q_.v_()}function qr(e){return Br(e)&&!oi(e).n_()&&e.N_.size>0}function Br(e){return 0===_(e).L_.size}function $r(e){e.Q_=void 0}async function Kr(e){e.q_.set("Online")}async function zr(e){e.N_.forEach((t,n)=>{Fr(e,t)})}async function Qr(e,t){$r(e),qr(e)?(e.q_.M_(t),Ur(e)):e.q_.set("Unknown")}async function Gr(e,t,n){if(e.q_.set("Online"),t instanceof Hn&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const s of t.targetIds)e.N_.has(s)&&(await e.remoteSyncer.rejectListen(s,n),e.N_.delete(s),e.Q_.removeTarget(s))}(e,t)}catch(n){m("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await jr(e,n)}else if(t instanceof jn?e.Q_.Ke(t):t instanceof Wn?e.Q_.He(t):e.Q_.We(t),!n.isEqual(O.min()))try{const t=await ar(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.Q_.rt(t);
2return n.targetChanges.forEach((n,s)=>{if(n.resumeToken.approximateByteSize()>0){const r=e.N_.get(s);r&&e.N_.set(s,r.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{const s=e.N_.get(t);if(!s)return;e.N_.set(t,s.withResumeToken(ye.EMPTY_BYTE_STRING,s.snapshotVersion)),Pr(e,t);const r=new xs(s.target,t,n,s.sequenceNumber);Fr(e,r)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){m("RemoteStore","Failed to raise snapshot:",t),await jr(e,t)}}async function jr(e,t,n){if(!J(t))throw t;e.L_.add(1),await Vr(e),e.q_.set("Offline"),n||(n=()=>ar(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{m("RemoteStore","Retrying IndexedDB access"),await n(),e.L_.delete(1),await Lr(e)})}function Wr(e,t){return t().catch(n=>jr(e,n,t))}async function Hr(e){const t=_(e),n=ai(t);let s=t.O_.length>0?t.O_[t.O_.length-1].batchId:-1;for(;Yr(t);)try{const e=await cr(t.localStore,s);if(null===e){0===t.O_.length&&n.o_();break}s=e.batchId,Xr(t,e)}catch(e){await jr(t,e)}Jr(t)&&Zr(t)}function Yr(e){return Br(e)&&e.O_.length<10}function Xr(e,t){e.O_.push(t);const n=ai(e);n.r_()&&n.V_&&n.m_(t.mutations)}function Jr(e){return Br(e)&&!ai(e).n_()&&e.O_.length>0}function Zr(e){ai(e).start()}async function ei(e){ai(e).p_()}async function ti(e){const t=ai(e);for(const n of e.O_)t.m_(n.mutations)}async function ni(e,t,n){const s=e.O_.shift(),r=Rn.from(s,t,n);await Wr(e,()=>e.remoteSyncer.applySuccessfulWrite(r)),await Hr(e)}async function si(e,t){t&&ai(e).V_&&await async function(e,t){if(function(e){return On(e)&&e!==E.ABORTED}(t.code)){const n=e.O_.shift();ai(e).s_(),await Wr(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await Hr(e)}}(e,t),Jr(e)&&Zr(e)}async function ri(e,t){const n=_(e);n.asyncQueue.verifyOperationInProgress(),m("RemoteStore","RemoteStore received new credentials");const s=Br(n);n.L_.add(3),await Vr(n),s&&n.q_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.L_.delete(3),await Lr(n)}async function ii(e,t){const n=_(e);t?(n.L_.delete(2),await Lr(n)):t||(n.L_.add(2),await Vr(n),n.q_.set("Unknown"))}function oi(e){return e.K_||(e.K_=function(e,t,n){const s=_(e);return s.w_(),new br(t,s.connection,s.authCredentials,s.appCheckCredentials,s.serializer,n)}(e.datastore,e.asyncQueue,{Eo:Kr.bind(null,e),Ro:zr.bind(null,e),mo:Qr.bind(null,e),d_:Gr.bind(null,e)}),e.B_.push(async t=>{t?(e.K_.s_(),qr(e)?Ur(e):e.q_.set("Unknown")):(await e.K_.stop(),$r(e))})),e.K_}function ai(e){return e.U_||(e.U_=function(e,t,n){const s=_(e);return s.w_(),new Dr(t,s.connection,s.authCredentials,s.appCheckCredentials,s.serializer,n)}(e.datastore,e.asyncQueue,{Eo:()=>Promise.resolve(),Ro:ei.bind(null,e),mo:si.bind(null,e),f_:ti.bind(null,e),g_:ni.bind(null,e)}),e.B_.push(async t=>{t?(e.U_.s_(),await Hr(e)):(await e.U_.stop(),e.O_.length>0&&(m("RemoteStore",`Stopping write stream with ${e.O_.length} pending writes`),e.O_=[]))})),e.U_}class ui{constructor(e,t,n,s,r){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=s,this.removalCallback=r,this.deferred=new I,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,s,r){const i=Date.now()+n,o=new ui(e,t,i,s,r);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 T(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 ci(e,t){if(p("AsyncQueue",`${t}: ${e}`),J(e))return new T(E.UNAVAILABLE,`${t}: ${e}`);throw e}class li{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=$t(),this.sortedSet=new le(this.comparator)}static emptySet(e){return new li(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 li))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,s=n.getNext().key;if(!e.isEqual(s))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 li;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class hi{constructor(){this.W_=new le(B.comparator)}track(e){const t=e.doc.key,n=this.W_.get(t);n?0!==e.type&&3===n.type?this.W_=this.W_.insert(t,e):3===e.type&&1!==n.type?this.W_=this.W_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.W_=this.W_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.W_=this.W_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.W_=this.W_.remove(t):1===e.type&&2===n.type?this.W_=this.W_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.W_=this.W_.insert(t,{type:2,doc:e.doc}):v():this.W_=this.W_.insert(t,e)}G_(){const e=[];return this.W_.inorderTraversal((t,n)=>{e.push(n)}),e}}class di{constructor(e,t,n,s,r,i,o,a,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=s,this.mutatedKeys=r,this.fromCache=i,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,s,r){const i=[];
2return t.forEach(e=>{i.push({type:0,doc:e})}),new di(e,t,li.emptySet(t),i,n,s,!0,!1,r)}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)&&Rt(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 s=0;s<t.length;s++)if(t[s].type!==n[s].type||!t[s].doc.isEqual(n[s].doc))return!1;return!0}}class fi{constructor(){this.z_=void 0,this.j_=[]}H_(){return this.j_.some(e=>e.J_())}}class mi{constructor(){this.queries=pi(),this.onlineState="Unknown",this.Y_=new Set}terminate(){!function(e,t){const n=_(e),s=n.queries;n.queries=pi(),s.forEach((e,n)=>{for(const s of n.j_)s.onError(t)})}(this,new T(E.ABORTED,"Firestore shutting down"))}}function pi(){return new Pt(e=>xt(e),Rt)}async function gi(e,t){const n=_(e);let s=3;const r=t.query;let i=n.queries.get(r);i?!i.H_()&&t.J_()&&(s=2):(i=new fi,s=t.J_()?0:1);try{switch(s){case 0:i.z_=await n.onListen(r,!0);break;case 1:i.z_=await n.onListen(r,!1);break;case 2:await n.onFirstRemoteStoreListen(r)}}catch(e){const n=ci(e,`Initialization of query '${Lt(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.j_.push(t),t.Z_(n.onlineState),i.z_&&t.X_(i.z_)&&_i(n)}async function yi(e,t){const n=_(e),s=t.query;let r=3;const i=n.queries.get(s);if(i){const e=i.j_.indexOf(t);e>=0&&(i.j_.splice(e,1),0===i.j_.length?r=t.J_()?0:1:!i.H_()&&t.J_()&&(r=2))}switch(r){case 0:return n.queries.delete(s),n.onUnlisten(s,!0);case 1:return n.queries.delete(s),n.onUnlisten(s,!1);case 2:return n.onLastRemoteStoreUnlisten(s);default:return}}function vi(e,t){const n=_(e);let s=!1;for(const r of t){const e=r.query,t=n.queries.get(e);if(t){for(const e of t.j_)e.X_(r)&&(s=!0);t.z_=r}}s&&_i(n)}function wi(e,t,n){const s=_(e),r=s.queries.get(t);if(r)for(const i of r.j_)i.onError(n);s.queries.delete(t)}function _i(e){e.Y_.forEach(e=>{e.next()})}var Ei,Ti;(Ti=Ei||(Ei={})).ea="default",Ti.Cache="cache";class Ii{constructor(e,t,n){this.query=e,this.ta=t,this.na=!1,this.ra=null,this.onlineState="Unknown",this.options=n||{}}X_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new di(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.na?this.ia(e)&&(this.ta.next(e),t=!0):this.sa(e,this.onlineState)&&(this.oa(e),t=!0),this.ra=e,t}onError(e){this.ta.error(e)}Z_(e){this.onlineState=e;let t=!1;return this.ra&&!this.na&&this.sa(this.ra,e)&&(this.oa(this.ra),t=!0),t}sa(e,t){if(!e.fromCache)return!0;if(!this.J_())return!0;const n="Offline"!==t;return(!this.options._a||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}ia(e){if(e.docChanges.length>0)return!0;const t=this.ra&&this.ra.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}oa(e){e=di.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.na=!0,this.ta.next(e)}J_(){return this.options.source!==Ei.Cache}}class Ci{constructor(e){this.key=e}}class Si{constructor(e){this.key=e}}class Ai{constructor(e,t){this.query=e,this.Ta=t,this.Ea=null,this.hasCachedResults=!1,this.current=!1,this.da=Ht(),this.mutatedKeys=Ht(),this.Aa=Ot(e),this.Ra=new li(this.Aa)}get Va(){return this.Ta}ma(e,t){const n=t?t.fa:new hi,s=t?t.Ra:this.Ra;let r=t?t.mutatedKeys:this.mutatedKeys,i=s,o=!1;const a="F"===this.query.limitType&&s.size===this.query.limit?s.last():null,u="L"===this.query.limitType&&s.size===this.query.limit?s.first():null;if(e.inorderTraversal((e,t)=>{const c=s.get(e),l=Vt(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.ga(c,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.Aa(l,a)>0||u&&this.Aa(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),r=d?r.add(e):r.delete(e)):(i=i.delete(e),r=r.delete(e)))}),null!==this.query.limit)for(;i.size>this.query.limit;
2){const e="F"===this.query.limitType?i.last():i.first();i=i.delete(e.key),r=r.delete(e.key),n.track({type:1,doc:e})}return{Ra:i,fa:n,ns:o,mutatedKeys:r}}ga(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,s){const r=this.Ra;this.Ra=e.Ra,this.mutatedKeys=e.mutatedKeys;const i=e.fa.G_();i.sort((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return v()}};return n(e)-n(t)}(e.type,t.type)||this.Aa(e.doc,t.doc)),this.pa(n),s=null!=s&&s;const o=t&&!s?this.ya():[],a=0===this.da.size&&this.current&&!s?1:0,u=a!==this.Ea;return this.Ea=a,0!==i.length||u?{snapshot:new di(this.query,e.Ra,r,i,e.mutatedKeys,0===a,u,!1,!!n&&n.resumeToken.approximateByteSize()>0),wa:o}:{wa:o}}Z_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ra:this.Ra,fa:new hi,mutatedKeys:this.mutatedKeys,ns:!1},!1)):{wa:[]}}Sa(e){return!this.Ta.has(e)&&!!this.Ra.has(e)&&!this.Ra.get(e).hasLocalMutations}pa(e){e&&(e.addedDocuments.forEach(e=>this.Ta=this.Ta.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ta=this.Ta.delete(e)),this.current=e.current)}ya(){if(!this.current)return[];const e=this.da;this.da=Ht(),this.Ra.forEach(e=>{this.Sa(e.key)&&(this.da=this.da.add(e.key))});const t=[];return e.forEach(e=>{this.da.has(e)||t.push(new Si(e))}),this.da.forEach(n=>{e.has(n)||t.push(new Ci(n))}),t}ba(e){this.Ta=e.Ts,this.da=Ht();const t=this.ma(e.documents);return this.applyChanges(t,!0)}Da(){return di.fromInitialDocuments(this.query,this.Ra,this.mutatedKeys,0===this.Ea,this.hasCachedResults)}}class Ni{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class bi{constructor(e){this.key=e,this.va=!1}}class Di{constructor(e,t,n,s,r,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=s,this.currentUser=r,this.maxConcurrentLimboResolutions=i,this.Ca={},this.Fa=new Pt(e=>xt(e),Rt),this.Ma=new Map,this.xa=new Set,this.Oa=new le(B.comparator),this.Na=new Map,this.La=new Gs,this.Ba={},this.ka=new Map,this.qa=Us.kn(),this.onlineState="Unknown",this.Qa=void 0}get isPrimaryClient(){return!0===this.Qa}}async function ki(e,t,n=!0){const s=Xi(e);let r;const i=s.Fa.get(t);return i?(s.sharedClientState.addLocalQueryTarget(i.targetId),r=i.view.Da()):r=await xi(s,t,n,!0),r}async function Ri(e,t){const n=Xi(e);await xi(n,t,!0,!1)}async function xi(e,t,n,s){const r=await lr(e.localStore,Nt(t)),i=r.targetId,o=e.sharedCl
2ientState.addLocalQueryTarget(i,n);let a;return s&&(a=await Li(e,t,i,"current"===o,r.resumeToken)),e.isPrimaryClient&&n&&Mr(e.remoteStore,r),a}async function Li(e,t,n,s,r){e.Ka=(t,n,s)=>async function(e,t,n,s){let r=t.view.ma(n);r.ns&&(r=await dr(e.localStore,t.query,!1).then(({documents:e})=>t.view.ma(e,r)));const i=s&&s.targetChanges.get(t.targetId),o=s&&null!=s.targetMismatches.get(t.targetId),a=t.view.applyChanges(r,e.isPrimaryClient,i,o);return Qi(e,t.targetId,a.wa),a.snapshot}(e,t,n,s);const i=await dr(e.localStore,t,!0),o=new Ai(t,i.Ts),a=o.ma(i.documents),u=Gn.createSynthesizedTargetChangeForCurrentChange(n,s&&"Offline"!==e.onlineState,r),c=o.applyChanges(a,e.isPrimaryClient,u);Qi(e,n,c.wa);const l=new Ni(t,n,o);return e.Fa.set(t,l),e.Ma.has(n)?e.Ma.get(n).push(t):e.Ma.set(n,[t]),c.snapshot}async function Vi(e,t,n){const s=_(e),r=s.Fa.get(t),i=s.Ma.get(r.targetId);if(i.length>1)return s.Ma.set(r.targetId,i.filter(e=>!Rt(e,t))),void s.Fa.delete(t);s.isPrimaryClient?(s.sharedClientState.removeLocalQueryTarget(r.targetId),s.sharedClientState.isActiveQueryTarget(r.targetId)||await hr(s.localStore,r.targetId,!1).then(()=>{s.sharedClientState.clearQueryState(r.targetId),n&&Or(s.remoteStore,r.targetId),Ki(s,r.targetId)}).catch(H)):(Ki(s,r.targetId),await hr(s.localStore,r.targetId,!0))}async function Mi(e,t){const n=_(e),s=n.Fa.get(t),r=n.Ma.get(s.targetId);n.isPrimaryClient&&1===r.length&&(n.sharedClientState.removeLocalQueryTarget(s.targetId),Or(n.remoteStore,s.targetId))}async function Oi(e,t){const n=_(e);try{const e=await function(e,t){const n=_(e),s=t.snapshotVersion;let r=n.os;return n.persistence.runTransaction("Apply remote event","readwrite-primary",e=>{const i=n.cs.newChangeBuffer({trackRemovals:!0});r=n.os;const o=[];
2t.targetChanges.forEach((i,a)=>{const u=r.get(a);if(!u)return;o.push(n.Ur.removeMatchingKeys(e,i.removedDocuments,a).next(()=>n.Ur.addMatchingKeys(e,i.addedDocuments,a)));let c=u.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?c=c.withResumeToken(ye.EMPTY_BYTE_STRING,O.min()).withLastLimboFreeSnapshotVersion(O.min()):i.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(i.resumeToken,s)),r=r.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.Ur.updateTargetData(e,c))});let a=qt(),u=Ht();if(t.documentUpdates.forEach(s=>{t.resolvedLimboDocuments.has(s)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,s))}),o.push(ur(e,i,t.documentUpdates).next(e=>{a=e.Ps,u=e.Is})),!s.isEqual(O.min())){const t=n.Ur.getLastRemoteSnapshotVersion(e).next(t=>n.Ur.setTargetsMetadata(e,e.currentSequenceNumber,s));o.push(t)}return Y.waitFor(o).next(()=>i.apply(e)).next(()=>n.localDocuments.getLocalViewOfDocuments(e,a,u)).next(()=>a)}).then(e=>(n.os=r,e))}(n.localStore,t);
2t.targetChanges.forEach((e,t)=>{const s=n.Na.get(t);s&&(w(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?s.va=!0:e.modifiedDocuments.size>0?w(s.va):e.removedDocuments.size>0&&(w(s.va),s.va=!1))}),await Wi(n,e,t)}catch(e){await H(e)}}function Fi(e,t,n){const s=_(e);if(s.isPrimaryClient&&0===n||!s.isPrimaryClient&&1===n){const e=[];s.Fa.forEach((n,s)=>{const r=s.view.Z_(t);r.snapshot&&e.push(r.snapshot)}),function(e,t){const n=_(e);n.onlineState=t;let s=!1;n.queries.forEach((e,n)=>{for(const r of n.j_)r.Z_(t)&&(s=!0)}),s&&_i(n)}(s.eventManager,t),e.length&&s.Ca.d_(e),s.onlineState=t,s.isPrimaryClient&&s.sharedClientState.setOnlineState(t)}}async function Pi(e,t,n){const s=_(e);s.sharedClientState.updateQueryState(t,"rejected",n);const r=s.Na.get(t),i=r&&r.key;if(i){let e=new le(B.comparator);e=e.insert(i,je.newNoDocument(i,O.min()));const n=Ht().add(i),r=new Qn(O.min(),new Map,new le(L),e,n);await Oi(s,r),s.Oa=s.Oa.remove(i),s.Na.delete(t),ji(s)}else await hr(s.localStore,t,!1).then(()=>Ki(s,t,n)).catch(H)}async function Ui(e,t){const n=_(e),s=t.batch.batchId;try{const e=await function(e,t){const n=_(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const s=t.batch.keys(),r=n.cs.newChangeBuffer({trackRemovals:!0});return function(e,t,n,s){const r=n.batch,i=r.keys();let o=Y.resolve();return i.forEach(e=>{o=o.next(()=>s.getEntry(t,e)).next(t=>{const i=n.docVersions.get(e);w(null!==i),t.version.compareTo(i)<0&&(r.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),s.addEntry(t)))})}),o.next(()=>e.mutationQueue.removeMutationBatch(t,r))}(n,e,t,r).next(()=>r.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,s,t.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Ht();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t))).next(()=>n.localDocuments.getDocuments(e,s))})}(n.localStore,t);$i(n,s,null),Bi(n,s),n.sharedClientState.updateMutationState(s,"acknowledged"),await Wi(n,e)}catch(e){await H(e)}}async function qi(e,t,n){const s=_(e);try{const e=await function(e,t){const n=_(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let s;
2return n.mutationQueue.lookupMutationBatch(e,t).next(t=>(w(null!==t),s=t.keys(),n.mutationQueue.removeMutationBatch(e,t))).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,s,t)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,s)).next(()=>n.localDocuments.getDocuments(e,s))})}(s.localStore,t);$i(s,t,n),Bi(s,t),s.sharedClientState.updateMutationState(t,"rejected",n),await Wi(s,e)}catch(n){await H(n)}}function Bi(e,t){(e.ka.get(t)||[]).forEach(e=>{e.resolve()}),e.ka.delete(t)}function $i(e,t,n){const s=_(e);let r=s.Ba[s.currentUser.toKey()];if(r){const e=r.get(t);e&&(n?e.reject(n):e.resolve(),r=r.remove(t)),s.Ba[s.currentUser.toKey()]=r}}function Ki(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const s of e.Ma.get(t))e.Fa.delete(s),n&&e.Ca.$a(s,n);e.Ma.delete(t),e.isPrimaryClient&&e.La.gr(t).forEach(t=>{e.La.containsKey(t)||zi(e,t)})}function zi(e,t){e.xa.delete(t.path.canonicalString());const n=e.Oa.get(t);null!==n&&(Or(e.remoteStore,n),e.Oa=e.Oa.remove(t),e.Na.delete(n),ji(e))}function Qi(e,t,n){for(const s of n)s instanceof Ci?(e.La.addReference(s.key,t),Gi(e,s)):s instanceof Si?(m("SyncEngine","Document no longer in limbo: "+s.key),e.La.removeReference(s.key,t),e.La.containsKey(s.key)||zi(e,s.key)):v()}function Gi(e,t){const n=t.key,s=n.path.canonicalString();e.Oa.get(n)||e.xa.has(s)||(m("SyncEngine","New document in limbo: "+n),e.xa.add(s),ji(e))}function ji(e){for(;e.xa.size>0&&e.Oa.size<e.maxConcurrentLimboResolutions;){const t=e.xa.values().next().value;e.xa.delete(t);const n=new B(P.fromString(t)),s=e.qa.next();e.Na.set(s,new bi(n)),e.Oa=e.Oa.insert(n,s),Mr(e.remoteStore,new xs(Nt(It(n.path)),s,"TargetPurposeLimboResolution",Z.oe))}}async function Wi(e,t,n){const s=_(e),r=[],i=[],o=[];s.Fa.isEmpty()||(s.Fa.forEach((e,a)=>{o.push(s.Ka(a,t,n).then(e=>{var t;if((e||n)&&s.isPrimaryClient){const r=e?!e.fromCache:null===(t=null==n?void 0:n.targetChanges.get(a.targetId))||void 0===t?void 0:t.current;s.sharedClientState.updateQueryState(a.targetId,r?"current":"not-current")}if(e){r.push(e);const t=tr.Wi(a.targetId,e);i.push(t)}}))}),await Promise.all(o),s.Ca.d_(r),await async function(e,t){const n=_(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",e=>Y.forEach(t,t=>Y.forEach(t.$i,s=>n.persistence.referenceDelegate.addReference(e,t.targetId,s)).next(()=>Y.forEach(t.Ui,s=>n.persistence.referenceDelegate.removeReference(e,t.targetId,s)))))}catch(e){if(!J(e))throw e;m("LocalStore","Failed to update sequence numbers: "+e)}for(const s of t){const e=s.targetId;if(!s.fromCache){const t=n.os.get(e),s=t.snapshotVersion,r=t.withLastLimboFreeSnapshotVersion(s);n.os=n.os.insert(e,r)}}}(s.localStore,i))}async function Hi(e,t){const n=_(e);if(!n.currentUser.isEqual(t)){m("SyncEngine","User change. New user:",t.toKey());const e=await or(n.localStore,t);n.currentUser=t,function(e,t){e.ka.forEach(e=>{e.forEach(e=>{e.reject(new T(E.CANCELLED,t))})}),e.ka.clear()}(n,"'waitForPendingWrites' promise is rejected due to a user change."),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Wi(n,e.hs)}}function Yi(e,t){const n=_(e),s=n.Na.get(t);if(s&&s.va)return Ht().add(s.key);{let e=Ht();const s=n.Ma.get(t);if(!s)return e;for(const t of s){const s=n.Fa.get(t);e=e.unionWith(s.view.Va)}return e}}function Xi(e){const t=_(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Oi.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Yi.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Pi.bind(null,t),t.Ca.d_=vi.bind(null,t.eventManager),t.Ca.$a=wi.bind(null,t.eventManager),t}function Ji(e){const t=_(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Ui.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=qi.bind(null,t),t}class Zi{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=Sr(e.databaseInfo.databaseId),this.sharedClientState=this.Wa(e),this.persistence=this.Ga(e),await this.persistence.start(),this.localStore=this.za(e),this.gcScheduler
2=this.ja(e,this.localStore),this.indexBackfillerScheduler=this.Ha(e,this.localStore)}ja(e,t){return null}Ha(e,t){return null}za(e){return ir(this.persistence,new sr,e.initialUser,this.serializer)}Ga(e){return new Js(er.Zr,this.serializer)}Wa(e){return new pr}async terminate(){var e,t;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(t=this.indexBackfillerScheduler)||void 0===t||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}Zi.provider={build:()=>new Zi};class eo{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=>Fi(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Hi.bind(null,this.syncEngine),await ii(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new mi}createDatastore(e){const t=Sr(e.databaseInfo.databaseId),n=function(e){return new Ir(e)}(e.databaseInfo);return function(e,t,n,s){return new kr(e,t,n,s)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,s,r){return new xr(e,t,n,s,r)}(this.localStore,this.datastore,e.asyncQueue,e=>Fi(this.syncEngine,e,0),yr.D()?new yr:new gr)}createSyncEngine(e,t){return function(e,t,n,s,r,i,o){const a=new Di(e,t,n,s,r,i);return o&&(a.Qa=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){const t=_(e);m("RemoteStore","RemoteStore shutting down."),t.L_.add(5),await Vr(t),t.k_.shutdown(),t.q_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(t=this.eventManager)||void 0===t||t.terminate()}}eo.provider={build:()=>new eo};class to{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ya(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ya(this.observer.error,e):p("Uncaught Error in snapshot listener:",e.toString()))}Za(){this.muted=!0}Ya(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class no{constructor(e,t,n,s,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=s,this.user=l.UNAUTHENTICATED,this.clientId=x.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=r,this.authCredentials.start(n,async e=>{m("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(m("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();const e=new I;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=ci(t,"Failed to shutdown persistence");e.reject(n)}}),e.promise}}async function so(e,t){e.asyncQueue.verifyOperationInProgress(),m("FirestoreClient","Initializing OfflineComponentProvider");const n=e.configuration;await t.initialize(n);let s=n.initialUser;e.setCredentialChangeListener(async e=>{s.isEqual(e)||(await or(t.localStore,e),s=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function ro(e,t){e.asyncQueue.verifyOperationInProgress();const n=await io(e);m("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener(e=>ri(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>ri(t.remoteStore,n)),e._onlineComponents=t}async function io(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){m("FirestoreClient","Using user provided OfflineComponentProvider");try{await so(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!function(e){return"FirebaseError"===e.name?e.code===E.FAILED_PRECONDITION||e.code===E.UNIMPLEMENT
2ED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}(n))throw n;g("Error using user provided cache. Falling back to memory cache: "+n),await so(e,new Zi)}}else m("FirestoreClient","Using default OfflineComponentProvider"),await so(e,new Zi);return e._offlineComponents}async function oo(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(m("FirestoreClient","Using user provided OnlineComponentProvider"),await ro(e,e._uninitializedComponentsProvider._online)):(m("FirestoreClient","Using default OnlineComponentProvider"),await ro(e,new eo))),e._onlineComponents}function ao(e){return oo(e).then(e=>e.syncEngine)}async function uo(e){const t=await oo(e),n=t.eventManager;return n.onListen=ki.bind(null,t.syncEngine),n.onUnlisten=Vi.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=Ri.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=Mi.bind(null,t.syncEngine),n}function co(e,t,n={}){const s=new I;return e.asyncQueue.enqueueAndForget(async()=>function(e,t,n,s,r){const i=new to({next:n=>{i.Za(),t.enqueueAndForget(()=>yi(e,o)),n.fromCache&&"server"===s.source?r.reject(new T(E.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):r.resolve(n)},error:e=>r.reject(e)}),o=new Ii(n,i,{includeMetadataChanges:!0,_a:!0});return gi(e,o)}(await uo(e),e.asyncQueue,t,n,s)),s.promise}function lo(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const ho=new Map;function fo(e,t,n){if(!n)throw new T(E.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function mo(e){if(!B.isDocumentKey(e))throw new T(E.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function po(e){if(B.isDocumentKey(e))throw new T(E.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function go(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":v()}function yo(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new T(E.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=go(e);throw new T(E.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}class vo{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new T(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 T(E.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,n,s){if(!0===t&&!0===s)throw new T(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=lo(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new T(E.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new T(E.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new T(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 wo{constructor(e,t,n,s){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=s,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new vo({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new T(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"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new T(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 vo(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new S;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 T(E.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
2d credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=ho.get(e);t&&(m("ComponentProvider","Removing Datastore"),ho.delete(e),t.terminate())}(this),Promise.resolve()}}class _o{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new _o(this.firestore,e,this._query)}}class Eo{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 To(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Eo(this.firestore,e,this._key)}}class To extends _o{constructor(e,t,n){super(e,t,It(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 Eo(this.firestore,null,new B(e))}withConverter(e){return new To(this.firestore,e,this._path)}}function Io(e,t,...n){if(e=(0,o.Ku)(e),fo("collection","path",t),e instanceof wo){const s=P.fromString(t,...n);return po(s),new To(e,null,s)}{if(!(e instanceof Eo||e instanceof To))throw new T(E.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=e._path.child(P.fromString(t,...n));return po(s),new To(e.firestore,null,s)}}function Co(e,t,...n){if(e=(0,o.Ku)(e),1===arguments.length&&(t=x.newId()),fo("doc","path",t),e instanceof wo){const s=P.fromString(t,...n);return mo(s),new Eo(e,null,new B(s))}{if(!(e instanceof Eo||e instanceof To))throw new T(E.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const s=e._path.child(P.fromString(t,...n));return mo(s),new Eo(e.firestore,e instanceof To?e.converter:null,new B(s))}}class So{constructor(e=Promise.resolve()){this.Pu=[],this.Iu=!1,this.Tu=[],this.Eu=null,this.du=!1,this.Au=!1,this.Ru=[],this.t_=new Ar(this,"async_queue_retry"),this.Vu=()=>{const e=Cr();e&&m("AsyncQueue","Visibility state changed to "+e.visibilityState),this.t_.jo()},this.mu=e;const t=Cr();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Vu)}get isShuttingDown(){return this.Iu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.fu(),this.gu(e)}enterRestrictedMode(e){if(!this.Iu){this.Iu=!0,this.Au=e||!1;const t=Cr();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Vu)}}enqueue(e){if(this.fu(),this.Iu)return new Promise(()=>{});const t=new I;return this.gu(()=>this.Iu&&this.Au?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Pu.push(e),this.pu()))}async pu(){if(0!==this.Pu.length){try{await this.Pu[0](),this.Pu.shift(),this.t_.reset()}catch(e){if(!J(e))throw e;m("AsyncQueue","Operation failed with retryable error: "+e)}this.Pu.length>0&&this.t_.Go(()=>this.pu())}}gu(e){const t=this.mu.then(()=>(this.du=!0,e().catch(e=>{this.Eu=e,this.du=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw p("INTERNAL UNHANDLED ERROR: ",t),e}).then(e=>(this.du=!1,e))));return this.mu=t,t}enqueueAfterDelay(e,t,n){this.fu(),this.Ru.indexOf(e)>-1&&(t=0);const s=ui.createAndSchedule(this,e,t,n,e=>this.yu(e));return this.Tu.push(s),s}fu(){this.Eu&&v()}verifyOperationInProgress(){}async wu(){let e;do{e=this.mu,await e}while(e!==this.mu)}Su(e){for(const t of this.Tu)if(t.timerId===e)return!0;return!1}bu(e){return this.wu().then(()=>{this.Tu.sort((e,t)=>
2e.targetTimeMs-t.targetTimeMs);for(const t of this.Tu)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.wu()})}Du(e){this.Ru.push(e)}yu(e){const t=this.Tu.indexOf(e);this.Tu.splice(t,1)}}class Ao extends wo{constructor(e,t,n,s){super(e,t,n,s),this.type="firestore",this._queue=new So,this._persistenceKey=(null==s?void 0:s.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new So(e),this._firestoreClient=void 0,await e}}}function No(e){if(e._terminated)throw new T(E.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||bo(e),e._firestoreClient}function bo(e){var t,n,s;const r=e._freezeSettings(),i=function(e,t,n,s){return new Se(e,t,n,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,lo(s.experimentalLongPollingOptions),s.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,r);e._componentsProvider||(null===(n=r.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(s=r.localCache)||void 0===s?void 0:s._onlineComponentProvider)&&(e._componentsProvider={_offline:r.localCache._offlineComponentProvider,_online:r.localCache._onlineComponentProvider}),e._firestoreClient=new no(e._authCredentials,e._appCheckCredentials,e._queue,i,e._componentsProvider&&function(e){const t=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(t),_online:t}}(e._componentsProvider))}class Do{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Do(ye.fromBase64String(e))}catch(e){throw new T(E.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Do(ye.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 ko{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new T(E.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new q(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class Ro{constructor(e){this._methodName=e}}class xo{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new T(E.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new T(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)}}class Lo{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}(this._values,e._values)}}const Vo=/^__.*__$/;class Mo{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Cn(e,this.data,this.fieldMask,t,this.fieldTransforms):new In(e,this.data,t,this.fieldTransforms)}}class Oo{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Cn(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function Fo(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw v()}}class Po{constructor(e,t,n,s,r,i){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=s,void 0===r&&this.vu(),this.fieldTransforms=r||[],this.fieldMask=i||[]}get path(){return this.settings.path}get Cu(){return this.settings.Cu}Fu(e){return new Po(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Mu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),s=this.Fu({path:n,xu:!1});return s.Ou(e),s}Nu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),s=this.Fu({path:n,xu:!1});return s.vu(),s}Lu(e){return this.Fu({path:void 0,xu:!0})}Bu(e){return Zo(e,this.settings.methodName,this.settings.ku||!1,this.path,this.settings.qu)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}vu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Ou(this.path.get(e))}Ou(e){if(0===e.length)throw this.Bu("Document fields must not be empty");if(Fo(this.Cu)&&Vo.test(e))throw this.Bu('Document fields cannot begin and end with "__"')}}class Uo{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer
2=n||Sr(e)}Qu(e,t,n,s=!1){return new Po({Cu:e,methodName:t,qu:n,path:q.emptyPath(),xu:!1,ku:s},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function qo(e){const t=e._freezeSettings(),n=Sr(e._databaseId);return new Uo(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Bo(e,t,n,s,r,i={}){const o=e.Qu(i.merge||i.mergeFields?2:0,t,n,r);Ho("Data must be an object, but it was:",o,s);const a=jo(s,o);let u,c;if(i.merge)u=new pe(o.fieldMask),c=o.fieldTransforms;else if(i.mergeFields){const e=[];for(const s of i.mergeFields){const r=Yo(t,s,n);if(!o.contains(r))throw new T(E.INVALID_ARGUMENT,`Field '${r}' is specified in your field mask but missing from your input data.`);ea(e,r)||e.push(r)}u=new pe(e),c=o.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,c=o.fieldTransforms;return new Mo(new Qe(a),u,c)}class $o extends Ro{_toFieldTransform(e){if(2!==e.Cu)throw 1===e.Cu?e.Bu(`${this._methodName}() can only appear at the top level of your update data`):e.Bu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof $o}}function Ko(e,t,n,s){const r=e.Qu(1,t,n);Ho("Data must be an object, but it was:",r,s);const i=[],a=Qe.empty();ue(s,(e,s)=>{const u=Jo(t,e,n);s=(0,o.Ku)(s);const c=r.Nu(u);if(s instanceof $o)i.push(u);else{const e=Go(s,c);null!=e&&(i.push(u),a.set(u,e))}});const u=new pe(i);return new Oo(a,u,r.fieldTransforms)}function zo(e,t,n,s,r,i){const a=e.Qu(1,t,n),u=[Yo(t,s,n)],c=[r];if(i.length%2!=0)throw new T(E.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let o=0;o<i.length;o+=2)u.push(Yo(t,i[o])),c.push(i[o+1]);const l=[],h=Qe.empty();for(let f=u.length-1;f>=0;--f)if(!ea(l,u[f])){const e=u[f];let t=c[f];t=(0,o.Ku)(t);const n=a.Nu(e);if(t instanceof $o)l.push(e);else{const s=Go(t,n);null!=s&&(l.push(e),h.set(e,s))}}const d=new pe(l);return new Oo(h,d,a.fieldTransforms)}function Qo(e,t,n,s=!1){return Go(n,e.Qu(s?4:3,t))}function Go(e,t){if(Wo(e=(0,o.Ku)(e)))return Ho("Unsupported field value:",t,e),jo(e,t);if(e instanceof Ro)return function(e,t){if(!Fo(t.Cu))throw t.Bu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Bu(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.xu&&4!==t.Cu)throw t.Bu("Nested arrays are not supported");return function(e,t){const n=[];let s=0;for(const r of e){let e=Go(r,t.Lu(s));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),s++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=(0,o.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return en(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=M.fromDate(e);return{timestampValue:is(t.serializer,n)}}if(e instanceof M){const n=new M(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:is(t.serializer,n)}}if(e instanceof xo)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Do)return{bytesValue:os(t.serializer,e._byteString)};if(e instanceof Eo){const n=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(n))throw t.Bu(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:cs(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof Lo)return function(e,t){return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw t.Bu("VectorValues must only contain numeric values.");return Jt(t.serializer,e)})}}}}}}(e,t);throw t.Bu(`Unsupported field value: ${go(e)}`)}(e,t)}function jo(e,t){const n={};return ce(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):ue(e,(e,s)=>{const r=Go(s,t.Mu(e));null!=r&&(n[e]=r)}),{mapValue:{fields:n}}}function Wo(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof M||e instanceof xo||e instanceof Do||e instanceof Eo||e instanceof Ro||e instanceof Lo)}
2function Ho(e,t,n){if(!Wo(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const s=go(n);throw"an object"===s?t.Bu(e+" a custom object"):t.Bu(e+" "+s)}}function Yo(e,t,n){if((t=(0,o.Ku)(t))instanceof ko)return t._internalPath;if("string"==typeof t)return Jo(e,t);throw Zo("Field path arguments must be of type string or ",e,!1,void 0,n)}const Xo=new RegExp("[~\\*/\\[\\]]");function Jo(e,t,n){if(t.search(Xo)>=0)throw Zo(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new ko(...t.split("."))._internalPath}catch(s){throw Zo(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Zo(e,t,n,s,r){const i=s&&!s.isEmpty(),o=void 0!==r;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let u="";return(i||o)&&(u+=" (found",i&&(u+=` in field ${s}`),o&&(u+=` in document ${r}`),u+=")"),new T(E.INVALID_ARGUMENT,a+e+u)}function ea(e,t){return e.some(e=>e.isEqual(t))}class ta{constructor(e,t,n,s,r){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=s,this._converter=r}get id(){return this._key.path.lastSegment()}get ref(){return new Eo(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new na(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(sa("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class na extends ta{data(){return super.data()}}function sa(e,t){return"string"==typeof t?Jo(e,t):t instanceof ko?t._internalPath:t._delegate._internalPath}function ra(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new T(E.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class ia{}class oa extends ia{}function aa(e,t,...n){let s=[];t instanceof ia&&s.push(t),s=s.concat(n),function(e){const t=e.filter(e=>e instanceof la).length,n=e.filter(e=>e instanceof ua).length;if(t>1||t>0&&n>0)throw new T(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(...)))`.")}(s);for(const r of s)e=r._apply(e);return e}class ua extends oa{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new ua(e,t,n)}_apply(e){const t=this._parse(e);return fa(e._query,t),new _o(e.firestore,e.converter,Dt(e._query,t))}_parse(e){const t=qo(e.firestore),n=function(e,t,n,s,r,i,o){let a;if(r.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new T(E.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){da(o,i);const t=[];for(const n of o)t.push(ha(s,e,n));a={arrayValue:{values:t}}}else a=ha(s,e,o)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||da(o,i),a=Qo(n,t,o,"in"===i||"not-in"===i);return et.create(r,i,a)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value);return n}}function ca(e,t,n){const s=t,r=sa("where",e);return ua._create(r,s,n)}class la extends ia{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new la(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]:tt.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const s=t.getFlattenedFilters();for(const r of s)fa(n,r),n=Dt(n,r)}(e._query,t),new _o(e.firestore,e.converter,Dt(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}
2function ha(e,t,n){if("string"==typeof(n=(0,o.Ku)(n))){if(""===n)throw new T(E.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!St(t)&&-1!==n.indexOf("/"))throw new T(E.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);const s=t.path.child(P.fromString(n));if(!B.isDocumentKey(s))throw new T(E.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);return Oe(e,new B(s))}if(n instanceof Eo)return Oe(e,n._key);throw new T(E.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${go(n)}.`)}function da(e,t){if(!Array.isArray(e)||0===e.length)throw new T(E.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function fa(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 T(E.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new T(E.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class ma{convertValue(e,t="none"){switch(be(e)){case 0:return null;case 1:return e.booleanValue;case 2:return _e(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(Ee(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw v()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const n={};return ue(e,(e,s)=>{n[e]=this.convertValue(s,t)}),n}convertVectorValue(e){var t,n,s;const r=null===(s=null===(n=null===(t=e.fields)||void 0===t?void 0:t.value.arrayValue)||void 0===n?void 0:n.values)||void 0===s?void 0:s.map(e=>_e(e.doubleValue));return new Lo(r)}convertGeoPoint(e){return new xo(_e(e.latitude),_e(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":const n=Ie(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ce(e));default:return null}}convertTimestamp(e){const t=we(e);return new M(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=P.fromString(e);w(Rs(n));const s=new Ae(n.get(1),n.get(3)),r=new B(n.popFirst(5));return s.isEqual(t)||p(`Document ${r} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),r}}function pa(e,t,n){let s;return s=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,s}class ga{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class ya extends ta{constructor(e,t,n,s,r,i){super(e,t,n,s,i),this._firestore=e,this._firestoreImpl=e,this.metadata=r}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new va(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(sa("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class va extends ya{data(e={}){return super.data(e)}}class wa{constructor(e,t,n,s){this._firestore=e,this._userDataWriter=t,this._snapshot=s,this.metadata=new ga(s.hasPendingWrites,s.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 va(this._firestore,this._userDataWriter,n.key,n,new ga(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}
2docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new T(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 s=new va(e._firestore,e._userDataWriter,n.doc.key,n.doc,new ga(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:s,oldIndex:-1,newIndex:t++}})}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(e=>t||3!==e.type).map(t=>{const s=new va(e._firestore,e._userDataWriter,t.doc.key,t.doc,new ga(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let r=-1,i=-1;return 0!==t.type&&(r=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:_a(t.type),doc:s,oldIndex:r,newIndex:i}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function _a(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return v()}}class Ea extends ma{constructor(e){super(),this.firestore=e}convertBytes(e){return new Do(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Eo(this.firestore,null,t)}}function Ta(e){e=yo(e,_o);const t=yo(e.firestore,Ao),n=No(t),s=new Ea(t);return ra(e._query),co(n,e._query).then(n=>new wa(t,s,e,n))}function Ia(e,t,n,...s){e=yo(e,Eo);const r=yo(e.firestore,Ao),i=qo(r);let a;return a="string"==typeof(t=(0,o.Ku)(t))||t instanceof ko?zo(i,"updateDoc",e._key,t,n,s):Ko(i,"updateDoc",e._key,t),Aa(r,[a.toMutation(e._key,pn.exists(!0))])}function Ca(e){return Aa(yo(e.firestore,Ao),[new bn(e._key,pn.none())])}function Sa(e,t){const n=yo(e.firestore,Ao),s=Co(e),r=pa(e.converter,t);return Aa(n,[Bo(qo(e.firestore),"addDoc",s._key,r,null!==e.converter,{}).toMutation(s._key,pn.exists(!1))]).then(()=>s)}function Aa(e,t){return function(e,t){const n=new I;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){const s=Ji(e);try{const e=await function(e,t){const n=_(e),s=M.now(),r=t.reduce((e,t)=>e.add(t.key),Ht());let i,o;return n.persistence.runTransaction("Locally write mutations","readwrite",e=>{let a=qt(),u=Ht();return n.cs.getEntries(e,r).next(e=>{a=e,a.forEach((e,t)=>{t.isValidDocument()||(u=u.add(e))})}).next(()=>n.localDocuments.getOverlayedDocuments(e,a)).next(r=>{i=r;const o=[];for(const e of t){const t=En(e,i.get(e.key).overlayedDocument);null!=t&&o.push(new Cn(e.key,t,Ge(t.value.mapValue),pn.exists(!0)))}
2return n.mutationQueue.addMutationBatch(e,s,o,t)}).next(t=>{o=t;const s=t.applyToLocalDocumentSet(i,u);return n.documentOverlayCache.saveOverlays(e,t.batchId,s)})}).then(()=>({batchId:o.batchId,changes:Kt(i)}))}(s.localStore,t);s.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let s=e.Ba[e.currentUser.toKey()];s||(s=new le(L)),s=s.insert(t,n),e.Ba[e.currentUser.toKey()]=s}(s,e.batchId,n),await Wi(s,e.changes),await Hr(s.remoteStore)}catch(e){const t=ci(e,"Failed to persist write");n.reject(t)}}(await ao(e),t,n)),n.promise}(No(e),t)}new WeakMap;!function(e,t=!0){!function(e){h=e}(s.MF),(0,s.om)(new r.uA("firestore",(e,{instanceIdentifier:n,options:s})=>{const r=e.getProvider("app").getImmediate(),i=new Ao(new A(e.getProvider("auth-internal")),new k(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new T(E.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ae(e.options.projectId,t)}(r,n),r);return s=Object.assign({useFetchStreams:t},s),i._setSettings(s),i},"PUBLIC").setMultipleInstances(!0)),(0,s.KO)(c,"4.7.3",e),(0,s.KO)(c,"4.7.3","esm2017")}()}}]); 3//# sourceMappingURL=7112840a-108507f23e595f1b6f71.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.