text: import t from"@firebase/app";import{Logger as e,LogLevel as s}from"@firebase/logger";import{getUA as n,isReactNative as i,isElectron as r,isIE as o,isUWP as h,isBrowserExtension as a}from"@firebase/util";import{Component as u}from"@firebase/component";import{XhrIo as c,EventType as l,ErrorCode as _,createWebChannelTransport as d,WebChannel as f}from"@firebase/webchannel-wrapper";const m=t.SDK_VERSION,T=new e("@firebase/firestore");var E;function w(){return T.logLevel===s.DEBUG?E.DEBUG:T.logLevel===s.SILENT?E.SILENT:E.ERROR}function I(t){switch(t){case E.DEBUG:T.logLevel=s.DEBUG;break;case E.ERROR:T.logLevel=s.ERROR;break;case E.SILENT:T.logLevel=s.SILENT;break;default:T.error(`Firestore (${m}): Invalid value passed to \`setLogLevel\``)}}function R(t,e,...n){if(T.logLevel<=s.DEBUG){const s=n.map(P);T.debug(`Firestore (${m}) [${t}]: ${e}`,...s)}}function A(t,...e){if(T.logLevel<=s.ERROR){const s=e.map(P);T.error(`Firestore (${m}): ${t}`,...s)}}function P(t){if("string"==typeof t)return t;{const e=Ss.t();try{return e.s(t)}catch(e){return t}}}function V(t){const e=`FIRESTORE (${m}) INTERNAL ASSERTION FAILED: `+t;throw A(e),new Error(e)}function p(t,e){t||V(e)}!function(t){t[t.DEBUG=0]="DEBUG",t[t.ERROR=1]="ERROR",t[t.SILENT=2]="SILENT"}(E||(E={}));class g{static i(){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let e="";for(let s=0;s<20;s++)e+=t.charAt(Math.floor(Math.random()*t.length));return p(20===e.length,"Invalid auto ID: "+e),e}}function y(t,e){return t<e?-1:t>e?1:0}function b(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!t[s].isEqual(e[s]))return!1;return!0}function v(t){return t+"\0"}class S{constructor(t,e,s,n,i){this.o=t,this.persistenceKey=e,this.host=s,this.ssl=n,this.forceLongPolling=i}}const D="(default)";class C{constructor(t,e){this.projectId=t,this.database=e||D}get h(){return this.database===D}isEqual(t){return t instanceof C&&t.projectId===this.projectId&&t.database===this.database}u(t){return y(this.projectId,t.projectId)||y(this.database,t.database)}}var k,N,F,$;(N=k||(k={}))[N.l=0]="__PRIVATE_Unknown",N[N._=1]="__PRIVATE_Online",N[N.m=2]="__PRIVATE_Offline",($=F||(F={}))[$.T=0]="__PRIVATE_RemoteStore",$[$.I=1]="__PRIVATE_SharedClientState";class x{constructor(t){this.uid=t}R(){return null!=this.uid}A(){return this.R()?"uid:"+this.uid:"anonymous-user"}isEqual(t){return t.uid===this.uid}}x.UNAUTHENTICATED=new x(null),x.P=new x("google-credentials-uid"),x.V=new x("first-party-uid");const M={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 L extends Error{constructor(t,e){super(e),this.code=t,this.message=e,this.name="FirebaseError",this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class B{constructor(t,e){this.user=e,this.type="OAuth",this.p={},this.p.Authorization=`Bearer ${t}`}}class q{constructor(){this.g=null}getToken(){return Promise.resolve(null)}v(){}S(t){p(!this.g,"Can only call setChangeListener() once."),this.g=t,t(x.UNAUTHENTICATED)}D(){p(null!==this.g,"removeChangeListener() when no listener registered"),this.g=null}}class O{constructor(t){this.C=null,this.currentUser=x.UNAUTHENTICATED,this.k=!1,this.N=0,this.g=null,this.forceRefresh=!1,this.C=()=>{this.N++,this.currentUser=this.F(),this.k=!0,this.g&&this.g(this.currentUser)},this.N=0,this.auth=t.getImmediate({optional:!0}),this.auth?this.auth.addAuthTokenListener(this.C):(this.C(null),t.get().then(t=>{this.auth=t,this.C&&this.auth.addAuthTokenListener(this.C)},()=>{}))}getToken(){p(null!=this.C,"getToken cannot be called after listener removed.");const t=this.N,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>{if(this.N!==t)throw new L(M.ABORTED,"getToken aborted due to token change.");return e?(p("string"==typeof e.accessToken,"Invalid tokenData returned from getToken():"+e),new B(e.accessToken,this.currentUser)):null}):Promise.resolve(null)}v(){this.forceRefresh=!0}S(t){p(!this.g,"Can only call setChangeListener() once."),this.g=t,this.k&&t(this.currentUser)}D(){p(null!=this.C,"removeChangeListener() called twice"),p(null!==this.g,"removeChangeListener() called when no listener registered"),this.auth&&this.auth.removeAuthTokenListener(this.C),this.C=null,this.g=null}F(){const t=this.auth&&this.auth.getUid();return p(null===t||"string"==typeof t,"Received invalid UID: "+t),new x(t)}}class U{constructor(t,e){this.$=t,this.M=e,this.type="FirstParty",this.user=x.V}get p(){const t={"X-Goog-AuthUser":this.M},e=this.$.auth.L([]);return e&&(t.Authorization=e),t}}class Q{constructor(t,e){this.$=t,this.M=e}getToken(){return Promise.resolve(new U(this.$,this.M))}S(t){t(x.V)}D(){}v(){}}function W(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function j(t,e){return void 0!==t?t:e}function z(t,e){for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)){const n=Number(s);isNaN(n)||e(n,t[s])}}function K(t,e){for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&e(s,t[s])}function G(t){p(null!=t&&"object"==typeof t,"isEmpty() expects object parameter.");for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function H(t,e){if(0!==e.length)throw new L(M.INVALID_ARGUMENT,`Function ${t}() does not support arguments, `+"but was called with "+dt(e.length,"argument")+".")}function J(t,e,s){if(e.length!==s)throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires `+dt(s,"argument")+", but was called with "+dt(e.length,"argument")+".")}function Y(t,e,s){if(e.length<s)throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires at least `+dt(s,"argument")+", but was called with "+dt(e.length,"argument")+".")}function X(t,e,s,n){if(e.length<s||e.length>n)throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires between ${s} and `+`${n} arguments, but was called with `+dt(e.length,"argument")+".")}function Z(t,e,s,n){rt(t,e,`${_t(s)} argument`,n)}function tt(t,e,s,n){void 0!==n&&Z(t,e,s,n)}function et(t,e,s,n){rt(t,e,`${s} option`,n)}function st(t,e,s,n){void 0!==n&&et(t,e,s,n)}function nt(t,e,s,n,i){void 0!==n&&function(t,e,s,n,i){if(!(n instanceof Array))throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires its ${e} `+`option to be an array, but it was: ${ht(n)}`);for(let r=0;r<n.length;++r)if(!i(n[r]))throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires all ${e} `+`elements to be ${s}, but the value at index ${r} `+`was: ${ht(n[r])}`)}(t,e,s,n,i)}function it(t,e,s,n,i){void 0!==n&&function(t,e,s,n,i){const r=[];for(const t of i){if(t===n)return;r.push(ht(t))}const o=ht(n);throw new L(M.INVALID_ARGUMENT,`Invalid value ${o} provided to function ${t}() for option `+`"${s}". Acceptable values: ${r.join(", ")}`)}(t,0,s,n,i)}function rt(t,e,s,n){let i=!1;if(!(i="object"===e?ot(n):"non-empty string"===e?"string"==typeof n&&""!==n:typeof n===e)){const i=ht(n);throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires its ${s} `+`to be of type ${e}, but it was: ${i}`)}}function ot(t){return"object"==typeof t&&null!==t&&(Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))}function ht(t){if(void 0===t)return"undefined";if(null===t)return"null";if("string"==typeof t)return t.length>20&&(t=`${t.substring(0,20)}...`),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";{const e=function(t){if(t.constructor){const e=/function\s+([^\s(]+)\s*\(/.exec(t.constructor.toString());if(e&&e.length>1)return e[1]}return null}(t);return e?`a custom ${e} object`:"an object"}}return"function"==typeof t?"a function":V("Unknown wrong type: "+typeof t)}function at(t,e,s){if(void 0===s)throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires a valid ${_t(e)} `+"argument, but it was undefined.")}function ut(t,e,s){K(e,(e,n)=>{if(s.indexOf(e)<0)throw new L(M.INVALID_ARGUMENT,`Unknown option '${e}' passed to function ${t}(). `+"Available options: "+s.join(", "))})}function ct(t,e,s,n){const i=ht(n);return new L(M.INVALID_ARGUMENT,`Function ${t}() requires its ${_t(s)} `+`argument to be a ${e}, but it was: ${i}`)}function lt(t,e,s){if(s<=0)throw new L(M.INVALID_ARGUMENT,`Function "${t}()" requires its ${_t(e)} argument to be a positive number, but it was: ${s}.`)}function _t(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function dt(t,e){return`${t} ${e}`+(1===t?"":"s")}class ft{constructor(t,e){if(J("GeoPoint",arguments,2),Z("GeoPoint","number",1,t),Z("GeoPoint","number",2,e),!isFinite(t)||t<-90||t>90)throw new L(M.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new L(M.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this.B=t,this.q=e}get latitude(){return this.B}get longitude(){return this.q}isEqual(t){return this.B===t.B&&this.q===t.q}O(t){return y(this.B,t.B)||y(this.q,t.q)}}class mt{constructor(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new L(M.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new L(M.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new L(M.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new L(M.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}static now(){return mt.fromMillis(Date.now())}static fromDate(t){return mt.fromMillis(t.getTime())}static fromMillis(t){const e=Math.floor(t/1e3);return new mt(e,1e6*(t-1e3*e))}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}O(t){return this.seconds===t.seconds?y(this.nanoseconds,t.nanoseconds):y(this.seconds,t.seconds)}isEqual(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}}class Tt{constructor(t){this.timestamp=t}static U(t){const e=Math.floor(t/1e6);return new Tt(new mt(e,t%1e6*1e3))}static W(t){return new Tt(t)}static j(){return Tt.MIN}u(t){return this.timestamp.O(t.timestamp)}isEqual(t){return this.timestamp.isEqual(t.timestamp)}K(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}G(){return this.timestamp}}Tt.MIN=new Tt(new mt(0,0));const Et="__name__";class wt{constructor(t,e,s){void 0===e?e=0:e>t.length&&V("offset "+e+" out of range "+t.length),void 0===s?s=t.length-e:s>t.length-e&&V("length "+s+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.H=s}get length(){return this.H}isEqual(t){return 0===wt.J(this,t)}child(t){const e=this.segments.slice(this.offset,this.limit());return t instanceof wt?t.forEach(t=>{e.push(t)}):e.push(t),this.Y(e)}limit(){return this.offset+this.length}X(t){return t=void 0===t?1:t,p(this.length>=t,"Can't call popFirst() with less segments"),this.Y(this.segments,this.offset+t,this.length-t)}Z(){return p(!this.tt(),"Can't call popLast() on empty path"),this.Y(this.segments,this.offset,this.length-1)}et(){return p(!this.tt(),"Can't call firstSegment() on empty path"),this.segments[this.offset]}st(){return this.get(this.length-1)}get(t){return p(t<this.length,"Index out of range"),this.segments[this.offset+t]}tt(){return 0===this.length}nt(t){if(t.length<this.length)return!1;for(let e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0}it(t){if(this.length+1!==t.length)return!1;for(let e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0}forEach(t){for(let e=this.offset,s=this.limit();e<s;e++)t(this.segments[e])}rt(){return this.segments.slice(this.offset,this.limit())}static J(t,e){const s=Math.min(t.length,e.length);for(let n=0;n<s;n++){const s=t.get(n),i=e.get(n);if(s<i)return-1;if(s>i)return 1}return t.length<e.length?-1:t.length>e.length?1:0}}class It extends wt{Y(t,e,s){return new It(t,e,s)}ot(){return this.rt().join("/")}toString(){return this.ot()}static ht(t){if(t.indexOf("//")>=0)throw new L(M.INVALID_ARGUMENT,`Invalid path (${t}). Paths must not contain // in them.`);const e=t.split("/").filter(t=>t.length>0);return new It(e)}}It.at=new It([]);const Rt=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class At extends wt{Y(t,e,s){return new At(t,e,s)}static ut(t){return Rt.test(t)}ot(){return this.rt().map(t=>(t=t.replace("\\","\\\\").replace("`","\\`"),At.ut(t)||(t="`"+t+"`"),t)).join(".")}toString(){return this.ot()}ct(){return 1===this.length&&this.get(0)===Et}static lt(){return new At([Et])}static _t(t){const e=[];let s="",n=0;const i=()=>{if(0===s.length)throw new L(M.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, begin `+"with '.', end with '.', or contain '..'");e.push(s),s=""};let r=!1;for(;n<t.length;){const e=t[n];if("\\"===e){if(n+1===t.length)throw new L(M.INVALID_ARGUMENT,"Path has trailing escape character: "+t);const e=t[n+1];if("\\"!==e&&"."!==e&&"`"!==e)throw new L(M.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);s+=e,n+=2}else"`"===e?(r=!r,n++):"."!==e||r?(s+=e,n++):(i(),n++)}if(i(),r)throw new L(M.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new At(e)}}At.at=new At([]);class Pt{constructor(t){this.path=t,p(Pt.dt(t),"Invalid DocumentKey with an odd number of segments: "+t.rt().join("/"))}ft(t){return this.path.length>=2&&this.path.get(this.path.length-2)===t}isEqual(t){return null!==t&&0===It.J(this.path,t.path)}toString(){return this.path.toString()}static J(t,e){return It.J(t.path,e.path)}static dt(t){return t.length%2==0}static Tt(t){return new Pt(new It(t.slice()))}static Et(t){return new Pt(It.ht(t))}}Pt.EMPTY=new Pt(new It([]));class Vt{constructor(t,e){this.J=t,this.root=e||gt.EMPTY}wt(t,e){return new Vt(this.J,this.root.wt(t,e,this.J).It(null,null,gt.Rt,null,null))}remove(t){return new Vt(this.J,this.root.remove(t,this.J).It(null,null,gt.Rt,null,null))}get(t){let e=this.root;for(;!e.tt();){const s=this.J(t,e.key);if(0===s)return e.value;s<0?e=e.left:s>0&&(e=e.right)}return null}indexOf(t){let e=0,s=this.root;for(;!s.tt();){const n=this.J(t,s.key);if(0===n)return e+s.left.size;n<0?s=s.left:(e+=s.left.size+1,s=s.right)}return-1}tt(){return this.root.tt()}get size(){return this.root.size}At(){return this.root.At()}Pt(){return this.root.Pt()}Vt(t){return this.root.Vt(t)}forEach(t){this.Vt((e,s)=>(t(e,s),!1))}toString(){const t=[];return this.Vt((e,s)=>(t.push(`${e}:${s}`),!1)),`{${t.join(", ")}}`}pt(t){return this.root.pt(t)}gt(){return new pt(this.root,null,this.J,!1)}yt(t){return new pt(this.root,t,this.J,!1)}bt(){return new pt(this.root,null,this.J,!0)}vt(t){return new pt(this.root,t,this.J,!0)}}class pt{constructor(t,e,s,n){this.St=n,this.Dt=[];let i=1;for(;!t.tt();)if(i=e?s(t.key,e):1,n&&(i*=-1),i<0)t=this.St?t.left:t.right;else{if(0===i){this.Dt.push(t);break}this.Dt.push(t),t=this.St?t.right:t.left}}Ct(){p(this.Dt.length>0,"getNext() called on iterator when hasNext() is false.");let t=this.Dt.pop();const e={key:t.key,value:t.value};if(this.St)for(t=t.left;!t.tt();)this.Dt.push(t),t=t.right;else for(t=t.right;!t.tt();)this.Dt.push(t),t=t.left;return e}kt(){return this.Dt.length>0}Nt(){if(0===this.Dt.length)return null;const t=this.Dt[this.Dt.length-1];return{key:t.key,value:t.value}}}class gt{constructor(t,e,s,n,i){this.key=t,this.value=e,this.color=null!=s?s:gt.RED,this.left=null!=n?n:gt.EMPTY,this.right=null!=i?i:gt.EMPTY,this.size=this.left.size+1+this.right.size}It(t,e,s,n,i){return new gt(null!=t?t:this.key,null!=e?e:this.value,null!=s?s:this.color,null!=n?n:this.left,null!=i?i:this.right)}tt(){return!1}Vt(t){return this.left.Vt(t)||t(this.key,this.value)||this.right.Vt(t)}pt(t){return this.right.pt(t)||t(this.key,this.value)||this.left.pt(t)}min(){return this.left.tt()?this:this.left.min()}At(){return this.min().key}Pt(){return this.right.tt()?this.key:this.right.Pt()}wt(t,e,s){let n=this;const i=s(t,n.key);return(n=i<0?n.It(null,null,null,n.left.wt(t,e,s),null):0===i?n.It(null,e,null,null,null):n.It(null,null,null,null,n.right.wt(t,e,s))).Ft()}$t(){if(this.left.tt())return gt.EMPTY;let t=this;return t.left.xt()||t.left.left.xt()||(t=t.Mt()),(t=t.It(null,null,null,t.left.$t(),null)).Ft()}remove(t,e){let s,n=this;if(e(t,n.key)<0)n.left.tt()||n.left.xt()||n.left.left.xt()||(n=n.Mt()),n=n.It(null,null,null,n.left.remove(t,e),null);else{if(n.left.xt()&&(n=n.Lt()),n.right.tt()||n.right.xt()||n.right.left.xt()||(n=n.Bt()),0===e(t,n.key)){if(n.right.tt())return gt.EMPTY;s=n.right.min(),n=n.It(s.key,s.value,null,null,n.right.$t())}n=n.It(null,null,null,null,n.right.remove(t,e))}return n.Ft()}xt(){return this.color}Ft(){let t=this;return t.right.xt()&&!t.left.xt()&&(t=t.qt()),t.left.xt()&&t.left.left.xt()&&(t=t.Lt()),t.left.xt()&&t.right.xt()&&(t=t.Ot()),t}Mt(){let t=this.Ot();return t.right.left.xt()&&(t=(t=(t=t.It(null,null,null,null,t.right.Lt())).qt()).Ot()),t}Bt(){let t=this.Ot();return t.left.left.xt()&&(t=(t=t.Lt()).Ot()),t}qt(){const t=this.It(null,null,gt.RED,null,this.right.left);return this.right.It(null,null,this.color,t,null)}Lt(){const t=this.It(null,null,gt.RED,this.left.right,null);return this.left.It(null,null,this.color,null,t)}Ot(){const t=this.left.It(null,null,!this.left.color,null,null),e=this.right.It(null,null,!this.right.color,null,null);return this.It(null,null,!this.color,t,e)}Ut(){const t=this.Qt();return Math.pow(2,t)<=this.size+1}Qt(){if(this.xt()&&this.left.xt())throw V("Red node has red child("+this.key+","+this.value+")");if(this.right.xt())throw V("Right child of ("+this.key+","+this.value+") is red");const t=this.left.Qt();if(t!==this.right.Qt())throw V("Black depths differ");return t+(this.xt()?0:1)}}gt.EMPTY=null,gt.RED=!0,gt.Rt=!1;gt.EMPTY=new class{constructor(){this.size=0}get key(){throw V("LLRBEmptyNode has no key.")}get value(){throw V("LLRBEmptyNode has no value.")}get color(){throw V("LLRBEmptyNode has no color.")}get left(){throw V("LLRBEmptyNode has no left child.")}get right(){throw V("LLRBEmptyNode has no right child.")}It(t,e,s,n,i){return this}wt(t,e,s){return new gt(t,e)}remove(t,e){return this}tt(){return!0}Vt(t){return!1}pt(t){return!1}At(){return null}Pt(){return null}xt(){return!1}Ut(){return!0}Qt(){return 0}};class yt{constructor(t){this.J=t,this.data=new Vt(this.J)}static Wt(t){let e=new yt(t.J);return t.forEach(t=>{e=e.add(t)}),e}has(t){return null!==this.data.get(t)}first(){return this.data.At()}last(){return this.data.Pt()}get size(){return this.data.size}indexOf(t){return this.data.indexOf(t)}forEach(t){this.data.Vt((e,s)=>(t(e),!1))}jt(t,e){const s=this.data.yt(t[0]);for(;s.kt();){const n=s.Ct();if(this.J(n.key,t[1])>=0)return;e(n.key)}}zt(t,e){let s;for(s=void 0!==e?this.data.yt(e):this.data.gt();s.kt();){if(!t(s.Ct().key))return}}Kt(t){const e=this.data.yt(t);return e.kt()?e.Ct().key:null}gt(){return new bt(this.data.gt())}yt(t){return new bt(this.data.yt(t))}add(t){return this.It(this.data.remove(t).wt(t,!0))}delete(t){return this.has(t)?this.It(this.data.remove(t)):this}tt(){return this.data.tt()}Gt(t){let e=this;return t.forEach(t=>{e=e.add(t)}),e}isEqual(t){if(!(t instanceof yt))return!1;if(this.size!==t.size)return!1;const e=this.data.gt(),s=t.data.gt();for(;e.kt();){const t=e.Ct().key,n=s.Ct().key;if(0!==this.J(t,n))return!1}return!0}rt(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}It(t){const e=new yt(this.J);return e.data=t,e}}class bt{constructor(t){this.Ht=t}Ct(){return this.Ht.Ct().key}kt(){return this.Ht.kt()}}class vt{constructor(){}Jt(t,e){return new re(e,t)}Yt(t,e){return e}Xt(t){return null}isEqual(t){return t instanceof vt}}vt.instance=new vt;class St{constructor(t){this.elements=t}Jt(t,e){return this.apply(t)}Yt(t,e){return this.apply(t)}apply(t){const e=kt(t);for(const t of this.elements)e.find(e=>e.isEqual(t))||e.push(t);return new ce(e)}Xt(t){return null}isEqual(t){return t instanceof St&&b(t.elements,this.elements)}}class Dt{constructor(t){this.elements=t}Jt(t,e){return this.apply(t)}Yt(t,e){return this.apply(t)}apply(t){let e=kt(t);for(const t of this.elements)e=e.filter(e=>!e.isEqual(t));return new ce(e)}Xt(t){return null}isEqual(t){return t instanceof Dt&&b(t.elements,this.elements)}}class Ct{constructor(t){this.Zt=t}Jt(t,e){const s=this.Xt(t);if(s instanceof ee&&this.Zt instanceof ee){const t=s.te+this.Zt.te;return new ee(t)}{const t=s.te+this.Zt.te;return new se(t)}}Yt(t,e){return p(null!==e,"Didn't receive transformResult for NUMERIC_ADD transform"),e}Xt(t){return t instanceof Zt?t:new ee(0)}isEqual(t){return t instanceof Ct&&this.Zt.isEqual(t.Zt)}}function kt(t){return t instanceof ce?t.te.slice():[]}class Nt{constructor(t){this.fields=t}static ee(t){return new Nt(t)}static se(t){let e=new yt(At.J);return t.forEach(t=>e=e.add(t)),new Nt(e)}ne(t){let e=!1;return this.fields.forEach(s=>{s.nt(t)&&(e=!0)}),e}isEqual(t){return this.fields.isEqual(t.fields)}}class Ft{constructor(t,e){this.field=t,this.transform=e}isEqual(t){return this.field.isEqual(t.field)&&this.transform.isEqual(t.transform)}}class $t{constructor(t,e){this.version=t,this.transformResults=e}}var xt,Mt,Lt,Bt,qt,Ot;(Mt=xt||(xt={}))[Mt.Set=0]="Set",Mt[Mt.ie=1]="__PRIVATE_Patch",Mt[Mt.re=2]="__PRIVATE_Transform",Mt[Mt.oe=3]="__PRIVATE_Delete",Mt[Mt.he=4]="__PRIVATE_Verify";class Ut{constructor(t,e){this.updateTime=t,this.exists=e,p(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}static exists(t){return new Ut(void 0,t)}static updateTime(t){return new Ut(t)}get ae(){return void 0===this.updateTime&&void 0===this.exists}ue(t){return void 0!==this.updateTime?t instanceof _e&&t.version.isEqual(this.updateTime):void 0!==this.exists?this.exists===t instanceof _e:(p(this.ae,"Precondition should be empty"),!0)}isEqual(t){return e=this.updateTime,s=t.updateTime,(null!=e?!(!s||!e.isEqual(s)):e===s)&&this.exists===t.exists;var e,s}}Ut.NONE=new Ut;class Qt{ce(t){null!=t&&p(t.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")}static le(t){return t instanceof _e?t.version:Tt.MIN}}class Wt extends Qt{constructor(t,e,s){super(),this.key=t,this.value=e,this._e=s,this.type=xt.Set}Yt(t,e){this.ce(t),p(null==e.transformResults,"Transform results received by SetMutation.");const s=e.version;return new _e(this.key,s,{hasCommittedMutations:!0},this.value)}Jt(t,e,s){if(this.ce(t),!this._e.ue(t))return t;const n=Qt.le(t);return new _e(this.key,n,{de:!0},this.value)}fe(t){return null}isEqual(t){return t instanceof Wt&&this.key.isEqual(t.key)&&this.value.isEqual(t.value)&&this._e.isEqual(t._e)}}class jt extends Qt{constructor(t,e,s,n){super(),this.key=t,this.data=e,this.me=s,this._e=n,this.type=xt.ie}Yt(t,e){if(this.ce(t),p(null==e.transformResults,"Transform results received by PatchMutation."),!this._e.ue(t))return new fe(this.key,e.version);const s=this.Te(t);return new _e(this.key,e.version,{hasCommittedMutations:!0},s)}Jt(t,e,s){if(this.ce(t),!this._e.ue(t))return t;const n=Qt.le(t),i=this.Te(t);return new _e(this.key,n,{de:!0},i)}fe(t){return null}isEqual(t){return t instanceof jt&&this.key.isEqual(t.key)&&this.me.isEqual(t.me)&&this._e.isEqual(t._e)}Te(t){let e;return e=t instanceof _e?t.data():ue.EMPTY,this.Ee(e)}Ee(t){return this.me.fields.forEach(e=>{if(!e.tt()){const s=this.data.field(e);t=null!==s?t.set(e,s):t.delete(e)}}),t}}class zt extends Qt{constructor(t,e){super(),this.key=t,this.fieldTransforms=e,this.type=xt.re,this._e=Ut.exists(!0)}Yt(t,e){if(this.ce(t),p(null!=e.transformResults,"Transform results missing for TransformMutation."),!this._e.ue(t))return new fe(this.key,e.version);const s=this.we(t),n=this.Ie(t,e.transformResults),i=e.version,r=this.Re(s.data(),n);return new _e(this.key,i,{hasCommittedMutations:!0},r)}Jt(t,e,s){if(this.ce(t),!this._e.ue(t))return t;const n=this.we(t),i=this.Ae(s,t,e),r=this.Re(n.data(),i);return new _e(this.key,n.version,{de:!0},r)}fe(t){let e=null;for(const s of this.fieldTransforms){const n=t instanceof _e?t.field(s.field):void 0,i=s.transform.Xt(n||null);null!=i&&(e=null==e?ue.EMPTY.set(s.field,i):e.set(s.field,i))}return e}isEqual(t){return t instanceof zt&&this.key.isEqual(t.key)&&b(this.fieldTransforms,t.fieldTransforms)&&this._e.isEqual(t._e)}we(t){return p(t instanceof _e,"Unknown MaybeDocument type "+t),p(t.key.isEqual(this.key),"Can only transform a document with the same key"),t}Ie(t,e){const s=[];p(this.fieldTransforms.length===e.length,`server transform result count (${e.length}) `+`should match field transform count (${this.fieldTransforms.length})`);for(let n=0;n<e.length;n++){const i=this.fieldTransforms[n],r=i.transform;let o=null;t instanceof _e&&(o=t.field(i.field)),s.push(r.Yt(o,e[n]))}return s}Ae(t,e,s){const n=[];for(const i of this.fieldTransforms){const r=i.transform;let o=null;e instanceof _e&&(o=e.field(i.field)),null===o&&s instanceof _e&&(o=s.field(i.field)),n.push(r.Jt(o,t))}return n}Re(t,e){p(e.length===this.fieldTransforms.length,"TransformResults length mismatch.");for(let s=0;s<this.fieldTransforms.length;s++){const n=this.fieldTransforms[s].field;t=t.set(n,e[s])}return t}}class Kt extends Qt{constructor(t,e){super(),this.key=t,this._e=e,this.type=xt.oe}Yt(t,e){return this.ce(t),p(null==e.transformResults,"Transform results received by DeleteMutation."),new de(this.key,e.version,{hasCommittedMutations:!0})}Jt(t,e,s){return this.ce(t),this._e.ue(t)?(t&&p(t.key.isEqual(this.key),"Can only apply mutation to document with same key"),new de(this.key,Tt.j())):t}fe(t){return null}isEqual(t){return t instanceof Kt&&this.key.isEqual(t.key)&&this._e.isEqual(t._e)}}class Gt extends Qt{constructor(t,e){super(),this.key=t,this._e=e,this.type=xt.he}Yt(t,e){V("VerifyMutation should only be used in Transactions.")}Jt(t,e,s){V("VerifyMutation should only be used in Transactions.")}fe(t){V("VerifyMutation should only be used in Transactions.")}isEqual(t){return t instanceof Gt&&this.key.isEqual(t.key)&&this._e.isEqual(t._e)}}(Bt=Lt||(Lt={}))[Bt.Pe=0]="__PRIVATE_NullValue",Bt[Bt.Ve=1]="__PRIVATE_BooleanValue",Bt[Bt.pe=2]="__PRIVATE_NumberValue",Bt[Bt.ge=3]="__PRIVATE_TimestampValue",Bt[Bt.ye=4]="__PRIVATE_StringValue",Bt[Bt.be=5]="__PRIVATE_BlobValue",Bt[Bt.ve=6]="__PRIVATE_RefValue",Bt[Bt.Se=7]="__PRIVATE_GeoPointValue",Bt[Bt.ArrayValue=8]="ArrayValue",Bt[Bt.De=9]="__PRIVATE_ObjectValue",(Ot=qt||(qt={}))[Ot.Ce=0]="__PRIVATE_Default",Ot[Ot.ke=1]="__PRIVATE_Estimate",Ot[Ot.Ne=2]="__PRIVATE_Previous";class Ht{constructor(t,e){this.Fe=t,this.timestampsInSnapshots=e}static $e(t,e){switch(t.serverTimestamps){case"estimate":return new Ht(qt.ke,e);case"previous":return new Ht(qt.Ne,e);case"none":case void 0:return new Ht(qt.Ce,e);default:return V("fromSnapshotOptions() called with invalid options.")}}}class Jt{toString(){const t=this.value();return null===t?"null":t.toString()}xe(t){return p(this.Me!==t.Me,"Default compareTo should not be used for values of same type."),y(this.Me,t.Me)}}class Yt extends Jt{constructor(){super(),this.Me=Lt.Pe,this.te=null}value(t){return null}isEqual(t){return t instanceof Yt}u(t){return t instanceof Yt?0:this.xe(t)}Le(){return 4}}Yt.Be=new Yt;class Xt extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.Ve}value(t){return this.te}isEqual(t){return t instanceof Xt&&this.te===t.te}u(t){return t instanceof Xt?y(this,t):this.xe(t)}Le(){return 4}static of(t){return t?Xt.qe:Xt.Oe}}Xt.qe=new Xt(!0),Xt.Oe=new Xt(!1);class Zt extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.pe}value(t){return this.te}u(t){return t instanceof Zt?(e=this.te,s=t.te,e<s?-1:e>s?1:e===s?0:isNaN(e)?isNaN(s)?0:-1:1):this.xe(t);var e,s}Le(){return 8}}function te(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}class ee extends Zt{isEqual(t){return t instanceof ee&&te(this.te,t.te)}}class se extends Zt{isEqual(t){return t instanceof se&&te(this.te,t.te)}}se.Ue=new se(NaN),se.POSITIVE_INFINITY=new se(1/0),se.NEGATIVE_INFINITY=new se(-1/0);class ne extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.ye}value(t){return this.te}isEqual(t){return t instanceof ne&&this.te===t.te}u(t){return t instanceof ne?y(this.te,t.te):this.xe(t)}Le(){return 2*this.te.length}}class ie extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.ge}value(t){return!t||t.timestampsInSnapshots?this.te:this.te.toDate()}isEqual(t){return t instanceof ie&&this.te.isEqual(t.te)}u(t){return t instanceof ie?this.te.O(t.te):t instanceof re?-1:this.xe(t)}Le(){return 16}}class re extends Jt{constructor(t,e){super(),this.Qe=t,this.previousValue=e,this.Me=Lt.ge}value(t){return t&&t.Fe===qt.ke?new ie(this.Qe).value(t):t&&t.Fe===qt.Ne&&this.previousValue?this.previousValue.value(t):null}isEqual(t){return t instanceof re&&this.Qe.isEqual(t.Qe)}u(t){return t instanceof re?this.Qe.O(t.Qe):t instanceof ie?1:this.xe(t)}toString(){return"<ServerTimestamp localTime="+this.Qe.toString()+">"}Le(){return 16+(this.previousValue?this.previousValue.Le():0)}}class oe extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.be}value(t){return this.te}isEqual(t){return t instanceof oe&&this.te.isEqual(t.te)}u(t){return t instanceof oe?this.te.O(t.te):this.xe(t)}Le(){return this.te.We()}}class he extends Jt{constructor(t,e){super(),this.o=t,this.key=e,this.Me=Lt.ve}value(t){return this.key}isEqual(t){return t instanceof he&&(this.key.isEqual(t.key)&&this.o.isEqual(t.o))}u(t){if(t instanceof he){const e=this.o.u(t.o);return 0!==e?e:Pt.J(this.key,t.key)}return this.xe(t)}Le(){return this.o.projectId.length+this.o.database.length+this.key.toString().length}}class ae extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.Se}value(t){return this.te}isEqual(t){return t instanceof ae&&this.te.isEqual(t.te)}u(t){return t instanceof ae?this.te.O(t.te):this.xe(t)}Le(){return 16}}class ue extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.De}value(t){const e={};return this.te.Vt((s,n)=>{e[s]=n.value(t)}),e}forEach(t){this.te.Vt(t)}isEqual(t){if(t instanceof ue){const e=this.te.gt(),s=t.te.gt();for(;e.kt()&&s.kt();){const t=e.Ct(),n=s.Ct();if(t.key!==n.key||!t.value.isEqual(n.value))return!1}return!e.kt()&&!s.kt()}return!1}u(t){if(t instanceof ue){const e=this.te.gt(),s=t.te.gt();for(;e.kt()&&s.kt();){const t=e.Ct(),n=s.Ct(),i=y(t.key,n.key)||t.value.u(n.value);if(i)return i}return y(e.kt(),s.kt())}return this.xe(t)}set(t,e){if(p(!t.tt(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.je(t.et(),e);{let s=this.child(t.et());s instanceof ue||(s=ue.EMPTY);const n=s.set(t.X(),e);return this.je(t.et(),n)}}delete(t){if(p(!t.tt(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new ue(this.te.remove(t.et()));{const e=this.child(t.et());if(e instanceof ue){const s=e.delete(t.X());return new ue(this.te.wt(t.et(),s))}return this}}contains(t){return null!==this.field(t)}field(t){p(!t.tt(),"Can't get field of empty path");let e=this;return t.forEach(t=>{e=e instanceof ue?e.te.get(t):null}),e}me(){let t=new yt(At.J);return this.te.forEach((e,s)=>{const n=new At([e]);if(s instanceof ue){const e=s.me().fields;e.tt()?t=t.add(n):e.forEach(e=>{t=t.add(n.child(e))})}else t=t.add(n)}),Nt.ee(t)}Le(){let t=0;return this.te.Vt((e,s)=>{t+=e.length+s.Le()}),t}toString(){return this.te.toString()}child(t){return this.te.get(t)||void 0}je(t,e){return new ue(this.te.wt(t,e))}}ue.EMPTY=new ue(new Vt(y));class ce extends Jt{constructor(t){super(),this.te=t,this.Me=Lt.ArrayValue}value(t){return this.te.map(e=>e.value(t))}contains(t){for(const e of this.te)if(e.isEqual(t))return!0;return!1}forEach(t){this.te.forEach(t)}isEqual(t){if(t instanceof ce){if(this.te.length!==t.te.length)return!1;for(let e=0;e<this.te.length;e++)if(!this.te[e].isEqual(t.te[e]))return!1;return!0}return!1}u(t){if(t instanceof ce){const e=Math.min(this.te.length,t.te.length);for(let s=0;s<e;s++){const e=this.te[s].u(t.te[s]);if(e)return e}return y(this.te.length,t.te.length)}return this.xe(t)}Le(){return this.te.reduce((t,e)=>t+e.Le(),0)}toString(){return`[${this.te.map(t=>t.toString()).join(",")}]`}}class le{constructor(t,e){this.key=t,this.version=e}static ze(t,e){return Pt.J(t.key,e.key)}}class _e extends le{constructor(t,e,s,n,i,r){super(t,e),this.Ke=n,this.proto=i,this.converter=r,p(void 0!==this.Ke||void 0!==this.proto&&void 0!==this.converter,"If objectValue is not defined, proto and converter need to be set."),this.de=!!s.de,this.hasCommittedMutations=!!s.hasCommittedMutations}field(t){if(this.Ke)return this.Ke.field(t);{this.Ge||(this.Ge=new Map);const e=t.ot();let s=this.Ge.get(e);if(void 0===s){const n=this.He(t);s=void 0===n?null:this.converter(n),this.Ge.set(e,s)}return s}}data(){if(!this.Ke){let t=ue.EMPTY;K(this.proto.fields||{},(e,s)=>{t=t.set(new At([e]),this.converter(s))}),this.Ke=t,this.Ge=void 0}return this.Ke}value(){return this.data().value()}isEqual(t){return t instanceof _e&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.de===t.de&&this.hasCommittedMutations===t.hasCommittedMutations&&this.data().isEqual(t.data())}toString(){return`Document(${this.key}, ${this.version}, ${this.data().toString()}, `+`{hasLocalMutations: ${this.de}}), `+`{hasCommittedMutations: ${this.hasCommittedMutations}})`}get hasPendingWrites(){return this.de||this.hasCommittedMutations}He(t){p(void 0!==this.proto,"Can only call getProtoField() when proto is defined");let e=this.proto.fields?this.proto.fields[t.et()]:void 0;for(let s=1;s<t.length;++s){if(!e||!e.mapValue||!e.mapValue.fields)return;e=e.mapValue.fields[t.get(s)]}return e}static Je(t,e,s){const n=e.field(t),i=s.field(t);return null!==n&&null!==i?n.u(i):V("Trying to compare documents on fields that don't exist")}}class de extends le{constructor(t,e,s){super(t,e),this.hasCommittedMutations=!(!s||!s.hasCommittedMutations)}toString(){return`NoDocument(${this.key}, ${this.version})`}get hasPendingWrites(){return this.hasCommittedMutations}isEqual(t){return t instanceof de&&t.hasCommittedMutations===this.hasCommittedMutations&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)}}class fe extends le{toString(){return`UnknownDocument(${this.key}, ${this.version})`}get hasPendingWrites(){return!0}isEqual(t){return t instanceof fe&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)}}const me=Number,Te=me.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),Ee=me.MAX_SAFE_INTEGER||Math.pow(2,53)-1,we=me.isInteger||(t=>"number"==typeof t&&isFinite(t)&&Math.floor(t)===t);function Ie(t){return null==t}function Re(t){return we(t)&&t<=Ee&&t>=Te}class Ae{constructor(t,e=null,s=[],n=[],i=null,r=null,o=null){this.path=t,this.collectionGroup=e,this.orderBy=s,this.filters=n,this.limit=i,this.startAt=r,this.endAt=o,this.Ye=null}canonicalId(){if(null===this.Ye){let t=this.path.ot();null!==this.collectionGroup&&(t+="|cg:"+this.collectionGroup),t+="|f:";for(const e of this.filters)t+=e.canonicalId(),t+=",";t+="|ob:";for(const e of this.orderBy)t+=e.canonicalId(),t+=",";Ie(this.limit)||(t+="|l:",t+=this.limit),this.startAt&&(t+="|lb:",t+=this.startAt.canonicalId()),this.endAt&&(t+="|ub:",t+=this.endAt.canonicalId()),this.Ye=t}return this.Ye}toString(){let t=this.path.ot();return null!==this.collectionGroup&&(t+=" collectionGroup="+this.collectionGroup),this.filters.length>0&&(t+=`, filters: [${this.filters.join(", ")}]`),Ie(this.limit)||(t+=", limit: "+this.limit),this.orderBy.length>0&&(t+=`, orderBy: [${this.orderBy.join(", ")}]`),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),`Target(${t})`}isEqual(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(let e=0;e<this.orderBy.length;e++)if(!this.orderBy[e].isEqual(t.orderBy[e]))return!1;if(this.filters.length!==t.filters.length)return!1;for(let e=0;e<this.filters.length;e++)if(!this.filters[e].isEqual(t.filters[e]))return!1;return this.collectionGroup===t.collectionGroup&&(!!this.path.isEqual(t.path)&&(!(null!==this.startAt?!this.startAt.isEqual(t.startAt):null!==t.startAt)&&(null!==this.endAt?this.endAt.isEqual(t.endAt):null===t.endAt)))}Xe(){return Pt.dt(this.path)&&null===this.collectionGroup&&0===this.filters.length}}var Pe,Ve;(Ve=Pe||(Pe={})).Ze="F",Ve.ts="L";class pe{constructor(t,e=null,s=[],n=[],i=null,r=Pe.Ze,o=null,h=null){this.path=t,this.collectionGroup=e,this.es=s,this.filters=n,this.limit=i,this.ss=r,this.startAt=o,this.endAt=h,this.ns=null,this.rs=null,this.startAt&&this.os(this.startAt),this.endAt&&this.os(this.endAt)}static hs(t){return new pe(t)}get orderBy(){if(null===this.ns){const t=this.as(),e=this.us();if(null!==t&&null===e)t.ct()?this.ns=[xe]:this.ns=[new $e(t),xe];else{p(null===t||null!==e&&t.isEqual(e),"First orderBy should match inequality field."),this.ns=[];let s=!1;for(const t of this.es)this.ns.push(t),t.field.ct()&&(s=!0);if(!s){const t=this.es.length>0?this.es[this.es.length-1].dir:Ne.ASCENDING;this.ns.push(t===Ne.ASCENDING?xe:Me)}}}return this.ns}cs(t){p(null==this.as()||!(t instanceof be)||!t.ls()||t.field.isEqual(this.as()),"Query must only have one inequality field."),p(!this.Xe(),"No filtering allowed for document query");const e=this.filters.concat([t]);return new pe(this.path,this.collectionGroup,this.es.slice(),e,this.limit,this.ss,this.startAt,this.endAt)}_s(t){p(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");const e=this.es.concat([t]);return new pe(this.path,this.collectionGroup,e,this.filters.slice(),this.limit,this.ss,this.startAt,this.endAt)}ds(t){return new pe(this.path,this.collectionGroup,this.es.slice(),this.filters.slice(),t,Pe.Ze,this.startAt,this.endAt)}fs(t){return new pe(this.path,this.collectionGroup,this.es.slice(),this.filters.slice(),t,Pe.ts,this.startAt,this.endAt)}ms(t){return new pe(this.path,this.collectionGroup,this.es.slice(),this.filters.slice(),this.limit,this.ss,t,this.endAt)}Ts(t){return new pe(this.path,this.collectionGroup,this.es.slice(),this.filters.slice(),this.limit,this.ss,this.startAt,t)}Es(t){return new pe(t,null,this.es.slice(),this.filters.slice(),this.limit,this.ss,this.startAt,this.endAt)}ws(){return 0===this.filters.length&&null===this.limit&&null==this.startAt&&null==this.endAt&&(0===this.es.length||1===this.es.length&&this.es[0].field.ct())}canonicalId(){return`${this.Is().canonicalId()}|lt:${this.ss}`}toString(){return`Query(target=${this.Is().toString()}; limitType=${this.ss})`}isEqual(t){return this.Is().isEqual(t.Is())&&this.ss===t.ss}Rs(t,e){let s=!1;for(const n of this.orderBy){const i=n.compare(t,e);if(0!==i)return i;s=s||n.field.ct()}return p(s,"orderBy used that doesn't compare on key field"),0}matches(t){return this.As(t)&&this.Ps(t)&&this.Vs(t)&&this.ps(t)}gs(){return!Ie(this.limit)&&this.ss===Pe.Ze}ys(){return!Ie(this.limit)&&this.ss===Pe.ts}us(){return this.es.length>0?this.es[0].field:null}as(){for(const t of this.filters)if(t instanceof be&&t.ls())return t.field;return null}bs(t){for(const e of this.filters)if(e instanceof be&&t.indexOf(e.op)>=0)return e.op;return null}Xe(){return this.Is().Xe()}vs(){return null!==this.collectionGroup}Is(){if(!this.rs)if(this.ss===Pe.Ze)this.rs=new Ae(this.path,this.collectionGroup,this.orderBy,this.filters,this.limit,this.startAt,this.endAt);else{const t=[];for(const e of this.orderBy){const s=e.dir===Ne.DESCENDING?Ne.ASCENDING:Ne.DESCENDING;t.push(new $e(e.field,s))}const e=this.endAt?new Fe(this.endAt.position,!this.endAt.before):null,s=this.startAt?new Fe(this.startAt.position,!this.startAt.before):null;this.rs=new Ae(this.path,this.collectionGroup,t,this.filters,this.limit,e,s)}return this.rs}As(t){const e=t.key.path;return null!==this.collectionGroup?t.key.ft(this.collectionGroup)&&this.path.nt(e):Pt.dt(this.path)?this.path.isEqual(e):this.path.it(e)}Ps(t){for(const e of this.es)if(!e.field.ct()&&null===t.field(e.field))return!1;return!0}Vs(t){for(const e of this.filters)if(!e.matches(t))return!1;return!0}ps(t){return!(this.startAt&&!this.startAt.Ss(this.orderBy,t))&&(!this.endAt||!this.endAt.Ss(this.orderBy,t))}os(t){p(t.position.length<=this.orderBy.length,"Bound is longer than orderBy")}}class ge{}class ye{constructor(t){this.name=t}static ht(t){switch(t){case"<":return ye.LESS_THAN;case"<=":return ye.LESS_THAN_OR_EQUAL;case"==":return ye.EQUAL;case">=":return ye.GREATER_THAN_OR_EQUAL;case">":return ye.GREATER_THAN;case"array-contains":return ye.ARRAY_CONTAINS;case"in":return ye.IN;case"array-contains-any":return ye.ARRAY_CONTAINS_ANY;default:return V("Unknown FieldFilter operator: "+t)}}toString(){return this.name}isEqual(t){return this.name===t.name}}ye.LESS_THAN=new ye("<"),ye.LESS_THAN_OR_EQUAL=new ye("<="),ye.EQUAL=new ye("=="),ye.GREATER_THAN=new ye(">"),ye.GREATER_THAN_OR_EQUAL=new ye(">="),ye.ARRAY_CONTAINS=new ye("array-contains"),ye.IN=new ye("in"),ye.ARRAY_CONTAINS_ANY=new ye("array-contains-any");class be extends ge{constructor(t,e,s){super(),this.field=t,this.op=e,this.value=s}static create(t,e,s){if(t.ct())return e===ye.IN?(p(s instanceof ce,"Comparing on key with IN, but filter value not an ArrayValue"),p(s.te.every(t=>t instanceof he),"Comparing on key with IN, but an array value was not a RefValue"),new Se(t,s)):(p(s instanceof he,"Comparing on key, but filter value not a RefValue"),p(e!==ye.ARRAY_CONTAINS&&e!==ye.ARRAY_CONTAINS_ANY,`'${e.toString()}' queries don't make sense on document keys.`),new ve(t,e,s));if(s.isEqual(Yt.Be)){if(e!==ye.EQUAL)throw new L(M.INVALID_ARGUMENT,"Invalid query. Null supports only equality comparisons.");return new be(t,e,s)}if(s.isEqual(se.Ue)){if(e!==ye.EQUAL)throw new L(M.INVALID_ARGUMENT,"Invalid query. NaN supports only equality comparisons.");return new be(t,e,s)}return e===ye.ARRAY_CONTAINS?new De(t,s):e===ye.IN?(p(s instanceof ce,"IN filter has invalid value: "+s.toString()),new Ce(t,s)):e===ye.ARRAY_CONTAINS_ANY?(p(s instanceof ce,"ARRAY_CONTAINS_ANY filter has invalid value: "+s.toString()),new ke(t,s)):new be(t,e,s)}matches(t){const e=t.field(this.field);return null!==e&&this.value.Me===e.Me&&this.Ds(e.u(this.value))}Ds(t){switch(this.op){case ye.LESS_THAN:return t<0;case ye.LESS_THAN_OR_EQUAL:return t<=0;case ye.EQUAL:return 0===t;case ye.GREATER_THAN:return t>0;case ye.GREATER_THAN_OR_EQUAL:return t>=0;default:return V("Unknown FieldFilter operator: "+this.op)}}ls(){return[ye.LESS_THAN,ye.LESS_THAN_OR_EQUAL,ye.GREATER_THAN,ye.GREATER_THAN_OR_EQUAL].indexOf(this.op)>=0}canonicalId(){return this.field.ot()+this.op.toString()+this.value.toString()}isEqual(t){return t instanceof be&&(this.op.isEqual(t.op)&&this.field.isEqual(t.field)&&this.value.isEqual(t.value))}toString(){return`${this.field.ot()} ${this.op} ${this.value.value()}`}}class ve extends be{matches(t){const e=this.value,s=Pt.J(t.key,e.key);return this.Ds(s)}}class Se extends be{constructor(t,e){super(t,ye.IN,e),this.value=e}matches(t){return this.value.te.some(e=>t.key.isEqual(e.key))}}class De extends be{constructor(t,e){super(t,ye.ARRAY_CONTAINS,e)}matches(t){const e=t.field(this.field);return e instanceof ce&&e.contains(this.value)}}class Ce extends be{constructor(t,e){super(t,ye.IN,e),this.value=e}matches(t){const e=this.value,s=t.field(this.field);return null!==s&&e.contains(s)}}class ke extends be{constructor(t,e){super(t,ye.ARRAY_CONTAINS_ANY,e),this.value=e}matches(t){const e=t.field(this.field);return e instanceof ce&&e.te.some(t=>this.value.contains(t))}}class Ne{constructor(t){this.name=t}toString(){return this.name}}Ne.ASCENDING=new Ne("asc"),Ne.DESCENDING=new Ne("desc");class Fe{constructor(t,e){this.position=t,this.before=e}canonicalId(){let t=this.before?"b:":"a:";for(const e of this.position)t+=e.toString();return t}Ss(t,e){p(this.position.length<=t.length,"Bound has more components than query's orderBy");let s=0;for(let n=0;n<this.position.length;n++){const i=t[n],r=this.position[n];if(i.field.ct())p(r instanceof he,"Bound has a non-key value where the key path is being used."),s=Pt.J(r.key,e.key);else{const t=e.field(i.field);p(null!==t,"Field should exist since document matched the orderBy already."),s=r.u(t)}if(i.dir===Ne.DESCENDING&&(s*=-1),0!==s)break}return this.before?s<=0:s<0}isEqual(t){if(null===t)return!1;if(this.before!==t.before||this.position.length!==t.position.length)return!1;for(let e=0;e<this.position.length;e++){const s=this.position[e],n=t.position[e];if(!s.isEqual(n))return!1}return!0}}class $e{constructor(t,e){this.field=t,void 0===e&&(e=Ne.ASCENDING),this.dir=e,this.Cs=t.ct()}compare(t,e){const s=this.Cs?_e.ze(t,e):_e.Je(this.field,t,e);switch(this.dir){case Ne.ASCENDING:return s;case Ne.DESCENDING:return-1*s;default:return V("Unknown direction: "+this.dir)}}canonicalId(){return this.field.ot()+this.dir.toString()}toString(){return`${this.field.ot()} (${this.dir})`}isEqual(t){return this.dir===t.dir&&this.field.isEqual(t.field)}}const xe=new $e(At.lt(),Ne.ASCENDING),Me=new $e(At.lt(),Ne.DESCENDING);var Le,Be,qe,Oe;(Be=Le||(Le={}))[Be.ks=0]="__PRIVATE_Listen",Be[Be.Ns=1]="__PRIVATE_ExistenceFilterMismatch",Be[Be.Fs=2]="__PRIVATE_LimboResolution";class Ue{constructor(t,e,s,n,i=Tt.MIN,r=Tt.MIN,o=Ds()){this.target=t,this.targetId=e,this.$s=s,this.sequenceNumber=n,this.xs=i,this.lastLimboFreeSnapshotVersion=r,this.resumeToken=o}Ms(t){return new Ue(this.target,this.targetId,this.$s,t,this.xs,this.lastLimboFreeSnapshotVersion,this.resumeToken)}Ls(t,e){return new Ue(this.target,this.targetId,this.$s,this.sequenceNumber,e,this.lastLimboFreeSnapshotVersion,t)}Bs(t){return new Ue(this.target,this.targetId,this.$s,this.sequenceNumber,this.xs,t,this.resumeToken)}isEqual(t){return this.targetId===t.targetId&&this.$s===t.$s&&this.sequenceNumber===t.sequenceNumber&&this.xs.isEqual(t.xs)&&this.lastLimboFreeSnapshotVersion.isEqual(t.lastLimboFreeSnapshotVersion)&&this.resumeToken===t.resumeToken&&this.target.isEqual(t.target)}}class Qe{constructor(t){this.count=t}isEqual(t){return t&&t.count===this.count}}function We(t){switch(t){case M.OK:return V("Treated status OK as error");case M.CANCELLED:case M.UNKNOWN:case M.DEADLINE_EXCEEDED:case M.RESOURCE_EXHAUSTED:case M.INTERNAL:case M.UNAVAILABLE:case M.UNAUTHENTICATED:return!1;case M.INVALID_ARGUMENT:case M.NOT_FOUND:case M.ALREADY_EXISTS:case M.PERMISSION_DENIED:case M.FAILED_PRECONDITION:case M.ABORTED:case M.OUT_OF_RANGE:case M.UNIMPLEMENTED:case M.DATA_LOSS:return!0;default:return V("Unknown status code: "+t)}}function je(t){if(void 0===t)return A("GRPC error has no .code"),M.UNKNOWN;switch(t){case qe.OK:return M.OK;case qe.CANCELLED:return M.CANCELLED;case qe.UNKNOWN:return M.UNKNOWN;case qe.DEADLINE_EXCEEDED:return M.DEADLINE_EXCEEDED;case qe.RESOURCE_EXHAUSTED:return M.RESOURCE_EXHAUSTED;case qe.INTERNAL:return M.INTERNAL;case qe.UNAVAILABLE:return M.UNAVAILABLE;case qe.UNAUTHENTICATED:return M.UNAUTHENTICATED;case qe.INVALID_ARGUMENT:return M.INVALID_ARGUMENT;case qe.NOT_FOUND:return M.NOT_FOUND;case qe.ALREADY_EXISTS:return M.ALREADY_EXISTS;case qe.PERMISSION_DENIED:return M.PERMISSION_DENIED;case qe.FAILED_PRECONDITION:return M.FAILED_PRECONDITION;case qe.ABORTED:return M.ABORTED;case qe.OUT_OF_RANGE:return M.OUT_OF_RANGE;case qe.UNIMPLEMENTED:return M.UNIMPLEMENTED;case qe.DATA_LOSS:return M.DATA_LOSS;default:return V("Unknown status code: "+t)}}function ze(t){if(void 0===t)return qe.OK;switch(t){case M.OK:return qe.OK;case M.CANCELLED:return qe.CANCELLED;case M.UNKNOWN:return qe.UNKNOWN;case M.DEADLINE_EXCEEDED:return qe.DEADLINE_EXCEEDED;case M.RESOURCE_EXHAUSTED:return qe.RESOURCE_EXHAUSTED;case M.INTERNAL:return qe.INTERNAL;case M.UNAVAILABLE:return qe.UNAVAILABLE;case M.UNAUTHENTICATED:return qe.UNAUTHENTICATED;case M.INVALID_ARGUMENT:return qe.INVALID_ARGUMENT;case M.NOT_FOUND:return qe.NOT_FOUND;case M.ALREADY_EXISTS:return qe.ALREADY_EXISTS;case M.PERMISSION_DENIED:return qe.PERMISSION_DENIED;case M.FAILED_PRECONDITION:return qe.FAILED_PRECONDITION;case M.ABORTED:return qe.ABORTED;case M.OUT_OF_RANGE:return qe.OUT_OF_RANGE;case M.UNIMPLEMENTED:return qe.UNIMPLEMENTED;case M.DATA_LOSS:return qe.DATA_LOSS;default:return V("Unknown status code: "+t)}}(Oe=qe||(qe={}))[Oe.OK=0]="OK",Oe[Oe.CANCELLED=1]="CANCELLED",Oe[Oe.UNKNOWN=2]="UNKNOWN",Oe[Oe.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Oe[Oe.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Oe[Oe.NOT_FOUND=5]="NOT_FOUND",Oe[Oe.ALREADY_EXISTS=6]="ALREADY_EXISTS",Oe[Oe.PERMISSION_DENIED=7]="PERMISSION_DENIED",Oe[Oe.UNAUTHENTICATED=16]="UNAUTHENTICATED",Oe[Oe.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Oe[Oe.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Oe[Oe.ABORTED=10]="ABORTED",Oe[Oe.OUT_OF_RANGE=11]="OUT_OF_RANGE",Oe[Oe.UNIMPLEMENTED=12]="UNIMPLEMENTED",Oe[Oe.INTERNAL=13]="INTERNAL",Oe[Oe.UNAVAILABLE=14]="UNAVAILABLE",Oe[Oe.DATA_LOSS=15]="DATA_LOSS";const Ke=new Vt(Pt.J);function Ge(){return Ke}function He(){return Ge()}const Je=new Vt(Pt.J);function Ye(){return Je}const Xe=new Vt(Pt.J);function Ze(){return Xe}const ts=new yt(Pt.J);function es(...t){let e=ts;for(const s of t)e=e.add(s);return e}const ss=new yt(y);function ns(){return ss}class is{constructor(t){this.J=t?(e,s)=>t(e,s)||Pt.J(e.key,s.key):(t,e)=>Pt.J(t.key,e.key),this.qs=Ye(),this.Os=new Vt(this.J)}static Us(t){return new is(t.J)}has(t){return null!=this.qs.get(t)}get(t){return this.qs.get(t)}first(){return this.Os.At()}last(){return this.Os.Pt()}tt(){return this.Os.tt()}indexOf(t){const e=this.qs.get(t);return e?this.Os.indexOf(e):-1}get size(){return this.Os.size}forEach(t){this.Os.Vt((e,s)=>(t(e),!1))}add(t){const e=this.delete(t.key);return e.It(e.qs.wt(t.key,t),e.Os.wt(t,null))}delete(t){const e=this.get(t);return e?this.It(this.qs.remove(t),this.Os.remove(e)):this}isEqual(t){if(!(t instanceof is))return!1;if(this.size!==t.size)return!1;const e=this.Os.gt(),s=t.Os.gt();for(;e.kt();){const t=e.Ct().key,n=s.Ct().key;if(!t.isEqual(n))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n  "+t.join("  \n")+"\n)"}It(t,e){const s=new is;return s.J=this.J,s.qs=t,s.Os=e,s}}var rs,os,hs,as,us,cs;(os=rs||(rs={}))[os.Qs=0]="__PRIVATE_Added",os[os.Ws=1]="__PRIVATE_Removed",os[os.js=2]="__PRIVATE_Modified",os[os.zs=3]="__PRIVATE_Metadata",(as=hs||(hs={}))[as.Ks=0]="__PRIVATE_Local",as[as.Gs=1]="__PRIVATE_Synced";class ls{constructor(){this.Hs=new Vt(Pt.J)}track(t){const e=t.doc.key,s=this.Hs.get(e);s?t.type!==rs.Qs&&s.type===rs.zs?this.Hs=this.Hs.wt(e,t):t.type===rs.zs&&s.type!==rs.Ws?this.Hs=this.Hs.wt(e,{type:s.type,doc:t.doc}):t.type===rs.js&&s.type===rs.js?this.Hs=this.Hs.wt(e,{type:rs.js,doc:t.doc}):t.type===rs.js&&s.type===rs.Qs?this.Hs=this.Hs.wt(e,{type:rs.Qs,doc:t.doc}):t.type===rs.Ws&&s.type===rs.Qs?this.Hs=this.Hs.remove(e):t.type===rs.Ws&&s.type===rs.js?this.Hs=this.Hs.wt(e,{type:rs.Ws,doc:s.doc}):t.type===rs.Qs&&s.type===rs.Ws?this.Hs=this.Hs.wt(e,{type:rs.js,doc:t.doc}):V("unsupported combination of changes: "+JSON.stringify(t)+" after "+JSON.stringify(s)):this.Hs=this.Hs.wt(e,t)}Js(){const t=[];return this.Hs.Vt((e,s)=>{t.push(s)}),t}}class _s{constructor(t,e,s,n,i,r,o,h){this.query=t,this.docs=e,this.Ys=s,this.docChanges=n,this.Xs=i,this.fromCache=r,this.Zs=o,this.tn=h}static en(t,e,s,n){const i=[];return e.forEach(t=>{i.push({type:rs.Qs,doc:t})}),new _s(t,e,is.Us(e),i,s,n,!0,!1)}get hasPendingWrites(){return!this.Xs.tt()}isEqual(t){if(!(this.fromCache===t.fromCache&&this.Zs===t.Zs&&this.Xs.isEqual(t.Xs)&&this.query.isEqual(t.query)&&this.docs.isEqual(t.docs)&&this.Ys.isEqual(t.Ys)))return!1;const e=this.docChanges,s=t.docChanges;if(e.length!==s.length)return!1;for(let t=0;t<e.length;t++)if(e[t].type!==s[t].type||!e[t].doc.isEqual(s[t].doc))return!1;return!0}}class ds{constructor(t,e,s,n,i){this.xs=t,this.sn=e,this.nn=s,this.in=n,this.rn=i}static on(t,e){const s={[t]:fs.hn(t,e)};return new ds(Tt.MIN,s,ns(),Ge(),es())}}class fs{constructor(t,e,s,n,i){this.resumeToken=t,this.an=e,this.un=s,this.cn=n,this.ln=i}static hn(t,e){return new fs(Ds(),e,es(),es(),es())}}class ms{constructor(t,e,s,n){this._n=t,this.removedTargetIds=e,this.key=s,this.dn=n}}class Ts{constructor(t,e){this.targetId=t,this.fn=e}}(cs=us||(us={}))[cs.mn=0]="__PRIVATE_NoChange",cs[cs.Qs=1]="__PRIVATE_Added",cs[cs.Ws=2]="__PRIVATE_Removed",cs[cs.Tn=3]="__PRIVATE_Current",cs[cs.En=4]="__PRIVATE_Reset";class Es{constructor(t,e,s=Ds(),n=null){this.state=t,this.targetIds=e,this.resumeToken=s,this.cause=n}}class ws{constructor(){this.wn=0,this.In=Ps(),this.Rn=Ds(),this.An=!1,this.Pn=!0}get an(){return this.An}get resumeToken(){return this.Rn}get Vn(){return 0!==this.wn}get pn(){return this.Pn}gn(t){t.length>0&&(this.Pn=!0,this.Rn=t)}yn(){let t=es(),e=es(),s=es();return this.In.forEach((n,i)=>{switch(i){case rs.Qs:t=t.add(n);break;case rs.js:e=e.add(n);break;case rs.Ws:s=s.add(n);break;default:V("Encountered invalid change type: "+i)}}),new fs(this.Rn,this.An,t,e,s)}bn(){this.Pn=!1,this.In=Ps()}vn(t,e){this.Pn=!0,this.In=this.In.wt(t,e)}Sn(t){this.Pn=!0,this.In=this.In.remove(t)}Dn(){this.wn+=1}Cn(){this.wn-=1}kn(){this.Pn=!0,this.An=!0}}const Is="WatchChangeAggregator";class Rs{constructor(t){this.Nn=t,this.Fn={},this.$n=Ge(),this.xn=As(),this.Mn=new yt(y)}Ln(t){for(const e of t._n)t.dn instanceof _e?this.Bn(e,t.dn):t.dn instanceof de&&this.qn(e,t.key,t.dn);for(const e of t.removedTargetIds)this.qn(e,t.key,t.dn)}On(t){this.Un(t,e=>{const s=this.Qn(e);switch(t.state){case us.mn:this.Wn(e)&&s.gn(t.resumeToken);break;case us.Qs:s.Cn(),s.Vn||s.bn(),s.gn(t.resumeToken);break;case us.Ws:s.Cn(),s.Vn||this.removeTarget(e),p(!t.cause,"WatchChangeAggregator does not handle errored targets");break;case us.Tn:this.Wn(e)&&(s.kn(),s.gn(t.resumeToken));break;case us.En:this.Wn(e)&&(this.jn(e),s.gn(t.resumeToken));break;default:V("Unknown target watch change state: "+t.state)}})}Un(t,e){t.targetIds.length>0?t.targetIds.forEach(e):z(this.Fn,e)}zn(t){const e=t.targetId,s=t.fn.count,n=this.Kn(e);if(n){const t=n.target;if(t.Xe())if(0===s){const s=new Pt(t.path);this.qn(e,s,new de(s,Tt.j()))}else p(1===s,"Single document existence filter with count: "+s);else{this.Gn(e)!==s&&(this.jn(e),this.Mn=this.Mn.add(e))}}}Hn(t){const e={};z(this.Fn,(s,n)=>{const i=this.Kn(s);if(i){if(n.an&&i.target.Xe()){const e=new Pt(i.target.path);null!==this.$n.get(e)||this.Jn(s,e)||this.qn(s,e,new de(e,t))}n.pn&&(e[s]=n.yn(),n.bn())}});let s=es();this.xn.forEach((t,e)=>{let n=!0;e.zt(t=>{const e=this.Kn(t);return!e||e.$s===Le.Fs||(n=!1,!1)}),n&&(s=s.add(t))});const n=new ds(t,e,this.Mn,this.$n,s);return this.$n=Ge(),this.xn=As(),this.Mn=new yt(y),n}Bn(t,e){if(!this.Wn(t))return;const s=this.Jn(t,e.key)?rs.js:rs.Qs;this.Qn(t).vn(e.key,s),this.$n=this.$n.wt(e.key,e),this.xn=this.xn.wt(e.key,this.Yn(e.key).add(t))}qn(t,e,s){if(!this.Wn(t))return;const n=this.Qn(t);this.Jn(t,e)?n.vn(e,rs.Ws):n.Sn(e),this.xn=this.xn.wt(e,this.Yn(e).delete(t)),s&&(this.$n=this.$n.wt(e,s))}removeTarget(t){delete this.Fn[t]}Gn(t){const e=this.Qn(t).yn();return this.Nn.Xn(t).size+e.un.size-e.ln.size}Dn(t){this.Qn(t).Dn()}Qn(t){return this.Fn[t]||(this.Fn[t]=new ws),this.Fn[t]}Yn(t){let e=this.xn.get(t);return e||(e=new yt(y),this.xn=this.xn.wt(t,e)),e}Wn(t){const e=null!==this.Kn(t);return e||R(Is,"Detected inactive target",t),e}Kn(t){const e=this.Fn[t];return e&&e.Vn?null:this.Nn.Zn(t)}jn(t){p(!this.Fn[t].Vn,"Should only reset active targets"),this.Fn[t]=new ws,this.Nn.Xn(t).forEach(e=>{this.qn(t,e,null)})}Jn(t,e){return this.Nn.Xn(t).has(e)}}function As(){return new Vt(Pt.J)}function Ps(){return new Vt(Pt.J)}const Vs=(()=>{const t={};return t[Ne.ASCENDING.name]="ASCENDING",t[Ne.DESCENDING.name]="DESCENDING",t})(),ps=(()=>{const t={};return t[ye.LESS_THAN.name]="LESS_THAN",t[ye.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",t[ye.GREATER_THAN.name]="GREATER_THAN",t[ye.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",t[ye.EQUAL.name]="EQUAL",t[ye.ARRAY_CONTAINS.name]="ARRAY_CONTAINS",t[ye.IN.name]="IN",t[ye.ARRAY_CONTAINS_ANY.name]="ARRAY_CONTAINS_ANY",t})(),gs=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ys(t,e){p(!Ie(t),e+" is missing")}function bs(t){return"number"==typeof t?t:"string"==typeof t?Number(t):V("can't parse "+t)}class vs{constructor(t,e){this.o=t,this.options=e}ti(){return this.options.ei?"":new Uint8Array(0)}si(t){return t}ni(t){const e=void 0===t.code?M.UNKNOWN:je(t.code);return new L(e,t.message||"")}ii(t){return this.options.ei||Ie(t)?t:{value:t}}ri(t){let e;return Ie(e="object"==typeof t?t.value:t)?null:e}G(t){if(this.options.ei){return`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`}return{seconds:""+t.seconds,nanos:t.nanoseconds}}W(t){if("string"==typeof t)return this.oi(t);{p(!!t,"Cannot deserialize null or undefined timestamp.");const e=bs(t.seconds||"0"),s=t.nanos||0;return new mt(e,s)}}oi(t){let e=0;const s=gs.exec(t);if(p(!!s,"invalid timestamp: "+t),s[1]){let t=s[1];t=(t+"000000000").substr(0,9),e=Number(t)}const n=new Date(t),i=Math.floor(n.getTime()/1e3);return new mt(i,e)}hi(t){return this.options.ei?t.toBase64():this.si(t.toUint8Array())}ai(t){return"string"==typeof t?(p(this.options.ei,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Fs.fromBase64String(t)):(p(!this.options.ei,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Fs.fromUint8Array(t))}toVersion(t){return this.G(t.G())}fromVersion(t){return p(!!t,"Trying to deserialize version that isn't set"),Tt.W(this.W(t))}ui(t,e){return this.ci(t).child("documents").child(e).ot()}li(t){const e=It.ht(t);return p(this._i(e),"Tried to deserialize invalid key "+e.toString()),e}di(t){return this.ui(this.o,t.path)}fi(t){const e=this.li(t);return p(e.get(1)===this.o.projectId,"Tried to deserialize key from different project: "+e.get(1)+" vs "+this.o.projectId),p(!e.get(3)&&!this.o.database||e.get(3)===this.o.database,"Tried to deserialize key from different database: "+e.get(3)+" vs "+this.o.database),new Pt(this.mi(e))}Ti(t){return this.ui(this.o,t)}Ei(t){const e=this.li(t);return 4===e.length?It.at:this.mi(e)}get wi(){return new It(["projects",this.o.projectId,"databases",this.o.database]).ot()}ci(t){return new It(["projects",t.projectId,"databases",t.database])}mi(t){return p(t.length>4&&"documents"===t.get(4),"tried to deserialize invalid key "+t.toString()),t.X(5)}_i(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)}Ii(t){if(t instanceof Yt)return{nullValue:"NULL_VALUE"};if(t instanceof Xt)return{booleanValue:t.value()};if(t instanceof ee)return{integerValue:""+t.value()};if(t instanceof se){const e=t.value();if(this.options.ei){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:t.value()}}return t instanceof ne?{stringValue:t.value()}:t instanceof ue?{mapValue:this.Ri(t)}:t instanceof ce?{arrayValue:this.Ai(t)}:t instanceof ie?{timestampValue:this.G(t.te)}:t instanceof ae?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof oe?{bytesValue:this.hi(t.value())}:t instanceof he?{referenceValue:this.ui(t.o,t.key.path)}:V("Unknown FieldValue "+JSON.stringify(t))}Pi(t){if("nullValue"in t)return Yt.Be;if("booleanValue"in t)return Xt.of(t.booleanValue);if("integerValue"in t)return new ee(bs(t.integerValue));if("doubleValue"in t){if(this.options.ei){if("NaN"===t.doubleValue)return se.Ue;if("Infinity"===t.doubleValue)return se.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return se.NEGATIVE_INFINITY}return new se(t.doubleValue)}if("stringValue"in t)return new ne(t.stringValue);if("mapValue"in t)return this.Vi(t.mapValue.fields||{});if("arrayValue"in t){ys(t.arrayValue,"arrayValue");const e=t.arrayValue.values||[];return new ce(e.map(t=>this.Pi(t)))}if("timestampValue"in t)return ys(t.timestampValue,"timestampValue"),new ie(this.W(t.timestampValue));if("geoPointValue"in t){ys(t.geoPointValue,"geoPointValue");const e=t.geoPointValue.latitude||0,s=t.geoPointValue.longitude||0;return new ae(new ft(e,s))}if("bytesValue"in t){ys(t.bytesValue,"bytesValue");const e=this.ai(t.bytesValue);return new oe(e)}if("referenceValue"in t){ys(t.referenceValue,"referenceValue");const e=this.li(t.referenceValue),s=new C(e.get(1),e.get(3)),n=new Pt(this.mi(e));return new he(s,n)}return V("Unknown Value proto "+JSON.stringify(t))}pi(t,e){return{name:this.di(t),fields:this.gi(e)}}yi(t){return p(!t.de,"Can't serialize documents with mutations."),{name:this.di(t.key),fields:this.gi(t.data()),updateTime:this.G(t.version.G())}}bi(t,e){const s=this.fi(t.name),n=this.fromVersion(t.updateTime);return new _e(s,n,{hasCommittedMutations:!!e},void 0,t,t=>this.Pi(t))}gi(t){const e={};return t.forEach((t,s)=>{e[t]=this.Ii(s)}),e}Vi(t){const e=t;let s=ue.EMPTY;return K(e,(t,e)=>{s=s.set(new At([t]),this.Pi(e))}),s}Ri(t){return{fields:this.gi(t)}}Ai(t){const e=[];return t.forEach(t=>{e.push(this.Ii(t))}),{values:e}}vi(t){p(!!t.found,"Tried to deserialize a found document from a missing document."),ys(t.found.name,"doc.found.name"),ys(t.found.updateTime,"doc.found.updateTime");const e=this.fi(t.found.name),s=this.fromVersion(t.found.updateTime);return new _e(e,s,{},void 0,t.found,t=>this.Pi(t))}Si(t){p(!!t.missing,"Tried to deserialize a missing document from a found document."),p(!!t.readTime,"Tried to deserialize a missing document without a read time.");const e=this.fi(t.missing),s=this.fromVersion(t.readTime);return new de(e,s)}Di(t){return"found"in t?this.vi(t):"missing"in t?this.Si(t):V("invalid batch get response: "+JSON.stringify(t))}Ci(t){switch(t){case us.Qs:return"ADD";case us.Tn:return"CURRENT";case us.mn:return"NO_CHANGE";case us.Ws:return"REMOVE";case us.En:return"RESET";default:return V("Unknown WatchTargetChangeState: "+t)}}ki(t){if(t instanceof Ts)return{filter:{count:t.fn.count,targetId:t.targetId}};if(t instanceof ms){if(t.dn instanceof _e){const e=t.dn;return{documentChange:{document:{name:this.di(e.key),fields:this.gi(e.data()),updateTime:this.toVersion(e.version)},targetIds:t._n,removedTargetIds:t.removedTargetIds}}}if(t.dn instanceof de){const e=t.dn;return{documentDelete:{document:this.di(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.dn)return{documentRemove:{document:this.di(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof Es){let e=void 0;return t.cause&&(e={code:ze(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.Ci(t.state),targetIds:t.targetIds,resumeToken:this.si(t.resumeToken),cause:e}}}return V("Unrecognized watch change: "+JSON.stringify(t))}Ni(t){let e;if("targetChange"in t){ys(t.targetChange,"targetChange");const s=this.Fi(t.targetChange.targetChangeType||"NO_CHANGE"),n=t.targetChange.targetIds||[],i=t.targetChange.resumeToken||this.ti(),r=t.targetChange.cause,o=r&&this.ni(r);e=new Es(s,n,i,o||null)}else if("documentChange"in t){ys(t.documentChange,"documentChange");const s=t.documentChange;ys(s.document,"documentChange.name"),ys(s.document.name,"documentChange.document.name"),ys(s.document.updateTime,"documentChange.document.updateTime");const n=this.fi(s.document.name),i=this.fromVersion(s.document.updateTime),r=new _e(n,i,{},void 0,s.document,t=>this.Pi(t)),o=s.targetIds||[],h=s.removedTargetIds||[];e=new ms(o,h,r.key,r)}else if("documentDelete"in t){ys(t.documentDelete,"documentDelete");const s=t.documentDelete;ys(s.document,"documentDelete.document");const n=this.fi(s.document),i=s.readTime?this.fromVersion(s.readTime):Tt.j(),r=new de(n,i),o=s.removedTargetIds||[];e=new ms([],o,r.key,r)}else if("documentRemove"in t){ys(t.documentRemove,"documentRemove");const s=t.documentRemove;ys(s.document,"documentRemove");const n=this.fi(s.document),i=s.removedTargetIds||[];e=new ms([],i,n,null)}else{if(!("filter"in t))return V("Unknown change type "+JSON.stringify(t));{ys(t.filter,"filter");const s=t.filter;ys(s.targetId,"filter.targetId");const n=s.count||0,i=new Qe(n),r=s.targetId;e=new Ts(r,i)}}return e}Fi(t){return"NO_CHANGE"===t?us.mn:"ADD"===t?us.Qs:"REMOVE"===t?us.Ws:"CURRENT"===t?us.Tn:"RESET"===t?us.En:V("Got unexpected TargetChange.state: "+t)}$i(t){if(!("targetChange"in t))return Tt.MIN;const e=t.targetChange;return e.targetIds&&e.targetIds.length?Tt.MIN:e.readTime?this.fromVersion(e.readTime):Tt.MIN}xi(t){let e;if(t instanceof Wt)e={update:this.pi(t.key,t.value)};else if(t instanceof Kt)e={delete:this.di(t.key)};else if(t instanceof jt)e={update:this.pi(t.key,t.data),updateMask:this.Mi(t.me)};else if(t instanceof zt)e={transform:{document:this.di(t.key),fieldTransforms:t.fieldTransforms.map(t=>this.Li(t))}};else{if(!(t instanceof Gt))return V("Unknown mutation type "+t.type);e={verify:this.di(t.key)}}return t._e.ae||(e.currentDocument=this.Bi(t._e)),e}qi(t){const e=t.currentDocument?this.Oi(t.currentDocument):Ut.NONE;if(t.update){ys(t.update.name,"name");const s=this.fi(t.update.name),n=this.Vi(t.update.fields||{});if(t.updateMask){const i=this.Ui(t.updateMask);return new jt(s,n,i,e)}return new Wt(s,n,e)}if(t.delete){const s=this.fi(t.delete);return new Kt(s,e)}if(t.transform){const s=this.fi(t.transform.document),n=t.transform.fieldTransforms.map(t=>this.Qi(t));return p(!0===e.exists,'Transforms only support precondition "exists == true"'),new zt(s,n)}if(t.verify){const s=this.fi(t.verify);return new Gt(s,e)}return V("unknown mutation proto: "+JSON.stringify(t))}Bi(t){return p(!t.ae,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:V("Unknown precondition")}Oi(t){return void 0!==t.updateTime?Ut.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?Ut.exists(t.exists):Ut.NONE}Wi(t,e){let s=t.updateTime?this.fromVersion(t.updateTime):this.fromVersion(e);s.isEqual(Tt.MIN)&&(s=this.fromVersion(e));let n=null;return t.transformResults&&t.transformResults.length>0&&(n=t.transformResults.map(t=>this.Pi(t))),new $t(s,n)}ji(t,e){return t&&t.length>0?(p(void 0!==e,"Received a write result without a commit time"),t.map(t=>this.Wi(t,e))):[]}Li(t){const e=t.transform;if(e instanceof vt)return{fieldPath:t.field.ot(),setToServerValue:"REQUEST_TIME"};if(e instanceof St)return{fieldPath:t.field.ot(),appendMissingElements:{values:e.elements.map(t=>this.Ii(t))}};if(e instanceof Dt)return{fieldPath:t.field.ot(),removeAllFromArray:{values:e.elements.map(t=>this.Ii(t))}};if(e instanceof Ct)return{fieldPath:t.field.ot(),increment:this.Ii(e.Zt)};throw V("Unknown transform: "+t.transform)}Qi(t){let e=null;if("setToServerValue"in t)p("REQUEST_TIME"===t.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(t)),e=vt.instance;else if("appendMissingElements"in t){const s=t.appendMissingElements.values||[];e=new St(s.map(t=>this.Pi(t)))}else if("removeAllFromArray"in t){const s=t.removeAllFromArray.values||[];e=new Dt(s.map(t=>this.Pi(t)))}else if("increment"in t){const s=this.Pi(t.increment);p(s instanceof Zt,"NUMERIC_ADD transform requires a NumberValue"),e=new Ct(s)}else V("Unknown transform proto: "+JSON.stringify(t));const s=At._t(t.fieldPath);return new Ft(s,e)}zi(t){return{documents:[this.Ti(t.path)]}}Ki(t){const e=t.documents.length;p(1===e,"DocumentsTarget contained other than 1 document: "+e);const s=t.documents[0];return pe.hs(this.Ei(s)).Is()}Gi(t){const e={structuredQuery:{}},s=t.path;null!==t.collectionGroup?(p(s.length%2==0,"Collection Group queries should be within a document path or root."),e.parent=this.Ti(s),e.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(p(s.length%2!=0,"Document queries with filters are not supported."),e.parent=this.Ti(s.Z()),e.structuredQuery.from=[{collectionId:s.st()}]);const n=this.Hi(t.filters);n&&(e.structuredQuery.where=n);const i=this.Ji(t.orderBy);i&&(e.structuredQuery.orderBy=i);const r=this.ii(t.limit);return null!==r&&(e.structuredQuery.limit=r),t.startAt&&(e.structuredQuery.startAt=this.Yi(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.Yi(t.endAt)),e}Xi(t){let e=this.Ei(t.parent);const s=t.structuredQuery,n=s.from?s.from.length:0;let i=null;if(n>0){p(1===n,"StructuredQuery.from with more than one collection is not supported.");const t=s.from[0];t.allDescendants?i=t.collectionId:e=e.child(t.collectionId)}let r=[];s.where&&(r=this.Zi(s.where));let o=[];s.orderBy&&(o=this.tr(s.orderBy));let h=null;s.limit&&(h=this.ri(s.limit));let a=null;s.startAt&&(a=this.er(s.startAt));let u=null;return s.endAt&&(u=this.er(s.endAt)),new pe(e,i,o,r,h,Pe.Ze,a,u).Is()}sr(t){const e=this.nr(t.$s);return null==e?null:{"goog-listen-tags":e}}nr(t){switch(t){case Le.ks:return null;case Le.Ns:return"existence-filter-mismatch";case Le.Fs:return"limbo-document";default:return V("Unrecognized query purpose: "+t)}}Is(t){let e;const s=t.target;return(e=s.Xe()?{documents:this.zi(s)}:{query:this.Gi(s)}).targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.si(t.resumeToken)),e}Hi(t){if(0===t.length)return;const e=t.map(t=>t instanceof be?this.ir(t):V("Unrecognized filter: "+JSON.stringify(t)));return 1===e.length?e[0]:{compositeFilter:{op:"AND",filters:e}}}Zi(t){return t?void 0!==t.unaryFilter?[this.rr(t)]:void 0!==t.fieldFilter?[this.or(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(t=>this.Zi(t)).reduce((t,e)=>t.concat(e)):V("Unknown filter: "+JSON.stringify(t)):[]}Ji(t){if(0!==t.length)return t.map(t=>this.hr(t))}tr(t){return t.map(t=>this.ar(t))}Yi(t){return{before:t.before,values:t.position.map(t=>this.Ii(t))}}er(t){const e=!!t.before,s=t.values.map(t=>this.Pi(t));return new Fe(s,e)}ur(t){return Vs[t.name]}cr(t){switch(t){case"ASCENDING":return Ne.ASCENDING;case"DESCENDING":return Ne.DESCENDING;default:return}}lr(t){return ps[t.name]}_r(t){switch(t){case"EQUAL":return ye.EQUAL;case"GREATER_THAN":return ye.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return ye.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return ye.LESS_THAN;case"LESS_THAN_OR_EQUAL":return ye.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return ye.ARRAY_CONTAINS;case"IN":return ye.IN;case"ARRAY_CONTAINS_ANY":return ye.ARRAY_CONTAINS_ANY;case"OPERATOR_UNSPECIFIED":return V("Unspecified operator");default:return V("Unknown operator")}}dr(t){return{fieldPath:t.ot()}}mr(t){return At._t(t.fieldPath)}hr(t){return{field:this.dr(t.field),direction:this.ur(t.dir)}}ar(t){return new $e(this.mr(t.field),this.cr(t.direction))}or(t){return be.create(this.mr(t.fieldFilter.field),this._r(t.fieldFilter.op),this.Pi(t.fieldFilter.value))}ir(t){if(t.op===ye.EQUAL){if(t.value.isEqual(se.Ue))return{unaryFilter:{field:this.dr(t.field),op:"IS_NAN"}};if(t.value.isEqual(Yt.Be))return{unaryFilter:{field:this.dr(t.field),op:"IS_NULL"}}}return{fieldFilter:{field:this.dr(t.field),op:this.lr(t.op),value:this.Ii(t.value)}}}rr(t){switch(t.unaryFilter.op){case"IS_NAN":const e=this.mr(t.unaryFilter.field);return be.create(e,ye.EQUAL,se.Ue);case"IS_NULL":const s=this.mr(t.unaryFilter.field);return be.create(s,ye.EQUAL,Yt.Be);case"OPERATOR_UNSPECIFIED":return V("Unspecified filter");default:return V("Unknown filter")}}Mi(t){const e=[];return t.fields.forEach(t=>e.push(t.ot())),{fieldPaths:e}}Ui(t){const e=(t.fieldPaths||[]).map(t=>At._t(t));return Nt.se(e)}}class Ss{static Tr(t){Ss.platform&&V("Platform already defined"),Ss.platform=t}static t(){return Ss.platform||V("Platform not set"),Ss.platform}}function Ds(){return Ss.t().ti}function Cs(t,e){function s(){let t="This constructor is private.";throw e&&(t+=" ",t+=e),new L(M.INVALID_ARGUMENT,t)}s.prototype=t.prototype;for(const e in t)t.hasOwnProperty(e)&&(s[e]=t[e]);return s}function ks(){if("undefined"==typeof Uint8Array)throw new L(M.UNIMPLEMENTED,"Uint8Arrays are not available in this environment.")}function Ns(){if(!Ss.t().Er)throw new L(M.UNIMPLEMENTED,"Blobs are unavailable in Firestore in this environment.")}class Fs{constructor(t){Ns(),this.wr=t}static fromBase64String(t){J("Blob.fromBase64String",arguments,1),Z("Blob.fromBase64String","string",1,t),Ns();try{const e=Ss.t().atob(t);return new Fs(e)}catch(t){throw new L(M.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}}static fromUint8Array(t){if(J("Blob.fromUint8Array",arguments,1),ks(),!(t instanceof Uint8Array))throw ct("Blob.fromUint8Array","Uint8Array",1,t);const e=Array.prototype.map.call(t,t=>String.fromCharCode(t)).join("");return new Fs(e)}toBase64(){return J("Blob.toBase64",arguments,0),Ns(),Ss.t().btoa(this.wr)}toUint8Array(){J("Blob.toUint8Array",arguments,0),ks();const t=new Uint8Array(this.wr.length);for(let e=0;e<this.wr.length;e++)t[e]=this.wr.charCodeAt(e);return t}toString(){return"Blob(base64: "+this.toBase64()+")"}isEqual(t){return this.wr===t.wr}We(){return 2*this.wr.length}O(t){return y(this.wr,t.wr)}}const $s=Cs(Fs,"Use Blob.fromUint8Array() or Blob.fromBase64String() instead.");class xs{constructor(t){this.Ir=t,this.Rr={}}get(t){const e=this.Ir(t),s=this.Rr[e];if(void 0!==s)for(const[e,n]of s)if(e.isEqual(t))return n}has(t){return void 0!==this.get(t)}set(t,e){const s=this.Ir(t),n=this.Rr[s];if(void 0!==n){for(let s=0;s<n.length;s++)if(n[s][0].isEqual(t))return void(n[s]=[t,e]);n.push([t,e])}else this.Rr[s]=[[t,e]]}delete(t){const e=this.Ir(t),s=this.Rr[e];if(void 0===s)return!1;for(let n=0;n<s.length;n++)if(s[n][0].isEqual(t))return 1===s.length?delete this.Rr[e]:s.splice(n,1),!0;return!1}forEach(t){K(this.Rr,(e,s)=>{for(const[e,n]of s)t(e,n)})}tt(){return G(this.Rr)}}const Ms=-1;class Ls{constructor(t,e,s,n){this.batchId=t,this.Qe=e,this.baseMutations=s,this.mutations=n,p(n.length>0,"Cannot create an empty mutation batch")}Yt(t,e,s){e&&p(e.key.isEqual(t),`applyToRemoteDocument: key ${t} should match maybeDoc key\n        ${e.key}`);const n=s.Ar;p(n.length===this.mutations.length,`Mismatch between mutations length\n      (${this.mutations.length}) and mutation results length\n      (${n.length}).`);for(let s=0;s<this.mutations.length;s++){const i=this.mutations[s];if(i.key.isEqual(t)){const t=n[s];e=i.Yt(e,t)}}return e}Jt(t,e){e&&p(e.key.isEqual(t),`applyToLocalDocument: key ${t} should match maybeDoc key\n        ${e.key}`);for(const s of this.baseMutations)s.key.isEqual(t)&&(e=s.Jt(e,e,this.Qe));const s=e;for(const n of this.mutations)n.key.isEqual(t)&&(e=n.Jt(e,s,this.Qe));return e}Pr(t){let e=t;return this.mutations.forEach(s=>{const n=this.Jt(s.key,t.get(s.key));n&&(e=e.wt(s.key,n))}),e}keys(){return this.mutations.reduce((t,e)=>t.add(e.key),es())}isEqual(t){return this.batchId===t.batchId&&b(this.mutations,t.mutations)&&b(this.baseMutations,t.baseMutations)}}class Bs{constructor(t,e,s,n,i){this.batch=t,this.Vr=e,this.Ar=s,this.streamToken=n,this.pr=i}static from(t,e,s,n){p(t.mutations.length===s.length,"Mutations sent "+t.mutations.length+" must equal results received "+s.length);let i=Ze();const r=t.mutations;for(let t=0;t<r.length;t++)i=i.wt(r[t].key,s[t].version);return new Bs(t,e,s,n,i)}}class qs{constructor(){this.gr=new yt(Os.ze),this.yr=new yt(Os.br)}tt(){return this.gr.tt()}vr(t,e){const s=new Os(t,e);this.gr=this.gr.add(s),this.yr=this.yr.add(s)}Sr(t,e){t.forEach(t=>this.vr(t,e))}Dr(t,e){this.Cr(new Os(t,e))}kr(t,e){t.forEach(t=>this.Dr(t,e))}Nr(t){const e=Pt.EMPTY,s=new Os(e,t),n=new Os(e,t+1),i=[];return this.yr.jt([s,n],t=>{this.Cr(t),i.push(t.key)}),i}Fr(){this.gr.forEach(t=>this.Cr(t))}Cr(t){this.gr=this.gr.delete(t),this.yr=this.yr.delete(t)}$r(t){const e=Pt.EMPTY,s=new Os(e,t),n=new Os(e,t+1);let i=es();return this.yr.jt([s,n],t=>{i=i.add(t.key)}),i}xr(t){const e=new Os(t,0),s=this.gr.Kt(e);return null!==s&&t.isEqual(s.key)}}class Os{constructor(t,e){this.key=t,this.Mr=e}static ze(t,e){return Pt.J(t.key,e.key)||y(t.Mr,e.Mr)}static br(t,e){return y(t.Mr,e.Mr)||Pt.J(t.key,e.key)}}class Us{constructor(t){this.Lr=null,this.Br=null,this.result=void 0,this.error=void 0,this.qr=!1,this.Or=!1,t(t=>{this.qr=!0,this.result=t,this.Lr&&this.Lr(t)},t=>{this.qr=!0,this.error=t,this.Br&&this.Br(t)})}catch(t){return this.next(void 0,t)}next(t,e){return this.Or&&V("Called next() or catch() twice for PersistencePromise"),this.Or=!0,this.qr?this.error?this.Ur(e,this.error):this.Qr(t,this.result):new Us((s,n)=>{this.Lr=e=>{this.Qr(t,e).next(s,n)},this.Br=t=>{this.Ur(e,t).next(s,n)}})}Wr(){return new Promise((t,e)=>{this.next(t,e)})}jr(t){try{const e=t();return e instanceof Us?e:Us.resolve(e)}catch(t){return Us.reject(t)}}Qr(t,e){return t?this.jr(()=>t(e)):Us.resolve(e)}Ur(t,e){return t?this.jr(()=>t(e)):Us.reject(e)}static resolve(t){return new Us((e,s)=>{e(t)})}static reject(t){return new Us((e,s)=>{s(t)})}static zr(t){return new Us((e,s)=>{let n=0,i=0,r=!1;t.forEach(t=>{++n,t.next(()=>{++i,r&&i===n&&e()},t=>s(t))}),r=!0,i===n&&e()})}static Kr(t){let e=Us.resolve(!1);for(const s of t)e=e.next(t=>t?Us.resolve(t):s());return e}static forEach(t,e){const s=[];return t.forEach((t,n)=>{s.push(e.call(this,t,n))}),this.zr(s)}}class Qs{constructor(){this.Gr=new xs(t=>t.toString()),this.Hr=!1}set readTime(t){p(void 0===this.Jr||this.Jr.isEqual(t),"All changes in a RemoteDocumentChangeBuffer must have the same read time"),this.Jr=t}get readTime(){return p(void 0!==this.Jr,"Read time is not set. All removeEntry() calls must include a readTime if `trackRemovals` is used."),this.Jr}Yr(t,e){this.Xr(),this.readTime=e,this.Gr.set(t.key,t)}Zr(t,e){this.Xr(),e&&(this.readTime=e),this.Gr.set(t,null)}to(t,e){this.Xr();const s=this.Gr.get(e);return void 0!==s?Us.resolve(s):this.eo(t,e)}getEntries(t,e){return this.so(t,e)}apply(t){return this.Xr(),this.Hr=!0,this.no(t)}Xr(){p(!this.Hr,"Changes have already been applied.")}}const Ws="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class js{constructor(){this.io=[]}ro(t){this.io.push(t)}oo(){this.io.forEach(t=>t())}}class zs{constructor(t,e,s){this.ho=t,this.ao=e,this.uo=s}co(t,e){return this.ao.lo(t,e).next(s=>this._o(t,e,s))}_o(t,e,s){return this.ho.to(t,e).next(t=>{for(const n of s)t=n.Jt(e,t);return t})}do(t,e,s){let n=He();return e.forEach((t,e)=>{for(const n of s)e=n.Jt(t,e);n=n.wt(t,e)}),n}fo(t,e){return this.ho.getEntries(t,e).next(e=>this.mo(t,e))}mo(t,e){return this.ao.To(t,e).next(s=>{const n=this.do(t,e,s);let i=Ge();return n.forEach((t,e)=>{e||(e=new de(t,Tt.j())),i=i.wt(t,e)}),i})}Eo(t,e,s){return e.Xe()?this.wo(t,e.path):e.vs()?this.Io(t,e,s):this.Ro(t,e,s)}wo(t,e){return this.co(t,new Pt(e)).next(t=>{let e=Ye();return t instanceof _e&&(e=e.wt(t.key,t)),e})}Io(t,e,s){p(e.path.tt(),"Currently we only support collection group queries at the root.");const n=e.collectionGroup;let i=Ye();return this.uo.Ao(t,n).next(r=>Us.forEach(r,r=>{const o=e.Es(r.child(n));return this.Ro(t,o,s).next(t=>{t.forEach((t,e)=>{i=i.wt(t,e)})})}).next(()=>i))}Ro(t,e,s){let n,i;return this.ho.Eo(t,e,s).next(s=>(n=s,this.ao.Po(t,e))).next(e=>(i=e,this.Vo(t,i,n).next(t=>{n=t;for(const t of i)for(const e of t.mutations){const s=e.key,i=n.get(s),r=e.Jt(i,i,t.Qe);n=r instanceof _e?n.wt(s,r):n.remove(s)}}))).next(()=>(n.forEach((t,s)=>{e.matches(s)||(n=n.remove(t))}),n))}Vo(t,e,s){let n=es();for(const t of e)for(const e of t.mutations)e instanceof jt&&null===s.get(e.key)&&(n=n.add(e.key));let i=s;return this.ho.getEntries(t,n).next(t=>(t.forEach((t,e)=>{null!==e&&e instanceof _e&&(i=i.wt(t,e))}),i))}}class Ks{constructor(t,e,s,n){this.targetId=t,this.fromCache=e,this.po=s,this.yo=n}static bo(t,e){let s=es(),n=es();for(const t of e.docChanges)switch(t.type){case rs.Qs:s=s.add(t.doc.key);break;case rs.Ws:n=n.add(t.doc.key)}return new Ks(t,e.fromCache,s,n)}}class Gs{constructor(t,e){this.previousValue=t,e&&(e.vo=t=>this.So(t),this.Do=t=>e.Co(t))}So(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue}next(){const t=++this.previousValue;return this.Do&&this.Do(t),t}}Gs.ko=-1;class Hs{constructor(){this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e})}}var Js,Ys;(Ys=Js||(Js={})).No="all",Ys.Fo="listen_stream_idle",Ys.$o="listen_stream_connection_backoff",Ys.xo="write_stream_idle",Ys.Mo="write_stream_connection_backoff",Ys.Lo="online_state_timeout",Ys.Bo="client_metadata_refresh",Ys.qo="lru_garbage_collection",Ys.Oo="retry_transaction";class Xs{constructor(t,e,s,n,i){this.Uo=t,this.Qo=e,this.Wo=s,this.op=n,this.jo=i,this.zo=new Hs,this.then=this.zo.promise.then.bind(this.zo.promise),this.catch=this.zo.promise.catch.bind(this.zo.promise),this.zo.promise.catch(t=>{})}static Ko(t,e,s,n,i){const r=Date.now()+s,o=new Xs(t,e,r,n,i);return o.start(s),o}start(t){this.Go=setTimeout(()=>this.Ho(),t)}Jo(){return this.Ho()}cancel(t){null!==this.Go&&(this.clearTimeout(),this.zo.reject(new L(M.CANCELLED,"Operation cancelled"+(t?": "+t:""))))}Ho(){this.Uo.Yo(()=>null!==this.Go?(this.clearTimeout(),this.op().then(t=>this.zo.resolve(t))):Promise.resolve())}clearTimeout(){null!==this.Go&&(this.jo(this),clearTimeout(this.Go),this.Go=null)}}class Zs{constructor(){this.Xo=Promise.resolve(),this.Zo=!1,this.th=[],this.eh=null,this.sh=!1,this.nh=[]}get ih(){return this.Zo}Yo(t){this.enqueue(t)}rh(t){this.oh(),this.hh(t)}ah(t){return this.oh(),this.hh(t)}async uh(t){this.oh(),this.Zo||(this.Zo=!0,await this.ah(t))}enqueue(t){return this.oh(),this.Zo?new Promise(t=>{}):this.hh(t)}hh(t){const e=this.Xo.then(()=>(this.sh=!0,t().catch(t=>{this.eh=t,this.sh=!1;const e=t.stack||t.message||"";throw A("INTERNAL UNHANDLED ERROR: ",e),e.indexOf("Firestore Test Simulated Error")<0&&setTimeout(()=>{throw t},0),t}).then(t=>(this.sh=!1,t))));return this.Xo=e,e}lh(t,e,s){this.oh(),p(e>=0,`Attempted to schedule an operation with a negative delay of ${e}`),this.nh.indexOf(t)>-1&&(e=0);const n=Xs.Ko(this,t,e,s,t=>this._h(t));return this.th.push(n),n}oh(){this.eh&&V("AsyncQueue is already failed: "+(this.eh.stack||this.eh.message))}dh(){p(this.sh,"verifyOpInProgress() called when no op in progress on this queue.")}fh(){return this.ah(()=>Promise.resolve())}mh(t){for(const e of this.th)if(e.Qo===t)return!0;return!1}Th(t){return this.fh().then(()=>{p(t===Js.No||this.mh(t),`Attempted to drain to missing operation ${t}`),this.th.sort((t,e)=>t.Wo-e.Wo);for(const e of this.th)if(e.Jo(),t!==Js.No&&e.Qo===t)break;return this.fh()})}Eh(t){this.nh.push(t)}_h(t){const e=this.th.indexOf(t);p(e>=0,"Delayed operation not found."),this.th.splice(e,1)}}function tn([t,e],[s,n]){const i=y(t,s);return 0===i?y(e,n):i}class en{constructor(t){this.wh=t,this.buffer=new yt(tn),this.Ih=0}Rh(){return++this.Ih}Ah(t){const e=[t,this.Rh()];if(this.buffer.size<this.wh)this.buffer=this.buffer.add(e);else{const t=this.buffer.last();tn(e,t)<0&&(this.buffer=this.buffer.delete(t).add(e))}}get maxValue(){return this.buffer.last()[0]}}const sn={Ph:!1,Vh:0,ph:0,gh:0};class nn{constructor(t,e,s){this.yh=t,this.bh=e,this.vh=s}static Sh(t){return new nn(t,nn.Dh,nn.Ch)}}nn.kh=-1,nn.Nh=1048576,nn.Fh=41943040,nn.Dh=10,nn.Ch=1e3,nn.$h=new nn(nn.Fh,nn.Dh,nn.Ch),nn.DISABLED=new nn(nn.kh,0,0);const rn=6e4,on=3e5;class hn{constructor(t,e,s){this.xh=t,this.Uo=e,this.Mh=s,this.Lh=!1,this.Bh=null}start(){p(null===this.Bh,"Cannot start an already started LruScheduler"),this.xh.qh.yh!==nn.kh&&this.Oh()}stop(){this.Bh&&(this.Bh.cancel(),this.Bh=null)}get Uh(){return null!==this.Bh}Oh(){p(null===this.Bh,"Cannot schedule GC while a task is pending");const t=this.Lh?on:rn;R("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.Bh=this.Uo.lh(Js.qo,t,()=>(this.Bh=null,this.Lh=!0,this.Mh.Qh(this.xh).then(()=>this.Oh()).catch(ln)))}}class an{constructor(t,e){this.Wh=t,this.qh=e}jh(t,e){return this.Wh.zh(t).next(t=>Math.floor(e/100*t))}Kh(t,e){if(0===e)return Us.resolve(Gs.ko);const s=new en(e);return this.Wh.Un(t,t=>s.Ah(t.sequenceNumber)).next(()=>this.Wh.Gh(t,t=>s.Ah(t))).next(()=>s.maxValue)}Hh(t,e,s){return this.Wh.Hh(t,e,s)}Jh(t,e){return this.Wh.Jh(t,e)}Yh(t,e){return this.qh.yh===nn.kh?(R("LruGarbageCollector","Garbage collection skipped; disabled"),Us.resolve(sn)):this.Xh(t).next(s=>s<this.qh.yh?(R("LruGarbageCollector",`Garbage collection skipped; Cache size ${s} `+`is lower than threshold ${this.qh.yh}`),sn):this.Zh(t,e))}Xh(t){return this.Wh.Xh(t)}Zh(t,e){let s,n,i,r,o,h,a;const u=Date.now();return this.jh(t,this.qh.bh).next(e=>(e>this.qh.vh?(R("LruGarbageCollector","Capping sequence numbers to collect down "+`to the maximum of ${this.qh.vh} `+`from ${e}`),n=this.qh.vh):n=e,r=Date.now(),this.Kh(t,n))).next(n=>(s=n,o=Date.now(),this.Hh(t,s,e))).next(e=>(i=e,h=Date.now(),this.Jh(t,s))).next(t=>{if(a=Date.now(),w()<=E.DEBUG){R("LruGarbageCollector","LRU Garbage Collection\n"+`\tCounted targets in ${r-u}ms\n`+`\tDetermined least recently used ${n} in `+`${o-r}ms\n`+`\tRemoved ${i} targets in `+`${h-o}ms\n`+`\tRemoved ${t} documents in `+`${a-h}ms\n`+`Total Duration: ${a-u}ms`)}return Us.resolve({Ph:!0,Vh:n,ph:i,gh:t})})}}const un="LocalStore";class cn{constructor(t,e,s){this.persistence=t,this.ta=e,this.ea=new qs,this.sa=new Vt(y),this.na=new xs(t=>t.canonicalId()),this.ia=Tt.MIN,p(t.Uh,"LocalStore was passed an unstarted persistence implementation"),this.persistence.oa.ra(this.ea),this.ao=t.ha(s),this.aa=t.ua(),this.ca=t.la(),this._a=new zs(this.aa,this.ao,this.persistence.da()),this.ta.fa(this._a)}start(){return this.ma()}async Ta(t){let e=this.ao,s=this._a;const n=await this.persistence.runTransaction("Handle user change","readonly-idempotent",n=>{let i;return this.ao.Ea(n).next(r=>(i=r,e=this.persistence.ha(t),s=new zs(this.aa,e,this.persistence.da()),e.Ea(n))).next(t=>{const e=[],r=[];let o=es();for(const t of i){e.push(t.batchId);for(const e of t.mutations)o=o.add(e.key)}for(const e of t){r.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return s.fo(n,o).next(t=>({wa:t,Ia:e,Ra:r}))})});return this.ao=e,this._a=s,this.ta.fa(this._a),n}Aa(t){const e=mt.now(),s=t.reduce((t,e)=>t.add(e.key),es());let n;return this.persistence.runTransaction("Locally write mutations","readwrite-idempotent",i=>this._a.fo(i,s).next(s=>{n=s;const r=[];for(const e of t){const t=e.fe(n.get(e.key));null!=t&&r.push(new jt(e.key,t,t.me(),Ut.exists(!0)))}return this.ao.Pa(i,e,r,t)})).then(t=>{const e=t.Pr(n);return{batchId:t.batchId,Gr:e}})}Va(t){return this.persistence.runTransaction("Lookup mutation documents","readonly-idempotent",e=>this.ao.pa(e,t).next(t=>t?this._a.fo(e,t):Us.resolve(null)))}ga(t){return this.persistence.runTransaction("Acknowledge batch","readwrite-primary-idempotent",e=>{const s=t.batch.keys(),n=this.aa.ya({ba:!0});return this.ao.ga(e,t.batch,t.streamToken).next(()=>this.va(e,t,n)).next(()=>n.apply(e)).next(()=>this.ao.Sa(e)).next(()=>this._a.fo(e,s))})}Da(t){return this.persistence.runTransaction("Reject batch","readwrite-primary-idempotent",e=>{let s;return this.ao.Ca(e,t).next(t=>(p(null!==t,"Attempt to reject nonexistent batch!"),s=t.keys(),this.ao.ka(e,t))).next(()=>this.ao.Sa(e)).next(()=>this._a.fo(e,s))})}Na(){return this.persistence.runTransaction("Get highest unacknowledged batch id","readonly-idempotent",t=>this.ao.Na(t))}Fa(){return this.persistence.runTransaction("Get last stream token","readonly-idempotent",t=>this.ao.Fa(t))}$a(t){return this.persistence.runTransaction("Set last stream token","readwrite-primary-idempotent",e=>this.ao.$a(e,t))}xa(){return this.persistence.runTransaction("Get last remote snapshot version","readonly-idempotent",t=>this.ca.xa(t))}Ma(t){const e=t.xs;let s=this.sa;return this.persistence.runTransaction("Apply remote event","readwrite-primary-idempotent",n=>{const i=this.aa.ya({ba:!0});s=this.sa;const r=[];z(t.sn,(t,i)=>{const o=s.get(t);if(!o)return;r.push(this.ca.La(n,i.ln,t).next(()=>this.ca.Ba(n,i.un,t)));const h=i.resumeToken;if(h.length>0){const a=o.Ls(h,e).Ms(n.qa);s=s.wt(t,a),cn.Oa(o,a,i)&&r.push(this.ca.Ua(n,a))}});let o=Ge(),h=es();if(t.in.forEach((t,e)=>{h=h.add(t)}),r.push(i.getEntries(n,h).next(s=>{t.in.forEach((h,a)=>{const u=s.get(h);a instanceof de&&a.version.isEqual(Tt.MIN)?(i.Zr(h,e),o=o.wt(h,a)):null==u||a.version.u(u.version)>0||0===a.version.u(u.version)&&u.hasPendingWrites?(p(!Tt.MIN.isEqual(e),"Cannot add a document when the remote version is zero"),i.Yr(a,e),o=o.wt(h,a)):R(un,"Ignoring outdated watch update for ",h,". Current version:",u.version," Watch version:",a.version),t.rn.has(h)&&r.push(this.persistence.oa.Qa(n,h))})})),!e.isEqual(Tt.MIN)){const t=this.ca.xa(n).next(t=>(p(e.u(t)>=0,"Watch stream reverted to previous snapshot?? "+e+" < "+t),this.ca.Wa(n,n.qa,e)));r.push(t)}return Us.zr(r).next(()=>i.apply(n)).next(()=>this._a.mo(n,o))}).then(t=>(this.sa=s,t))}static Oa(t,e,s){if(p(e.resumeToken.length>0,"Attempted to persist target data with no resume token"),0===t.resumeToken.length)return!0;return e.xs.K()-t.xs.K()>=this.ja||s.un.size+s.cn.size+s.ln.size>0}za(t){for(const e of t){const t=e.targetId;if(this.ea.Sr(e.po,t),this.ea.kr(e.yo,t),!e.fromCache){const e=this.sa.get(t);p(null!==e,`Can't set limbo-free snapshot version for unknown target: ${t}`);const s=e.xs,n=e.Bs(s);this.sa=this.sa.wt(t,n)}}return this.persistence.runTransaction("notifyLocalViewChanges","readwrite-idempotent",e=>Us.forEach(t,t=>Us.forEach(t.yo,t=>this.persistence.oa.Dr(e,t))))}Ka(t){return this.persistence.runTransaction("Get next mutation batch","readonly-idempotent",e=>(void 0===t&&(t=Ms),this.ao.Ga(e,t)))}Ha(t){return this.persistence.runTransaction("read document","readonly-idempotent",e=>this._a.co(e,t))}Ja(t){return this.persistence.runTransaction("Allocate target","readwrite-idempotent",e=>{let s;return this.ca.Ya(e,t).next(n=>n?(s=n,Us.resolve(s)):this.ca.Xa(e).next(n=>(s=new Ue(t,n,Le.ks,e.qa),this.ca.Za(e,s).next(()=>s))))}).then(e=>(null===this.sa.get(e.targetId)&&(this.sa=this.sa.wt(e.targetId,e),this.na.set(t,e.targetId)),e))}Ya(t,e){const s=this.na.get(e);return void 0!==s?Us.resolve(this.sa.get(s)):this.ca.Ya(t,e)}tu(t,e){const s=this.sa.get(t);p(null!==s,`Tried to release nonexistent target: ${t}`);const n=e?"readwrite-idempotent":"readwrite-primary-idempotent";return this.persistence.runTransaction("Release target",n,n=>{const i=this.ea.Nr(t);return e?Us.resolve():Us.forEach(i,t=>this.persistence.oa.Dr(n,t)).next(()=>{this.persistence.oa.removeTarget(n,s)})}).then(()=>{this.sa=this.sa.remove(t),this.na.delete(s.target)})}eu(t,e){let s=Tt.MIN,n=es();return this.persistence.runTransaction("Execute query","readonly-idempotent",i=>this.Ya(i,t.Is()).next(t=>{if(t)return s=t.lastLimboFreeSnapshotVersion,this.ca.su(i,t.targetId).next(t=>{n=t})}).next(()=>this.ta.Eo(i,t,e?s:Tt.MIN,e?n:es())).next(t=>({documents:t,nu:n})))}iu(t){return this.persistence.runTransaction("Remote document keys","readonly-idempotent",e=>this.ca.su(e,t))}ru(){return this.persistence.ru()}ou(t){this.ao.hu(t)}au(t){this.persistence.au(t)}va(t,e,s){const n=e.batch,i=n.keys();let r=Us.resolve();return i.forEach(i=>{r=r.next(()=>s.to(t,i)).next(t=>{let r=t;const o=e.pr.get(i);p(null!==o,"ackVersions should contain every doc in the write."),(!r||r.version.u(o)<0)&&((r=n.Yt(i,r,e))?s.Yr(r,e.Vr):p(!t,"Mutation batch "+n+" applied to document "+t+" resulted in null"))})}),r.next(()=>this.ao.ka(t,n))}Qh(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary-idempotent",e=>t.Yh(e,this.sa))}uu(t){const e=this.sa.get(t);return e?Promise.resolve(e.target):this.persistence.runTransaction("Get target data","readonly-idempotent",e=>this.ca.Zn(e,t).next(t=>t?t.target:null))}cu(){return this.persistence.runTransaction("Get new document changes","readonly-idempotent",t=>this.aa.cu(t,this.ia)).then(({lu:t,readTime:e})=>(this.ia=e,t))}async ma(){this.ia=await this.persistence.runTransaction("Synchronize last document change read time","readonly-idempotent",t=>this.aa._u(t))}}async function ln(t){if(t.code!==M.FAILED_PRECONDITION||t.message!==Ws)throw t;R(un,"Unexpectedly lost primary lease")}cn.ja=3e8;class _n{constructor(...t){!function(t,e,s,n){if(!(e instanceof Array)||e.length<n)throw new L(M.INVALID_ARGUMENT,`Function ${t}() requires its ${s} argument to be an `+"array with at least "+`${dt(n,"element")}.`)}("FieldPath",t,"fieldNames",1);for(let e=0;e<t.length;++e)if(Z("FieldPath","string",e,t[e]),0===t[e].length)throw new L(M.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this.du=new At(t)}static documentId(){return _n.fu}isEqual(t){if(!(t instanceof _n))throw ct("isEqual","FieldPath",1,t);return this.du.isEqual(t.du)}}_n.fu=new _n(At.lt().ot());const dn=new RegExp("[~\\*/\\[\\]]");class fn{constructor(t){this.mu=t}static delete(){return H("FieldValue.delete",arguments),mn.instance}static serverTimestamp(){return H("FieldValue.serverTimestamp",arguments),Tn.instance}static arrayUnion(...t){return Y("FieldValue.arrayUnion",arguments,1),new En(t)}static arrayRemove(...t){return Y("FieldValue.arrayRemove",arguments,1),new wn(t)}static increment(t){return Z("FieldValue.increment","number",1,t),J("FieldValue.increment",arguments,1),new In(t)}isEqual(t){return this===t}}class mn extends fn{constructor(){super("FieldValue.delete")}}mn.instance=new mn;class Tn extends fn{constructor(){super("FieldValue.serverTimestamp")}}Tn.instance=new Tn;class En extends fn{constructor(t){super("FieldValue.arrayUnion"),this.Tu=t}}class wn extends fn{constructor(t){super("FieldValue.arrayRemove"),this.Tu=t}}class In extends fn{constructor(t){super("FieldValue.increment"),this.Eu=t}}const Rn=Cs(fn,"Use FieldValue.<field>() instead."),An=/^__.*__$/;class Pn{constructor(t,e,s){this.data=t,this.me=e,this.fieldTransforms=s}wu(t,e){const s=[];return null!==this.me?s.push(new jt(t,this.data,this.me,e)):s.push(new Wt(t,this.data,e)),this.fieldTransforms.length>0&&s.push(new zt(t,this.fieldTransforms)),s}}class Vn{constructor(t,e,s){this.data=t,this.me=e,this.fieldTransforms=s}wu(t,e){const s=[new jt(t,this.data,this.me,e)];return this.fieldTransforms.length>0&&s.push(new zt(t,this.fieldTransforms)),s}}var pn,gn;function yn(t){switch(t){case pn.Set:case pn.Iu:case pn.Ru:return!0;case pn.Au:case pn.Pu:return!1;default:throw V(`Unexpected case for UserDataSource: ${t}`)}}(gn=pn||(pn={}))[gn.Set=0]="Set",gn[gn.Ru=1]="__PRIVATE_Update",gn[gn.Iu=2]="__PRIVATE_MergeSet",gn[gn.Au=3]="__PRIVATE_Argument",gn[gn.Pu=4]="__PRIVATE_ArrayArgument";class bn{constructor(t,e,s,n,i,r){this.Vu=t,this.methodName=e,this.path=s,this.pu=n,void 0===i&&this.gu(),this.pu=void 0!==n&&n,this.fieldTransforms=i||[],this.me=r||[]}yu(t){const e=null==this.path?null:this.path.child(t),s=new bn(this.Vu,this.methodName,e,!1,this.fieldTransforms,this.me);return s.bu(t),s}vu(t){const e=null==this.path?null:this.path.child(t),s=new bn(this.Vu,this.methodName,e,!1,this.fieldTransforms,this.me);return s.gu(),s}Su(t){return new bn(this.Vu,this.methodName,null,!0,this.fieldTransforms,this.me)}Du(t){const e=null===this.path||this.path.tt()?"":` (found in field ${this.path.toString()})`;return new L(M.INVALID_ARGUMENT,`Function ${this.methodName}() called with invalid data. `+t+e)}contains(t){return void 0!==this.me.find(e=>t.nt(e))||void 0!==this.fieldTransforms.find(e=>t.nt(e.field))}gu(){if(null!==this.path)for(let t=0;t<this.path.length;t++)this.bu(this.path.get(t))}bu(t){if(0===t.length)throw this.Du("Document fields must not be empty");if(yn(this.Vu)&&An.test(t))throw this.Du('Document fields cannot begin and end with "__"')}}class vn{constructor(t,e){this.o=t,this.key=e}}class Sn{constructor(t){this.Cu=t}ku(t,e){const s=new bn(pn.Set,t,At.at);Cn("Data must be an object, but it was:",s,e);const n=this.Nu(e,s);return new Pn(n,null,s.fieldTransforms)}Fu(t,e,s){const n=new bn(pn.Iu,t,At.at);Cn("Data must be an object, but it was:",n,e);const i=this.Nu(e,n);let r,o;if(s){let e=new yt(At.J);for(const i of s){let s;if(i instanceof _n)s=i.du;else{if("string"!=typeof i)throw V("Expected stringOrFieldPath to be a string or a FieldPath");s=Nn(t,i)}if(!n.contains(s))throw new L(M.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);e=e.add(s)}r=Nt.ee(e),o=n.fieldTransforms.filter(t=>r.ne(t.field))}else r=Nt.se(n.me),o=n.fieldTransforms;return new Pn(i,r,o)}$u(t,e){const s=new bn(pn.Ru,t,At.at);Cn("Data must be an object, but it was:",s,e);let n=new yt(At.J),i=ue.EMPTY;K(e,(e,r)=>{const o=Nn(t,e),h=s.vu(o);if((r=this.xu(r,h))instanceof mn)n=n.add(o);else{const t=this.Nu(r,h);null!=t&&(n=n.add(o),i=i.set(o,t))}});const r=Nt.ee(n);return new Vn(i,r,s.fieldTransforms)}Mu(t,e,s,n){const i=new bn(pn.Ru,t,At.at),r=[kn(t,e)],o=[s];if(n.length%2!=0)throw new L(M.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number `+"of arguments that alternate between field names and values.");for(let e=0;e<n.length;e+=2)r.push(kn(t,n[e])),o.push(n[e+1]);let h=new yt(At.J),a=ue.EMPTY;for(let t=0;t<r.length;++t){const e=r[t],s=i.vu(e),n=this.xu(o[t],s);if(n instanceof mn)h=h.add(e);else{const t=this.Nu(n,s);null!=t&&(h=h.add(e),a=a.set(e,t))}}const u=Nt.ee(h);return new Vn(a,u,i.fieldTransforms)}Lu(t,e,s=!1){const n=new bn(s?pn.Pu:pn.Au,t,At.at),i=this.Nu(e,n);return p(null!=i,"Parsed data should not be null."),p(0===n.fieldTransforms.length,"Field transforms should have been disallowed."),i}xu(t,e){try{return this.Cu(t)}catch(t){const s=Fn(t);throw e.Du(s)}}Nu(t,e){if(Dn(t=this.xu(t,e)))return Cn("Unsupported field value:",e,t),this.Bu(t,e);if(t instanceof fn)return this.qu(t,e),null;if(e.path&&e.me.push(e.path),t instanceof Array){if(e.pu&&e.Vu!==pn.Pu)throw e.Du("Nested arrays are not supported");return this.Ou(t,e)}return this.Uu(t,e)}Bu(t,e){let s=new Vt(y);return G(t)?e.path&&e.path.length>0&&e.me.push(e.path):K(t,(t,n)=>{const i=this.Nu(n,e.yu(t));null!=i&&(s=s.wt(t,i))}),new ue(s)}Ou(t,e){const s=[];let n=0;for(const i of t){let t=this.Nu(i,e.Su(n));null==t&&(t=Yt.Be),s.push(t),n++}return new ce(s)}qu(t,e){if(!yn(e.Vu))throw e.Du(`${t.mu}() can only be used with update() and set()`);if(null===e.path)throw e.Du(`${t.mu}() is not currently supported inside arrays`);if(t instanceof mn){if(e.Vu!==pn.Iu)throw e.Vu===pn.Ru?(p(e.path.length>0,"FieldValue.delete() at the top level should have already been handled."),e.Du("FieldValue.delete() can only appear at the top level of your update data")):e.Du("FieldValue.delete() cannot be used with set() unless you pass {merge:true}");e.me.push(e.path)}else if(t instanceof Tn)e.fieldTransforms.push(new Ft(e.path,vt.instance));else if(t instanceof En){const s=this.Qu(t.mu,t.Tu),n=new St(s);e.fieldTransforms.push(new Ft(e.path,n))}else if(t instanceof wn){const s=this.Qu(t.mu,t.Tu),n=new Dt(s);e.fieldTransforms.push(new Ft(e.path,n))}else if(t instanceof In){const s=this.Lu("FieldValue.increment",t.Eu),n=new Ct(s);e.fieldTransforms.push(new Ft(e.path,n))}else V("Unknown FieldValue type: "+t)}Uu(t,e){if(null===t)return Yt.Be;if("number"==typeof t)return Re(t)?new ee(t):new se(t);if("boolean"==typeof t)return Xt.of(t);if("string"==typeof t)return new ne(t);if(t instanceof Date)return new ie(mt.fromDate(t));if(t instanceof mt)return new ie(new mt(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)));if(t instanceof ft)return new ae(t);if(t instanceof Fs)return new oe(t);if(t instanceof vn)return new he(t.o,t.key);throw e.Du(`Unsupported field value: ${ht(t)}`)}Qu(t,e){return e.map((e,s)=>{const n=new bn(pn.Au,t,At.at);return this.Nu(e,n.Su(s))})}}function Dn(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof mt||t instanceof ft||t instanceof Fs||t instanceof vn||t instanceof fn)}function Cn(t,e,s){if(!Dn(s)||!ot(s)){const n=ht(s);throw"an object"===n?e.Du(t+" a custom object"):e.Du(t+" "+n)}}function kn(t,e){if(e instanceof _n)return e.du;if("string"==typeof e)return Nn(t,e);{const e="Field path arguments must be of type string or FieldPath.";throw new L(M.INVALID_ARGUMENT,`Function ${t}() called with invalid data. ${e}`)}}function Nn(t,e){try{return function(t){if(t.search(dn)>=0)throw new L(M.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not contain `+"'~', '*', '/', '[', or ']'");try{return new _n(...t.split("."))}catch(e){throw new L(M.INVALID_ARGUMENT,`Invalid field path (${t}). Paths must not be empty, `+"begin with '.', end with '.', or contain '..'")}}(e).du}catch(e){const s=Fn(e);throw new L(M.INVALID_ARGUMENT,`Function ${t}() called with invalid data. ${s}`)}}function Fn(t){return t instanceof Error?t.message:t.toString()}const $n="ExponentialBackoff",xn=1e3,Mn=1.5,Ln=6e4;class Bn{constructor(t,e,s=xn,n=Mn,i=Ln){this.Wu=t,this.Qo=e,this.ju=s,this.zu=n,this.Ku=i,this.Gu=0,this.Hu=null,this.Ju=Date.now(),this.reset()}reset(){this.Gu=0}Yu(){this.Gu=this.Ku}Xu(t){this.cancel();const e=Math.floor(this.Gu+this.Zu()),s=Math.max(0,Date.now()-this.Ju),n=Math.max(0,e-s);this.Gu>0&&R($n,`Backing off for ${n} ms `+`(base delay: ${this.Gu} ms, `+`delay with jitter: ${e} ms, `+`last attempt: ${s} ms ago)`),this.Hu=this.Wu.lh(this.Qo,n,()=>(this.Ju=Date.now(),t())),this.Gu*=this.zu,this.Gu<this.ju&&(this.Gu=this.ju),this.Gu>this.Ku&&(this.Gu=this.Ku)}cancel(){null!==this.Hu&&(this.Hu.cancel(),this.Hu=null)}Zu(){return(Math.random()-.5)*this.Gu}}const qn="PersistentStream";var On,Un;(Un=On||(On={}))[Un.tc=0]="__PRIVATE_Initial",Un[Un.ec=1]="__PRIVATE_Starting",Un[Un.sc=2]="__PRIVATE_Open",Un[Un.Error=3]="Error",Un[Un.nc=4]="__PRIVATE_Backoff";const Qn=6e4;class Wn{constructor(t,e,s,n,i,r){this.Wu=t,this.ic=s,this.rc=n,this.oc=i,this.listener=r,this.state=On.tc,this.hc=0,this.ac=null,this.stream=null,this.uc=new Bn(t,e)}cc(){return this.state===On.ec||this.state===On.sc||this.state===On.nc}lc(){return this.state===On.sc}start(){this.state!==On.Error?(p(this.state===On.tc,"Already started"),this.auth()):this._c()}async stop(){this.cc()&&await this.close(On.tc)}dc(){p(!this.cc(),"Can only inhibit backoff in a stopped state"),this.state=On.tc,this.uc.reset()}fc(){this.lc()&&null===this.ac&&(this.ac=this.Wu.lh(this.ic,Qn,()=>this.mc()))}Tc(t){this.Ec(),this.stream.send(t)}async mc(){if(this.lc())return this.close(On.tc)}Ec(){this.ac&&(this.ac.cancel(),this.ac=null)}async close(t,e){p(this.cc(),"Only started streams should be closed."),p(t===On.Error||Ie(e),"Can't provide an error when not in an error state."),this.Ec(),this.uc.cancel(),this.hc++,t!==On.Error?this.uc.reset():e&&e.code===M.RESOURCE_EXHAUSTED?(A(e.toString()),A("Using maximum backoff delay to prevent overloading the backend."),this.uc.Yu()):e&&e.code===M.UNAUTHENTICATED&&this.oc.v(),null!==this.stream&&(this.wc(),this.stream.close(),this.stream=null),this.state=t,await this.listener.Ic(e)}wc(){}auth(){p(this.state===On.tc,"Must be in initial state to auth"),this.state=On.ec;const t=this.Rc(this.hc),e=this.hc;this.oc.getToken().then(t=>{this.hc===e&&this.Ac(t)},e=>{t(()=>{const t=new L(M.UNKNOWN,"Fetching auth token failed: "+e.message);return this.Pc(t)})})}Ac(t){p(this.state===On.ec,"Trying to start stream in a non-starting state");const e=this.Rc(this.hc);this.stream=this.Vc(t),this.stream.pc(()=>{e(()=>(p(this.state===On.ec,"Expected stream to be in state Starting, but was "+this.state),this.state=On.sc,this.listener.pc()))}),this.stream.Ic(t=>{e(()=>this.Pc(t))}),this.stream.onMessage(t=>{e(()=>this.onMessage(t))})}_c(){p(this.state===On.Error,"Should only perform backoff when in Error state"),this.state=On.nc,this.uc.Xu(async()=>{p(this.state===On.nc,"Backoff elapsed but state is now: "+this.state),this.state=On.tc,this.start(),p(this.cc(),"PersistentStream should have started")})}Pc(t){return p(this.cc(),"Can't handle server close on non-started stream"),R(qn,`close with error: ${t}`),this.stream=null,this.close(On.Error,t)}Rc(t){return e=>{this.Wu.Yo(()=>this.hc===t?e():(R(qn,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class jn extends Wn{constructor(t,e,s,n,i){super(t,Js.$o,Js.Fo,e,s,i),this.serializer=n}Vc(t){return this.rc.gc("Listen",t)}onMessage(t){this.uc.reset();const e=this.serializer.Ni(t),s=this.serializer.$i(t);return this.listener.yc(e,s)}bc(t){const e={};e.database=this.serializer.wi,e.addTarget=this.serializer.Is(t);const s=this.serializer.sr(t);s&&(e.labels=s),this.Tc(e)}vc(t){const e={};e.database=this.serializer.wi,e.removeTarget=t,this.Tc(e)}}class zn extends Wn{constructor(t,e,s,n,i){super(t,Js.Mo,Js.xo,e,s,i),this.serializer=n,this.Sc=!1,this.lastStreamToken=Ds()}get Dc(){return this.Sc}start(){this.Sc=!1,super.start()}wc(){this.Sc&&this.Cc([])}Vc(t){return this.rc.gc("Write",t)}onMessage(t){if(p(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.Sc){this.uc.reset();const e=this.serializer.ji(t.writeResults,t.commitTime),s=this.serializer.fromVersion(t.commitTime);return this.listener.kc(s,e)}return p(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.Sc=!0,this.listener.Nc()}Fc(){p(this.lc(),"Writing handshake requires an opened stream"),p(!this.Sc,"Handshake already completed");const t={};t.database=this.serializer.wi,this.Tc(t)}Cc(t){p(this.lc(),"Writing mutations requires an opened stream"),p(this.Sc,"Handshake must be complete before writing mutations"),p(this.lastStreamToken.length>0,"Trying to write mutation without a token");const e={streamToken:this.lastStreamToken,writes:t.map(t=>this.serializer.xi(t))};this.Tc(e)}}class Kn{constructor(t,e,s,n){this.Wu=t,this.rc=e,this.credentials=s,this.serializer=n}$c(t){return new zn(this.Wu,this.rc,this.credentials,this.serializer,t)}xc(t){return new jn(this.Wu,this.rc,this.credentials,this.serializer,t)}commit(t){const e={database:this.serializer.wi,writes:t.map(t=>this.serializer.xi(t))};return this.Mc("Commit",e).then(t=>this.serializer.ji(t.writeResults,t.commitTime))}Lc(t){const e={database:this.serializer.wi,documents:t.map(t=>this.serializer.di(t))};return this.Bc("BatchGetDocuments",e).then(e=>{let s=Ge();e.forEach(t=>{const e=this.serializer.Di(t);s=s.wt(e.key,e)});const n=[];return t.forEach(t=>{const e=s.get(t);p(!!e,"Missing entity in write response for "+t),n.push(e)}),n})}Mc(t,e){return this.credentials.getToken().then(s=>this.rc.Mc(t,e,s)).catch(t=>{throw t.code===M.UNAUTHENTICATED&&this.credentials.v(),t})}Bc(t,e){return this.credentials.getToken().then(s=>this.rc.Bc(t,e,s)).catch(t=>{throw t.code===M.UNAUTHENTICATED&&this.credentials.v(),t})}}class Gn{constructor(t){this.qc=t,this.Oc=Ze(),this.mutations=[],this.Uc=!1,this.Qc=null,this.Wc=new Set}async Lc(t){if(this.jc(),this.mutations.length>0)throw new L(M.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const e=await this.qc.Lc(t);return e.forEach(t=>{t instanceof de||t instanceof _e?this.zc(t):V("Document in a transaction was a "+t.constructor.name)}),e}set(t,e){this.write(e.wu(t,this._e(t))),this.Wc.add(t)}update(t,e){try{this.write(e.wu(t,this.Kc(t)))}catch(t){this.Qc=t}this.Wc.add(t)}delete(t){this.write([new Kt(t,this._e(t))]),this.Wc.add(t)}async commit(){if(this.jc(),this.Qc)throw this.Qc;let t=this.Oc;this.mutations.forEach(e=>{t=t.remove(e.key)}),t.forEach((t,e)=>{this.mutations.push(new Gt(t,this._e(t)))}),await this.qc.commit(this.mutations),this.Uc=!0}zc(t){let e;if(t instanceof _e)e=t.version;else{if(!(t instanceof de))throw V("Document in a transaction was a "+t.constructor.name);e=Tt.j()}const s=this.Oc.get(t.key);if(null!==s){if(!e.isEqual(s))throw new L(M.ABORTED,"Document version changed between two reads.")}else this.Oc=this.Oc.wt(t.key,e)}_e(t){const e=this.Oc.get(t);return!this.Wc.has(t)&&e?Ut.updateTime(e):Ut.NONE}Kc(t){const e=this.Oc.get(t);if(!this.Wc.has(t)&&e){if(e.isEqual(Tt.j()))throw new L(M.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Ut.updateTime(e)}return Ut.exists(!0)}write(t){this.jc(),this.mutations=this.mutations.concat(t)}jc(){p(!this.Uc,"A transaction object cannot be used after its update callback has been invoked.")}}const Hn="OnlineStateTracker",Jn=1,Yn=1e4;class Xn{constructor(t,e){this.Uo=t,this.Gc=e,this.state=k.l,this.Hc=0,this.Jc=null,this.Yc=!0}Xc(){0===this.Hc&&(this.Zc(k.l),p(null===this.Jc,"onlineStateTimer shouldn't be started yet"),this.Jc=this.Uo.lh(Js.Lo,Yn,()=>(this.Jc=null,p(this.state===k.l,"Timer should be canceled if we transitioned to a different state."),this.tl(`Backend didn't respond within ${Yn/1e3} `+"seconds."),this.Zc(k.m),Promise.resolve())))}el(t){this.state===k._?(this.Zc(k.l),p(0===this.Hc,"watchStreamFailures must be 0"),p(null===this.Jc,"onlineStateTimer must be null")):(this.Hc++,this.Hc>=Jn&&(this.sl(),this.tl(`Connection failed ${Jn} `+`times. Most recent error: ${t.toString()}`),this.Zc(k.m)))}set(t){this.sl(),this.Hc=0,t===k._&&(this.Yc=!1),this.Zc(t)}Zc(t){t!==this.state&&(this.state=t,this.Gc(t))}tl(t){const e=`Could not reach Cloud Firestore backend. ${t}\n`+"This 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.Yc?(A(e),this.Yc=!1):R(Hn,e)}sl(){null!==this.Jc&&(this.Jc.cancel(),this.Jc=null)}}const Zn="RemoteStore",ti=10;class ei{constructor(t,e,s,n,i){this.Mh=t,this.qc=e,this.nl=[],this.il={},this.rl=null,this.networkEnabled=!1,this.isPrimary=!1,this.ol=i,this.ol.hl(t=>{s.Yo(async()=>{this.al()&&(R(Zn,"Restarting streams for network reachability change."),await this.ul())})}),this.cl=new Xn(s,n),this.ll=this.qc.xc({pc:this._l.bind(this),Ic:this.dl.bind(this),yc:this.fl.bind(this)}),this.ml=this.qc.$c({pc:this.Tl.bind(this),Ic:this.El.bind(this),Nc:this.wl.bind(this),kc:this.kc.bind(this)})}start(){return this.enableNetwork()}async enableNetwork(){this.networkEnabled=!0,this.al()&&(this.ml.lastStreamToken=await this.Mh.Fa(),this.Il()?this.Rl():this.cl.set(k.l),await this.Al())}async disableNetwork(){this.networkEnabled=!1,await this.Pl(),this.cl.set(k.m)}async Pl(){await this.ml.stop(),await this.ll.stop(),this.nl.length>0&&(R(Zn,`Stopping write stream with ${this.nl.length} pending writes`),this.nl=[]),this.Vl()}async pl(){R(Zn,"RemoteStore shutting down."),this.networkEnabled=!1,await this.Pl(),this.ol.pl(),this.cl.set(k.l)}listen(t){W(this.il,t.targetId)||(this.il[t.targetId]=t,this.Il()?this.Rl():this.ll.lc()&&this.gl(t))}yl(t){p(W(this.il,t),`unlisten called on target no currently watched: ${t}`),delete this.il[t],this.ll.lc()&&this.bl(t),G(this.il)&&(this.ll.lc()?this.ll.fc():this.al()&&this.cl.set(k.l))}Zn(t){return this.il[t]||null}Xn(t){return this.vl.Xn(t)}gl(t){this.rl.Dn(t.targetId),this.ll.bc(t)}bl(t){this.rl.Dn(t),this.ll.vc(t)}Rl(){p(this.Il(),"startWatchStream() called when shouldStartWatchStream() is false."),this.rl=new Rs(this),this.ll.start(),this.cl.Xc()}Il(){return this.al()&&!this.ll.cc()&&!G(this.il)}al(){return this.isPrimary&&this.networkEnabled}Vl(){this.rl=null}async _l(){z(this.il,(t,e)=>{this.gl(e)})}async dl(t){void 0===t&&p(!this.Il(),"Watch stream was stopped gracefully while still needed."),this.Vl(),this.Il()?(this.cl.el(t),this.Rl()):this.cl.set(k.l)}async fl(t,e){if(this.cl.set(k._),t instanceof Es&&t.state===us.Ws&&t.cause)return this.Sl(t);if(t instanceof ms?this.rl.Ln(t):t instanceof Ts?this.rl.zn(t):(p(t instanceof Es,"Expected watchChange to be an instance of WatchTargetChange"),this.rl.On(t)),!e.isEqual(Tt.MIN)){const t=await this.Mh.xa();e.u(t)>=0&&await this.Dl(e)}}Dl(t){p(!t.isEqual(Tt.MIN),"Can't raise event for unknown SnapshotVersion");const e=this.rl.Hn(t);return z(e.sn,(e,s)=>{if(s.resumeToken.length>0){const n=this.il[e];n&&(this.il[e]=n.Ls(s.resumeToken,t))}}),e.nn.forEach(t=>{const e=this.il[t];if(!e)return;this.il[t]=e.Ls(Ds(),e.xs),this.bl(t);const s=new Ue(e.target,t,Le.Ns,e.sequenceNumber);this.gl(s)}),this.vl.Ma(e)}Sl(t){p(!!t.cause,"Handling target error without a cause");const e=t.cause;let s=Promise.resolve();return t.targetIds.forEach(t=>{s=s.then(async()=>{if(W(this.il,t))return delete this.il[t],this.rl.removeTarget(t),this.vl.Cl(t,e)})}),s}async Al(){if(this.kl()){const t=this.nl.length>0?this.nl[this.nl.length-1].batchId:Ms,e=await this.Mh.Ka(t);null===e?0===this.nl.length&&this.ml.fc():(this.Nl(e),await this.Al())}this.Fl()&&this.$l()}kl(){return this.al()&&this.nl.length<ti}xl(){return this.nl.length}Nl(t){p(this.kl(),"addToWritePipeline called when pipeline is full"),this.nl.push(t),this.ml.lc()&&this.ml.Dc&&this.ml.Cc(t.mutations)}Fl(){return this.al()&&!this.ml.cc()&&this.nl.length>0}$l(){p(this.Fl(),"startWriteStream() called when shouldStartWriteStream() is false."),this.ml.start()}async Tl(){this.ml.Fc()}wl(){return this.Mh.$a(this.ml.lastStreamToken).then(()=>{for(const t of this.nl)this.ml.Cc(t.mutations)}).catch(ln)}kc(t,e){p(this.nl.length>0,"Got result for empty write pipeline");const s=this.nl.shift(),n=Bs.from(s,t,e,this.ml.lastStreamToken);return this.vl.Ml(n).then(()=>this.Al())}async El(t){if(void 0===t&&p(!this.Fl(),"Write stream was stopped gracefully while still needed."),t&&this.nl.length>0){let e;return(e=this.ml.Dc?this.Ll(t):this.Bl(t)).then(()=>{this.Fl()&&this.$l()})}}async Bl(t){if(We(t.code))return R(Zn,"RemoteStore error before completed handshake; resetting stream token: ",this.ml.lastStreamToken),this.ml.lastStreamToken=Ds(),this.Mh.$a(Ds()).catch(ln)}async Ll(t){if(We(e=t.code)&&e!==M.ABORTED){const e=this.nl.shift();return this.ml.dc(),this.vl.ql(e.batchId,t).then(()=>this.Al())}var e}Ol(){return new Gn(this.qc)}async ul(){this.networkEnabled=!1,await this.Pl(),this.cl.set(k.l),await this.enableNetwork()}async Ul(){this.al()&&(R(Zn,"RemoteStore restarting streams for new credential"),await this.ul())}async Ql(t){this.isPrimary=t,t&&this.networkEnabled?await this.enableNetwork():t||(await this.Pl(),this.cl.set(k.l))}}const si="firestore_clients";function ni(t,e){return p(-1===e.indexOf("_"),`Client key cannot contain '_', but was '${e}'`),`${si}_${t}_${e}`}const ii="firestore_mutations";function ri(t,e,s){let n=`${ii}_${t}_${s}`;return e.R()&&(n+=`_${e.uid}`),n}const oi="firestore_targets";function hi(t,e){return`${oi}_${t}_${e}`}const ai="firestore_online_state";const ui="firestore_sequence_number";const ci="SharedClientState";class li{constructor(t,e,s,n){this.user=t,this.batchId=e,this.state=s,this.error=n,p(void 0!==n==("rejected"===s),"MutationMetadata must contain an error iff state is 'rejected'")}static Wl(t,e,s){const n=JSON.parse(s);let i="object"==typeof n&&-1!==["pending","acknowledged","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error),r=void 0;return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(r=new L(n.error.code,n.error.message)),i?new li(t,e,n.state,r):(A(ci,`Failed to parse mutation state for ID '${e}': ${s}`),null)}jl(){const t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)}}class _i{constructor(t,e,s){this.targetId=t,this.state=e,this.error=s,p(void 0!==s==("rejected"===e),"QueryTargetMetadata must contain an error iff state is 'rejected'")}static Wl(t,e){const s=JSON.parse(e);let n="object"==typeof s&&-1!==["not-current","current","rejected"].indexOf(s.state)&&(void 0===s.error||"object"==typeof s.error),i=void 0;return n&&s.error&&(n="string"==typeof s.error.message&&"string"==typeof s.error.code)&&(i=new L(s.error.code,s.error.message)),n?new _i(t,s.state,i):(A(ci,`Failed to parse target state for ID '${t}': ${e}`),null)}jl(){const t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)}}class di{constructor(t,e){this.clientId=t,this.activeTargetIds=e}static Wl(t,e){const s=JSON.parse(e);let n="object"==typeof s&&s.activeTargetIds instanceof Array,i=ns();for(let t=0;n&&t<s.activeTargetIds.length;++t)n=Re(s.activeTargetIds[t]),i=i.add(s.activeTargetIds[t]);return n?new di(t,i):(A(ci,`Failed to parse client data for instance '${t}': ${e}`),null)}}class fi{constructor(t,e){this.clientId=t,this.onlineState=e}static Wl(t){const e=JSON.parse(t);return"object"==typeof e&&e.onlineState in k&&"string"==typeof e.clientId?new fi(e.clientId,k[e.onlineState]):(A(ci,`Failed to parse online state: ${t}`),null)}}class mi{constructor(){this.activeTargetIds=ns()}zl(t){this.activeTargetIds=this.activeTargetIds.add(t)}Kl(t){this.activeTargetIds=this.activeTargetIds.delete(t)}jl(){const t={activeTargetIds:this.activeTargetIds.rt(),updateTimeMs:Date.now()};return JSON.stringify(t)}}class Ti{constructor(t,e,s,n,i){if(this.Wu=t,this.platform=e,this.persistenceKey=s,this.Gl=n,this.vl=null,this.Gc=null,this.vo=null,this.Hl={},this.Jl=this.Yl.bind(this),this.Uh=!1,this.Xl=[],!Ti.Zl(this.platform))throw new L(M.UNIMPLEMENTED,"LocalStorage is not available on this platform.");const r=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.platform.window.localStorage,this.currentUser=i,this.t_=ni(this.persistenceKey,this.Gl),this.e_=function(t){return`${ui}_${t}`}(this.persistenceKey),this.Hl[this.Gl]=new mi,this.s_=new RegExp(`^${si}_${r}_([^_]*)$`),this.n_=new RegExp(`^${ii}_${r}_(\\d+)(?:_(.*))?$`),this.i_=new RegExp(`^${oi}_${r}_(\\d+)$`),this.r_=function(t){return`${ai}_${t}`}(this.persistenceKey),this.platform.window.addEventListener("storage",this.Jl)}static Zl(t){return!(!t.window||null==t.window.localStorage)}async start(){p(!this.Uh,"WebStorageSharedClientState already started"),p(null!==this.vl,"syncEngine property must be set before calling start()"),p(null!==this.Gc,"onlineStateHandler property must be set before calling start()");const t=await this.vl.ru();for(const e of t){if(e===this.Gl)continue;const t=this.getItem(ni(this.persistenceKey,e));if(t){const s=di.Wl(e,t);s&&(this.Hl[s.clientId]=s)}}this.o_();const e=this.storage.getItem(this.r_);if(e){const t=this.h_(e);t&&this.a_(t)}for(const t of this.Xl)this.Yl(t);this.Xl=[],this.platform.window.addEventListener("unload",()=>this.pl()),this.Uh=!0}Co(t){this.setItem(this.e_,JSON.stringify(t))}u_(){let t=ns();return K(this.Hl,(e,s)=>{t=t.Gt(s.activeTargetIds)}),t}c_(t){for(const e in this.Hl)if(this.Hl.hasOwnProperty(e)&&this.Hl[e].activeTargetIds.has(t))return!0;return!1}l_(t){this.__(t,"pending")}d_(t,e,s){this.__(t,e,s),this.f_(t)}m_(t){let e="not-current";if(this.c_(t)){const s=this.storage.getItem(hi(this.persistenceKey,t));if(s){const n=_i.Wl(t,s);n&&(e=n.state)}}return this.T_.zl(t),this.o_(),e}E_(t){this.T_.Kl(t),this.o_()}w_(t){return this.T_.activeTargetIds.has(t)}I_(t){this.removeItem(hi(this.persistenceKey,t))}R_(t,e,s){this.A_(t,e,s)}Ta(t,e,s){e.forEach(t=>{this.f_(t)}),this.currentUser=t,s.forEach(t=>{this.l_(t)})}P_(t){this.V_(t)}pl(){this.Uh&&(this.platform.window.removeEventListener("storage",this.Jl),this.removeItem(this.t_),this.Uh=!1)}getItem(t){const e=this.storage.getItem(t);return R(ci,"READ",t,e),e}setItem(t,e){R(ci,"SET",t,e),this.storage.setItem(t,e)}removeItem(t){R(ci,"REMOVE",t),this.storage.removeItem(t)}Yl(t){if(t.storageArea===this.storage){if(R(ci,"EVENT",t.key,t.newValue),t.key===this.t_)return void A("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.Wu.Yo(async()=>{if(this.Uh){if(null!==t.key)if(this.s_.test(t.key)){if(null==t.newValue){const e=this.p_(t.key);return this.g_(e,null)}{const e=this.y_(t.key,t.newValue);if(e)return this.g_(e.clientId,e)}}else if(this.n_.test(t.key)){if(null!==t.newValue){const e=this.b_(t.key,t.newValue);if(e)return this.v_(e)}}else if(this.i_.test(t.key)){if(null!==t.newValue){const e=this.S_(t.key,t.newValue);if(e)return this.D_(e)}}else if(t.key===this.r_){if(null!==t.newValue){const e=this.h_(t.newValue);if(e)return this.a_(e)}}else if(t.key===this.e_){p(!!this.vo,"Missing sequenceNumberHandler");const e=function(t){let e=Gs.ko;if(null!=t)try{const s=JSON.parse(t);p("number"==typeof s,"Found non-numeric sequence number"),e=s}catch(t){A(ci,"Failed to read sequence number from WebStorage",t)}return e}(t.newValue);e!==Gs.ko&&this.vo(e)}}else this.Xl.push(t)})}}get T_(){return this.Hl[this.Gl]}o_(){this.setItem(this.t_,this.T_.jl())}__(t,e,s){const n=new li(this.currentUser,t,e,s),i=ri(this.persistenceKey,this.currentUser,t);this.setItem(i,n.jl())}f_(t){const e=ri(this.persistenceKey,this.currentUser,t);this.removeItem(e)}V_(t){const e={clientId:this.Gl,onlineState:k[t]};this.storage.setItem(this.r_,JSON.stringify(e))}A_(t,e,s){const n=hi(this.persistenceKey,t),i=new _i(t,e,s);this.setItem(n,i.jl())}p_(t){const e=this.s_.exec(t);return e?e[1]:null}y_(t,e){const s=this.p_(t);return p(null!==s,`Cannot parse client state key '${t}'`),di.Wl(s,e)}b_(t,e){const s=this.n_.exec(t);p(null!==s,`Cannot parse mutation batch key '${t}'`);const n=Number(s[1]),i=void 0!==s[2]?s[2]:null;return li.Wl(new x(i),n,e)}S_(t,e){const s=this.i_.exec(t);p(null!==s,`Cannot parse query target key '${t}'`);const n=Number(s[1]);return _i.Wl(n,e)}h_(t){return fi.Wl(t)}async v_(t){if(t.user.uid===this.currentUser.uid)return this.vl.C_(t.batchId,t.state,t.error);R(ci,`Ignoring mutation for non-active user ${t.user.uid}`)}D_(t){return this.vl.k_(t.targetId,t.state,t.error)}g_(t,e){const s=this.u_();e?this.Hl[t]=e:delete this.Hl[t];const n=this.u_(),i=[],r=[];return n.forEach(async t=>{s.has(t)||i.push(t)}),s.forEach(async t=>{n.has(t)||r.push(t)}),this.vl.N_(i,r)}a_(t){this.Hl[t.clientId]&&this.Gc(t.onlineState)}}class Ei{constructor(){this.F_=new mi,this.x_={},this.vl=null,this.Gc=null,this.vo=null}l_(t){}d_(t,e,s){}m_(t){return this.F_.zl(t),this.x_[t]||"not-current"}R_(t,e,s){this.x_[t]=e}E_(t){this.F_.Kl(t)}w_(t){return this.F_.activeTargetIds.has(t)}I_(t){delete this.x_[t]}u_(){return this.F_.activeTargetIds}c_(t){return this.F_.activeTargetIds.has(t)}start(){return this.F_=new mi,Promise.resolve()}Ta(t,e,s){}P_(t){}pl(){}Co(t){}}const wi=1;var Ii,Ri;(Ri=Ii||(Ii={}))[Ri.M_=0]="__PRIVATE_QueryCache",Ri[Ri.L_=1]="__PRIVATE_SyncEngine";class Ai{constructor(t,e){this.B_=t,p((t&wi)===t,`Generator ID ${t} contains more than ${wi} reserved bits`),this.q_(void 0!==e?e:this.B_)}next(){const t=this.O_;return this.O_+=1<<wi,t}after(t){return this.q_(t+(1<<wi)),this.next()}q_(t){p((t&wi)===this.B_,"Cannot supply target ID from different generator ID"),this.O_=t}static U_(){return new Ai(Ii.M_,2)}static Q_(){return new Ai(Ii.L_)}}class Pi{constructor(t){this.key=t}}class Vi{constructor(t){this.key=t}}class pi{constructor(t,e){this.query=t,this.W_=e,this.j_=null,this.an=!1,this.z_=es(),this.Xs=es(),this.K_=new is(t.Rs.bind(t))}get G_(){return this.W_}H_(t,e){const s=e?e.J_:new ls,n=e?e.K_:this.K_;let i=e?e.Xs:this.Xs,r=n,o=!1;const h=this.query.gs()&&n.size===this.query.limit?n.last():null,a=this.query.ys()&&n.size===this.query.limit?n.first():null;if(t.Vt((t,e)=>{const u=n.get(t);let c=e instanceof _e?e:null;c&&(p(t.isEqual(c.key),"Mismatching keys found in document changes: "+t+" != "+c.key),c=this.query.matches(c)?c:null);const l=!!u&&this.Xs.has(u.key),_=!!c&&(c.de||this.Xs.has(c.key)&&c.hasCommittedMutations);let d=!1;if(u&&c){u.data().isEqual(c.data())?l!==_&&(s.track({type:rs.zs,doc:c}),d=!0):this.Y_(u,c)||(s.track({type:rs.js,doc:c}),d=!0,(h&&this.query.Rs(c,h)>0||a&&this.query.Rs(c,a)<0)&&(o=!0))}else!u&&c?(s.track({type:rs.Qs,doc:c}),d=!0):u&&!c&&(s.track({type:rs.Ws,doc:u}),d=!0,(h||a)&&(o=!0));d&&(c?(r=r.add(c),i=_?i.add(t):i.delete(t)):(r=r.delete(t),i=i.delete(t)))}),this.query.gs()||this.query.ys())for(;r.size>this.query.limit;){const t=this.query.gs()?r.last():r.first();r=r.delete(t.key),i=i.delete(t.key),s.track({type:rs.Ws,doc:t})}return p(!o||!e,"View was refilled using docs that themselves needed refilling."),{K_:r,J_:s,X_:o,Xs:i}}Y_(t,e){return t.de&&e.hasCommittedMutations&&!e.de}no(t,e,s){p(!t.X_,"Cannot apply changes that need a refill");const n=this.K_;this.K_=t.K_,this.Xs=t.Xs;const i=t.J_.Js();i.sort((t,e)=>(function(t,e){const s=t=>{switch(t){case rs.Qs:return 1;case rs.js:case rs.zs:return 2;case rs.Ws:return 0;default:return V("Unknown ChangeType: "+t)}};return s(t)-s(e)})(t.type,e.type)||this.query.Rs(t.doc,e.doc)),this.Z_(s);const r=e?this.td():[],o=0===this.z_.size&&this.an?hs.Gs:hs.Ks,h=o!==this.j_;if(this.j_=o,0!==i.length||h){return{snapshot:new _s(this.query,t.K_,n,i,t.Xs,o===hs.Ks,h,!1),ed:r}}return{ed:r}}sd(t){return this.an&&t===k.m?(this.an=!1,this.no({K_:this.K_,J_:new ls,Xs:this.Xs,X_:!1},!1)):{ed:[]}}nd(t){return!this.W_.has(t)&&(!!this.K_.has(t)&&!this.K_.get(t).de)}Z_(t){t&&(t.un.forEach(t=>this.W_=this.W_.add(t)),t.cn.forEach(t=>p(this.W_.has(t),`Modified document ${t} not found in view.`)),t.ln.forEach(t=>this.W_=this.W_.delete(t)),this.an=t.an)}td(){if(!this.an)return[];const t=this.z_;this.z_=es(),this.K_.forEach(t=>{this.nd(t.key)&&(this.z_=this.z_.add(t.key))});const e=[];return t.forEach(t=>{this.z_.has(t)||e.push(new Vi(t))}),this.z_.forEach(s=>{t.has(s)||e.push(new Pi(s))}),e}rd(t){this.W_=t.nu,this.z_=es();const e=this.H_(t.documents);return this.no(e,!0)}od(){return _s.en(this.query,this.K_,this.Xs,this.j_===hs.Ks)}}const gi=5;class yi{constructor(t,e,s,n){this.Uo=t,this.hd=e,this.updateFunction=s,this.zo=n,this.ad=gi,this.uc=new Bn(this.Uo,Js.Oo)}ud(){this.ld()}ld(){this.uc.Xu(async()=>{const t=this.hd.Ol(),e=this._d(t);e&&e.then(e=>{this.Uo.Yo(()=>t.commit().then(()=>{this.zo.resolve(e)}).catch(t=>{this.dd(t)}))}).catch(t=>{this.dd(t)})})}_d(t){try{const e=this.updateFunction(t);return!Ie(e)&&e.catch&&e.then?e:(this.zo.reject(Error("Transaction callback must return a Promise")),null)}catch(t){return this.zo.reject(t),null}}dd(t){this.ad>0&&this.fd(t)?(this.ad-=1,this.Uo.Yo(()=>(this.ld(),Promise.resolve()))):this.zo.reject(t)}fd(t){if("FirebaseError"===t.name){const e=t.code;return"aborted"===e||"failed-precondition"===e||!We(e)}return!1}}const bi="SyncEngine";class vi{constructor(t,e,s){this.query=t,this.targetId=e,this.view=s}}class Si{constructor(t){this.key=t,this.md=!1}}class Di{constructor(t,e,s,n){this.Mh=t,this.hd=e,this.Td=s,this.currentUser=n,this.Ed=null,this.wd=new xs(t=>t.canonicalId()),this.Id={},this.Rd=new Vt(Pt.J),this.Ad={},this.Pd=new qs,this.Vd={},this.pd=new Map,this.gd=Ai.Q_(),this.isPrimary=void 0,this.onlineState=k.l}get yd(){return!0===this.isPrimary}subscribe(t){p(null!==t,"SyncEngine listener cannot be null"),p(null===this.Ed,"SyncEngine already has a subscriber."),this.Ed=t}async listen(t){let e,s;this.bd("listen()");const n=this.wd.get(t);if(n)e=n.targetId,this.Td.m_(e),s=n.view.od();else{const n=await this.Mh.Ja(t.Is()),i=this.Td.m_(n.targetId);e=n.targetId,s=await this.vd(t,e,"current"===i),this.isPrimary&&this.hd.listen(n)}return this.Ed.yc([s]),e}async vd(t,e,s){const n=await this.Mh.eu(t,!0),i=new pi(t,n.nu),r=i.H_(n.documents),o=fs.hn(e,s&&this.onlineState!==k.m),h=i.no(r,!0===this.isPrimary,o);p(0===h.ed.length,"View returned limbo docs before target ack from the server."),p(!!h.snapshot,"applyChanges for new view should always return a snapshot");const a=new vi(t,e,i);return this.wd.set(t,a),this.Id[e]||(this.Id[e]=[]),this.Id[e].push(t),h.snapshot}async Sd(t){const e=await this.Mh.eu(t.query,!0),s=t.view.rd(e);return this.isPrimary&&this.Dd(t.targetId,s.ed),s}async yl(t){this.bd("unlisten()");const e=this.wd.get(t);p(!!e,"Trying to unlisten on query not found:"+t);const s=this.Id[e.targetId];if(s.length>1)return this.Id[e.targetId]=s.filter(e=>!e.isEqual(t)),void this.wd.delete(t);if(this.isPrimary){this.Td.E_(e.targetId),this.Td.c_(e.targetId)||await this.Mh.tu(e.targetId,!1).then(()=>{this.Td.I_(e.targetId),this.hd.yl(e.targetId),this.Cd(e.targetId)}).catch(ln)}else this.Cd(e.targetId),await this.Mh.tu(e.targetId,!0)}async write(t,e){this.bd("write()");const s=await this.Mh.Aa(t);this.Td.l_(s.batchId),this.kd(s.batchId,e),await this.Nd(s.Gr),await this.hd.Al()}runTransaction(t,e,s){new yi(t,this.hd,e,s).ud()}async Ma(t){this.bd("applyRemoteEvent()");try{const e=await this.Mh.Ma(t);K(t.sn,(t,e)=>{const s=this.Ad[Number(t)];s&&(p(e.un.size+e.cn.size+e.ln.size<=1,"Limbo resolution for single document contains multiple changes."),e.un.size>0?s.md=!0:e.cn.size>0?p(s.md,"Received change for limbo target document without add."):e.ln.size>0&&(p(s.md,"Received remove for limbo target document without add."),s.md=!1))}),await this.Nd(e,t)}catch(t){await ln(t)}}sd(t,e){if(this.isPrimary&&e===F.T||!this.isPrimary&&e===F.I){this.bd("applyOnlineStateChange()");const e=[];this.wd.forEach((s,n)=>{const i=n.view.sd(t);p(0===i.ed.length,"OnlineState should not affect limbo documents."),i.snapshot&&e.push(i.snapshot)}),this.Ed.Fd(t),this.Ed.yc(e),this.onlineState=t,this.isPrimary&&this.Td.P_(t)}}async Cl(t,e){this.bd("rejectListens()"),this.Td.R_(t,"rejected",e);const s=this.Ad[t],n=s&&s.key;if(n){this.Rd=this.Rd.remove(n),delete this.Ad[t];let e=new Vt(Pt.J);e=e.wt(n,new de(n,Tt.j()));const s=es().add(n),i=new ds(Tt.MIN,{},new yt(y),e,s);return this.Ma(i)}await this.Mh.tu(t,!1).then(()=>this.Cd(t,e)).catch(ln)}async C_(t,e,s){this.bd("applyBatchState()");const n=await this.Mh.Va(t);null!==n?("pending"===e?await this.hd.Al():"acknowledged"===e||"rejected"===e?(this.$d(t,s||null),this.Mh.ou(t)):V(`Unknown batchState: ${e}`),await this.Nd(n)):R(bi,"Cannot apply mutation batch with id: "+t)}async Ml(t){this.bd("applySuccessfulWrite()");const e=t.batch.batchId;this.$d(e,null),this.xd(e);try{const s=await this.Mh.ga(t);this.Td.d_(e,"acknowledged"),await this.Nd(s)}catch(t){await ln(t)}}async ql(t,e){this.bd("rejectFailedWrite()"),this.$d(t,e),this.xd(t);try{const s=await this.Mh.Da(t);this.Td.d_(t,"rejected",e),await this.Nd(s)}catch(e){await ln(e)}}async Md(t){this.hd.al()||R(bi,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");const e=await this.Mh.Na();if(e===Ms)return void t.resolve();const s=this.pd.get(e)||[];s.push(t),this.pd.set(e,s)}xd(t){(this.pd.get(t)||[]).forEach(t=>{t.resolve()}),this.pd.delete(t)}Ld(t){this.pd.forEach(e=>{e.forEach(e=>{e.reject(new L(M.CANCELLED,t))})}),this.pd.clear()}kd(t,e){let s=this.Vd[this.currentUser.A()];s||(s=new Vt(y)),s=s.wt(t,e),this.Vd[this.currentUser.A()]=s}$d(t,e){let s=this.Vd[this.currentUser.A()];if(s){const n=s.get(t);n&&(p(t===s.At(),"Mutation callbacks processed out-of-order?"),e?n.reject(e):n.resolve(),s=s.remove(t)),this.Vd[this.currentUser.A()]=s}}Cd(t,e=null){this.Td.E_(t),p(this.Id[t]&&0!==this.Id[t].length,`There are no queries mapped to target id ${t}`);for(const s of this.Id[t])this.wd.delete(s),e&&this.Ed.Bd(s,e);if(delete this.Id[t],this.isPrimary){const e=this.Pd.$r(t);this.Pd.Nr(t),e.forEach(t=>{this.Pd.xr(t)||this.qd(t)})}}qd(t){const e=this.Rd.get(t);null!==e&&(this.hd.yl(e),this.Rd=this.Rd.remove(t),delete this.Ad[e])}Dd(t,e){for(const s of e)if(s instanceof Pi)this.Pd.vr(s.key,t),this.Od(s);else if(s instanceof Vi){R(bi,"Document no longer in limbo: "+s.key),this.Pd.Dr(s.key,t),this.Pd.xr(s.key)||this.qd(s.key)}else V("Unknown limbo change: "+JSON.stringify(s))}Od(t){const e=t.key;if(!this.Rd.get(e)){R(bi,"New document in limbo: "+e);const t=this.gd.next(),s=pe.hs(e.path);this.Ad[t]=new Si(e),this.hd.listen(new Ue(s.Is(),t,Le.Fs,Gs.ko)),this.Rd=this.Rd.wt(e,t)}}Ud(){return this.Rd}async Nd(t,e){const s=[],n=[],i=[];this.wd.forEach((r,o)=>{i.push(Promise.resolve().then(()=>{const e=o.view.H_(t);return e.X_?this.Mh.eu(o.query,!1).then(({documents:t})=>o.view.H_(t,e)):e}).then(t=>{const i=e&&e.sn[o.targetId],r=o.view.no(t,!0===this.isPrimary,i);if(this.Dd(o.targetId,r.ed),r.snapshot){this.isPrimary&&this.Td.R_(o.targetId,r.snapshot.fromCache?"not-current":"current"),s.push(r.snapshot);const t=Ks.bo(o.targetId,r.snapshot);n.push(t)}}))}),await Promise.all(i),this.Ed.yc(s),await this.Mh.za(n)}bd(t){p(null!==this.Ed,"Trying to call "+t+" before calling subscribe().")}async Ul(t){const e=!this.currentUser.isEqual(t);if(this.currentUser=t,e){this.Ld("'waitForPendingWrites' promise is rejected due to a user change.");const e=await this.Mh.Ta(t);this.Td.Ta(t,e.Ia,e.Ra),await this.Nd(e.wa)}await this.hd.Ul()}async Ql(t){if(!0===t&&!0!==this.isPrimary){this.isPrimary=!0,await this.hd.Ql(!0);const t=this.Td.u_(),e=await this.Qd(t.rt());for(const t of e)this.hd.listen(t)}else if(!1===t&&!1!==this.isPrimary){this.isPrimary=!1;const t=[];let e=Promise.resolve();z(this.Id,(s,n)=>{this.Td.w_(s)?t.push(s):e=e.then(()=>(this.Cd(s),this.Mh.tu(s,!0))),this.hd.yl(s)}),await e,await this.Qd(t),this.Wd(),await this.hd.Ql(!1)}}Wd(){z(this.Ad,t=>{this.hd.yl(t)}),this.Pd.Fr(),this.Ad=[],this.Rd=new Vt(Pt.J)}async Qd(t){const e=[],s=[];for(const n of t){let t;const i=this.Id[n];if(i&&0!==i.length){await this.Mh.tu(n,!0),t=await this.Mh.Ja(i[0].Is());for(const t of i){const e=this.wd.get(t);p(!!e,`No query view found for ${t}`);const n=await this.Sd(e);n.snapshot&&s.push(n.snapshot)}}else{p(!0===this.isPrimary,"A secondary tab should never have an active target without an active query.");const e=await this.Mh.uu(n);p(!!e,`Target for id ${n} not found`),t=await this.Mh.Ja(e),await this.vd(this.jd(e),n,!1)}e.push(t)}return this.Ed.yc(s),e}jd(t){return new pe(t.path,t.collectionGroup,t.orderBy,t.filters,t.limit,Pe.Ze,t.startAt,t.endAt)}ru(){return this.Mh.ru()}async k_(t,e,s){if(this.isPrimary)R(bi,"Ignoring unexpected query state notification.");else if(this.Id[t])switch(e){case"current":case"not-current":{const s=await this.Mh.cu(),n=ds.on(t,"current"===e);await this.Nd(s,n);break}case"rejected":await this.Mh.tu(t,!0),this.Cd(t,s);break;default:V("Unexpected target state: "+e)}}async N_(t,e){if(this.isPrimary){for(const e of t){p(!this.Id[e],"Trying to add an already active target");const t=await this.Mh.uu(e);p(!!t,`Query data for active target ${e} not found`);const s=await this.Mh.Ja(t);await this.vd(this.jd(t),s.targetId,!1),this.hd.listen(s)}for(const t of e)this.Id[t]&&await this.Mh.tu(t,!1).then(()=>{this.hd.yl(t),this.Cd(t)}).catch(ln)}}enableNetwork(){return this.Mh.au(!0),this.hd.enableNetwork()}disableNetwork(){return this.Mh.au(!1),this.hd.disableNetwork()}Xn(t){const e=this.Ad[t];if(e&&e.md)return es().add(e.key);{let e=es();const s=this.Id[t];if(!s)return e;for(const t of s){const s=this.wd.get(t);p(!!s,`No query view found for ${t}`),e=e.Gt(s.view.G_)}return e}}}class Ci{constructor(){this.zd=null,this.targetId=0,this.Kd=[]}}class ki{constructor(t){this.vl=t,this.Gd=new xs(t=>t.canonicalId()),this.onlineState=k.l,this.Hd=new Set,this.vl.subscribe(this)}listen(t){const e=t.query;let s=!1,n=this.Gd.get(e);if(n||(s=!0,n=new Ci,this.Gd.set(e,n)),n.Kd.push(t),p(!t.sd(this.onlineState),"applyOnlineStateChange() shouldn't raise an event for brand-new listeners."),n.zd){t.Jd(n.zd)&&this.Yd()}return s?this.vl.listen(e).then(t=>(n.targetId=t,t)):Promise.resolve(n.targetId)}async yl(t){const e=t.query;let s=!1;const n=this.Gd.get(e);if(n){const e=n.Kd.indexOf(t);e>=0&&(n.Kd.splice(e,1),s=0===n.Kd.length)}if(s)return this.Gd.delete(e),this.vl.yl(e)}yc(t){let e=!1;for(const s of t){const t=s.query,n=this.Gd.get(t);if(n){for(const t of n.Kd)t.Jd(s)&&(e=!0);n.zd=s}}e&&this.Yd()}Bd(t,e){const s=this.Gd.get(t);if(s)for(const t of s.Kd)t.onError(e);this.Gd.delete(t)}Fd(t){this.onlineState=t;let e=!1;this.Gd.forEach((s,n)=>{for(const s of n.Kd)s.sd(t)&&(e=!0)}),e&&this.Yd()}Xd(t){this.Hd.add(t),t.next()}Zd(t){this.Hd.delete(t)}Yd(){this.Hd.forEach(t=>{t.next()})}}class Ni{constructor(t,e,s){this.query=t,this.tf=e,this.ef=!1,this.sf=null,this.onlineState=k.l,this.options=s||{}}Jd(t){if(p(t.docChanges.length>0||t.Zs,"We got a new snapshot with no changes?"),!this.options.includeMetadataChanges){const e=[];for(const s of t.docChanges)s.type!==rs.zs&&e.push(s);t=new _s(t.query,t.docs,t.Ys,e,t.Xs,t.fromCache,t.Zs,!0)}let e=!1;return this.ef?this.nf(t)&&(this.tf.next(t),e=!0):this.if(t,this.onlineState)&&(this.rf(t),e=!0),this.sf=t,e}onError(t){this.tf.error(t)}sd(t){this.onlineState=t;let e=!1;return this.sf&&!this.ef&&this.if(this.sf,t)&&(this.rf(this.sf),e=!0),e}if(t,e){if(p(!this.ef,"Determining whether to raise first event but already had first event"),!t.fromCache)return!0;const s=e!==k.m;return this.options.hf&&s?(p(t.fromCache,"Waiting for sync, but snapshot is not from cache"),!1):!t.docs.tt()||e===k.m}nf(t){if(t.docChanges.length>0)return!0;const e=this.sf&&this.sf.hasPendingWrites!==t.hasPendingWrites;return!(!t.Zs&&!e)&&!0===this.options.includeMetadataChanges}rf(t){p(!this.ef,"Trying to raise initial events for second time"),t=_s.en(t.query,t.docs,t.Xs,t.fromCache),this.ef=!0,this.tf.next(t)}}const Fi="",$i="",xi="",Mi="";function Li(t){let e="";for(let s=0;s<t.length;s++)e.length>0&&(e=qi(e)),e=Bi(t.get(s),e);return qi(e)}function Bi(t,e){let s=e;const n=t.length;for(let e=0;e<n;e++){const n=t.charAt(e);switch(n){case"\0":s+=Fi+xi;break;case Fi:s+=Fi+Mi;break;default:s+=n}}return s}function qi(t){return t+Fi+$i}function Oi(t){const e=t.length;if(p(e>=2,"Invalid path "+t),2===e)return p(t.charAt(0)===Fi&&t.charAt(1)===$i,"Non-empty path "+t+" had length 2"),It.at;const s=e-2,n=[];let i="";for(let r=0;r<e;){const e=t.indexOf(Fi,r);switch((e<0||e>s)&&V('Invalid encoded resource path: "'+t+'"'),t.charAt(e+1)){case $i:const s=t.substring(r,e);let o;0===i.length?o=s:(o=i+=s,i=""),n.push(o);break;case xi:i+=t.substring(r,e),i+="\0";break;case Mi:i+=t.substring(r,e+1);break;default:V('Invalid encoded resource path: "'+t+'"')}r=e+2}return new It(n)}const Ui="SimpleDb",Qi=3;class Wi{constructor(t){this.db=t,12.2===Wi.af(n())&&A("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static uf(t,e,s){return p(Wi.Zl(),"IndexedDB not supported in current environment."),R(Ui,"Opening database:",t),new Us((n,i)=>{const r=window.indexedDB.open(t,e);r.onsuccess=t=>{const e=t.target.result;n(new Wi(e))},r.onblocked=()=>{i(new L(M.FAILED_PRECONDITION,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{const e=t.target.error;"VersionError"===e.name?i(new L(M.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):i(e)},r.onupgradeneeded=e=>{R(Ui,'Database "'+t+'" requires upgrade from version:',e.oldVersion);const n=e.target.result;s.createOrUpgrade(n,r.transaction,e.oldVersion,Tr).next(()=>{R(Ui,"Database upgrade to version "+Tr+" complete")})}}).Wr()}static delete(t){return R(Ui,"Removing database:",t),Gi(window.indexedDB.deleteDatabase(t)).Wr()}static Zl(){if("undefined"==typeof window||null==window.indexedDB)return!1;if(Wi.cf())return!0;if(void 0===window.navigator)return!1;const t=n(),e=Wi.af(t),s=0<e&&e<10,i=Wi.lf(t),r=0<i&&i<4.5;return!(t.indexOf("MSIE ")>0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0||s||r)}static cf(){var t;return"undefined"!=typeof __PRIVATE_process&&"YES"===(null===(t=__PRIVATE_process.__PRIVATE_env)||void 0===t?void 0:t._f)}static df(t,e){return t.store(e)}static af(t){const e=t.match(/i(?:phone|pad|pod) os ([\d_]+)/i),s=e?e[1].split("_").slice(0,2).join("."):"-1";return Number(s)}static lf(t){const e=t.match(/Android ([\d.]+)/i),s=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(s)}ff(t){this.db.onversionchange=e=>t(e)}async runTransaction(t,e,s){const n=t.startsWith("readonly"),i=t.endsWith("idempotent");let r=0;for(;;){++r;const t=zi.open(this.db,n?"readonly":"readwrite",e);try{const e=s(t).catch(e=>(t.abort(e),Us.reject(e))).Wr();return e.catch(()=>{}),await t.mf,e}catch(t){const e=i&&"FirebaseError"!==t.name&&r<Qi;if(R(Ui,"Transaction failed with error: %s. Retrying: %s.",t.message,e),!e)return Promise.reject(t)}}}close(){this.db.close()}}class ji{constructor(t){this.Tf=t,this.Ef=!1,this.wf=null}get qr(){return this.Ef}get If(){return this.wf}set cursor(t){this.Tf=t}done(){this.Ef=!0}Rf(t){this.wf=t}delete(){return Gi(this.Tf.delete())}}class zi{constructor(t){this.transaction=t,this.aborted=!1,this.Af=new Hs,this.transaction.oncomplete=()=>{this.Af.resolve()},this.transaction.onabort=()=>{t.error?this.Af.reject(t.error):this.Af.resolve()},this.transaction.onerror=t=>{const e=Ji(t.target.error);this.Af.reject(e)}}static open(t,e,s){return new zi(t.transaction(s,e))}get mf(){return this.Af.promise}abort(t){t&&this.Af.reject(t),this.aborted||(R(Ui,"Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}store(t){const e=this.transaction.objectStore(t);return p(!!e,"Object store not part of transaction: "+t),new Ki(e)}}class Ki{constructor(t){this.store=t}put(t,e){let s;return void 0!==e?(R(Ui,"PUT",this.store.name,t,e),s=this.store.put(e,t)):(R(Ui,"PUT",this.store.name,"<auto-key>",t),s=this.store.put(t)),Gi(s)}add(t){return R(Ui,"ADD",this.store.name,t,t),Gi(this.store.add(t))}get(t){return Gi(this.store.get(t)).next(e=>(void 0===e&&(e=null),R(Ui,"GET",this.store.name,t,e),e))}delete(t){return R(Ui,"DELETE",this.store.name,t),Gi(this.store.delete(t))}count(){return R(Ui,"COUNT",this.store.name),Gi(this.store.count())}Pf(t,e){const s=this.cursor(this.options(t,e)),n=[];return this.Vf(s,(t,e)=>{n.push(e)}).next(()=>n)}pf(t,e){R(Ui,"DELETE ALL",this.store.name);const s=this.options(t,e);s.gf=!1;const n=this.cursor(s);return this.Vf(n,(t,e,s)=>s.delete())}yf(t,e){let s;e?s=t:(s={},e=t);const n=this.cursor(s);return this.Vf(n,e)}bf(t){const e=this.cursor({});return new Us((s,n)=>{e.onerror=t=>{const e=Ji(t.target.error);n(e)},e.onsuccess=e=>{const n=e.target.result;n?t(n.primaryKey,n.value).next(t=>{t?n.continue():s()}):s()}})}Vf(t,e){const s=[];return new Us((n,i)=>{t.onerror=t=>{i(t.target.error)},t.onsuccess=t=>{const i=t.target.result;if(!i)return void n();const r=new ji(i),o=e(i.primaryKey,i.value,r);if(o instanceof Us){const t=o.catch(t=>(r.done(),Us.reject(t)));s.push(t)}r.qr?n():null===r.If?i.continue():i.continue(r.If)}}).next(()=>Us.zr(s))}options(t,e){let s=void 0;return void 0!==t&&("string"==typeof t?s=t:(p(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:s,range:e}}cursor(t){let e="next";if(t.reverse&&(e="prev"),t.index){const s=this.store.index(t.index);return t.gf?s.openKeyCursor(t.range,e):s.openCursor(t.range,e)}return this.store.openCursor(t.range,e)}}function Gi(t){return new Us((e,s)=>{t.onsuccess=t=>{const s=t.target.result;e(s)},t.onerror=t=>{const e=Ji(t.target.error);s(e)}})}let Hi=!1;function Ji(t){const e=Wi.af(n());if(e>=12.2&&e<13){const e="An internal error was encountered in the Indexed Database server";if(t.message.indexOf(e)>=0){const t=new L("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely `+"due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");return Hi||(Hi=!0,setTimeout(()=>{throw t},0)),t}}return t}class Yi{constructor(t,e,s,n){this.userId=t,this.serializer=e,this.uo=s,this.oa=n,this.vf={}}static Sf(t,e,s,n){p(""!==t.uid,"UserID must not be an empty string.");const i=t.R()?t.uid:"";return new Yi(i,e,s,n)}Df(t){let e=!0;const s=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return er(t).yf({index:Ar.userMutationsIndex,range:s},(t,s,n)=>{e=!1,n.done()}).next(()=>e)}ga(t,e,s){return this.Cf(t).next(e=>(e.lastStreamToken=tr(s),nr(t).put(e)))}Fa(t){return this.Cf(t).next(t=>t.lastStreamToken)}$a(t,e){return this.Cf(t).next(s=>(s.lastStreamToken=tr(e),nr(t).put(s)))}Pa(t,e,s,n){const i=sr(t),r=er(t);return r.add({}).next(o=>{p("number"==typeof o,"Auto-generated key is not a number");const h=new Ls(o,e,s,n),a=this.serializer.kf(this.userId,h),u=[];let c=new yt((t,e)=>y(t.ot(),e.ot()));for(const t of n){const e=Pr.key(this.userId,t.key.path,o);c=c.add(t.key.path.Z()),u.push(r.put(a)),u.push(i.put(e,Pr.PLACEHOLDER))}return c.forEach(e=>{u.push(this.uo.Nf(t,e))}),t.ro(()=>{this.vf[o]=h.keys()}),Us.zr(u).next(()=>h)})}Ca(t,e){return er(t).get(e).next(t=>t?(p(t.userId===this.userId,`Unexpected user '${t.userId}' for mutation batch ${e}`),this.serializer.Ff(t)):null)}pa(t,e){return this.vf[e]?Us.resolve(this.vf[e]):this.Ca(t,e).next(t=>{if(t){const s=t.keys();return this.vf[e]=s,s}return null})}Ga(t,e){const s=e+1,n=IDBKeyRange.lowerBound([this.userId,s]);let i=null;return er(t).yf({index:Ar.userMutationsIndex,range:n},(t,e,n)=>{e.userId===this.userId&&(p(e.batchId>=s,"Should have found mutation after "+s),i=this.serializer.Ff(e)),n.done()}).next(()=>i)}Na(t){const e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let s=Ms;return er(t).yf({index:Ar.userMutationsIndex,range:e,reverse:!0},(t,e,n)=>{s=e.batchId,n.done()}).next(()=>s)}Ea(t){const e=IDBKeyRange.bound([this.userId,Ms],[this.userId,Number.POSITIVE_INFINITY]);return er(t).Pf(Ar.userMutationsIndex,e).next(t=>t.map(t=>this.serializer.Ff(t)))}lo(t,e){const s=Pr.prefixForPath(this.userId,e.path),n=IDBKeyRange.lowerBound(s),i=[];return sr(t).yf({range:n},(s,n,r)=>{const[o,h,a]=s,u=Oi(h);if(o===this.userId&&e.path.isEqual(u))return er(t).get(a).next(t=>{if(!t)throw V("Dangling document-mutation reference found: "+s+" which points to "+a);p(t.userId===this.userId,`Unexpected user '${t.userId}' for mutation batch ${a}`),i.push(this.serializer.Ff(t))});r.done()}).next(()=>i)}To(t,e){let s=new yt(y);const n=[];return e.forEach(e=>{const i=Pr.prefixForPath(this.userId,e.path),r=IDBKeyRange.lowerBound(i),o=sr(t).yf({range:r},(t,n,i)=>{const[r,o,h]=t,a=Oi(o);r===this.userId&&e.path.isEqual(a)?s=s.add(h):i.done()});n.push(o)}),Us.zr(n).next(()=>this.$f(t,s))}Po(t,e){p(!e.Xe(),"Document queries shouldn't go down this path"),p(!e.vs(),"CollectionGroup queries should be handled in LocalDocumentsView");const s=e.path,n=s.length+1,i=Pr.prefixForPath(this.userId,s),r=IDBKeyRange.lowerBound(i);let o=new yt(y);return sr(t).yf({range:r},(t,e,i)=>{const[r,h,a]=t,u=Oi(h);r===this.userId&&s.nt(u)?u.length===n&&(o=o.add(a)):i.done()}).next(()=>this.$f(t,o))}$f(t,e){const s=[],n=[];return e.forEach(e=>{n.push(er(t).get(e).next(t=>{if(null===t)throw V("Dangling document-mutation reference found, which points to "+e);p(t.userId===this.userId,`Unexpected user '${t.userId}' for mutation batch ${e}`),s.push(this.serializer.Ff(t))}))}),Us.zr(n).next(()=>s)}ka(t,e){return Zi(t.xf,this.userId,e).next(s=>(t.ro(()=>{this.hu(e.batchId)}),Us.forEach(s,e=>this.oa.Mf(t,e))))}hu(t){delete this.vf[t]}Sa(t){return this.Df(t).next(e=>{if(!e)return Us.resolve();const s=IDBKeyRange.lowerBound(Pr.prefixForUser(this.userId)),n=[];return sr(t).yf({range:s},(t,e,s)=>{if(t[0]===this.userId){const e=Oi(t[1]);n.push(e)}else s.done()}).next(()=>{p(0===n.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+n.map(t=>t.ot()))})})}xr(t,e){return Xi(t,this.userId,e)}Cf(t){return nr(t).get(this.userId).next(t=>t||new Rr(this.userId,Ms,""))}}function Xi(t,e,s){const n=Pr.prefixForPath(e,s.path),i=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return sr(t).yf({range:r,gf:!0},(t,s,n)=>{const[r,h,a]=t;r===e&&h===i&&(o=!0),n.done()}).next(()=>o)}function Zi(t,e,s){const n=t.store(Ar.store),i=t.store(Pr.store),r=[],o=IDBKeyRange.only(s.batchId);let h=0;const a=n.yf({range:o},(t,e,s)=>(h++,s.delete()));r.push(a.next(()=>{p(1===h,"Dangling document-mutation reference found: Missing batch "+s.batchId)}));const u=[];for(const t of s.mutations){const n=Pr.key(e,t.key.path,s.batchId);r.push(i.delete(n)),u.push(t.key)}return Us.zr(r).next(()=>u)}function tr(t){return t instanceof Uint8Array?(p(Wi.cf(),"Persisting non-string stream tokens is only supported with mock persistence."),t.toString()):t}function er(t){return jr.df(t,Ar.store)}function sr(t){return jr.df(t,Pr.store)}function nr(t){return jr.df(t,Rr.store)}class ir{constructor(t,e){this.oa=t,this.serializer=e,this.Lf=Ai.U_()}Xa(t){return this.Bf(t).next(e=>(e.highestTargetId=this.Lf.after(e.highestTargetId),this.qf(t,e).next(()=>e.highestTargetId)))}xa(t){return this.Bf(t).next(t=>Tt.W(new mt(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds)))}Of(t){return hr(t.xf)}Wa(t,e,s){return this.Bf(t).next(n=>(n.highestListenSequenceNumber=e,s&&(n.lastRemoteSnapshotVersion=s.G()),e>n.highestListenSequenceNumber&&(n.highestListenSequenceNumber=e),this.qf(t,n)))}Za(t,e){return this.Uf(t,e).next(()=>this.Bf(t).next(s=>(s.targetCount+=1,this.Qf(e,s),this.qf(t,s))))}Ua(t,e){return this.Uf(t,e)}Wf(t,e){return this.jf(t,e.targetId).next(()=>rr(t).delete(e.targetId)).next(()=>this.Bf(t)).next(e=>(p(e.targetCount>0,"Removing from an empty target cache"),e.targetCount-=1,this.qf(t,e)))}Hh(t,e,s){let n=0;const i=[];return rr(t).yf((r,o)=>{const h=this.serializer.zf(o);h.sequenceNumber<=e&&null===s.get(h.targetId)&&(n++,i.push(this.Wf(t,h)))}).next(()=>Us.zr(i)).next(()=>n)}Un(t,e){return rr(t).yf((t,s)=>{const n=this.serializer.zf(s);e(n)})}Bf(t){return or(t.xf)}qf(t,e){return(s=t,jr.df(s,Sr.store)).put(Sr.key,e);var s}Uf(t,e){return rr(t).put(this.serializer.Kf(e))}Qf(t,e){let s=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,s=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,s=!0),s}Gf(t){return this.Bf(t).next(t=>t.targetCount)}Ya(t,e){const s=e.canonicalId(),n=IDBKeyRange.bound([s,Number.NEGATIVE_INFINITY],[s,Number.POSITIVE_INFINITY]);let i=null;return rr(t).yf({range:n,index:br.queryTargetsIndexName},(t,s,n)=>{const r=this.serializer.zf(s);e.isEqual(r.target)&&(i=r,n.done())}).next(()=>i)}Ba(t,e,s){const n=[],i=ar(t);return e.forEach(e=>{const r=Li(e.path);n.push(i.put(new vr(s,r))),n.push(this.oa.vr(t,e))}),Us.zr(n)}La(t,e,s){const n=ar(t);return Us.forEach(e,e=>{const i=Li(e.path);return Us.zr([n.delete([s,i]),this.oa.Dr(t,e)])})}jf(t,e){const s=ar(t),n=IDBKeyRange.bound([e],[e+1],!1,!0);return s.delete(n)}su(t,e){const s=IDBKeyRange.bound([e],[e+1],!1,!0),n=ar(t);let i=es();return n.yf({range:s,gf:!0},(t,e,s)=>{const n=Oi(t[1]),r=new Pt(n);i=i.add(r)}).next(()=>i)}xr(t,e){const s=Li(e.path),n=IDBKeyRange.bound([s],[v(s)],!1,!0);let i=0;return ar(t).yf({index:vr.documentTargetsIndex,gf:!0,range:n},([t,e],s,n)=>{0!==t&&(i++,n.done())}).next(()=>i>0)}Zn(t,e){return rr(t).get(e).next(t=>t?this.serializer.zf(t):null)}}function rr(t){return jr.df(t,br.store)}function or(t){return Wi.df(t,Sr.store).get(Sr.key).next(t=>(p(null!==t,"Missing metadata row."),t))}function hr(t){return or(t).next(t=>t.highestListenSequenceNumber)}function ar(t){return jr.df(t,vr.store)}class ur{constructor(t,e){this.serializer=t,this.uo=e}Yr(t,e,s){return lr(t).put(_r(e),s)}Zr(t,e){const s=lr(t),n=_r(e);return s.delete(n)}updateMetadata(t,e){return this.getMetadata(t).next(s=>(s.byteSize+=e,this.Hf(t,s)))}to(t,e){return lr(t).get(_r(e)).next(t=>this.Jf(t))}Yf(t,e){return lr(t).get(_r(e)).next(t=>{const e=this.Jf(t);return e?{Xf:e,size:dr(t)}:null})}getEntries(t,e){let s=He();return this.Zf(t,e,(t,e)=>{const n=this.Jf(e);s=s.wt(t,n)}).next(()=>s)}tm(t,e){let s=He(),n=new Vt(Pt.J);return this.Zf(t,e,(t,e)=>{const i=this.Jf(e);i?(s=s.wt(t,i),n=n.wt(t,dr(e))):(s=s.wt(t,null),n=n.wt(t,0))}).next(()=>({em:s,sm:n}))}Zf(t,e,s){if(e.tt())return Us.resolve();const n=IDBKeyRange.bound(e.first().path.rt(),e.last().path.rt()),i=e.gt();let r=i.Ct();return lr(t).yf({range:n},(t,e,n)=>{const o=Pt.Tt(t);for(;r&&Pt.J(r,o)<0;)s(r,null),r=i.Ct();r&&r.isEqual(o)&&(s(r,e),r=i.kt()?i.Ct():null),r?n.Rf(r.path.rt()):n.done()}).next(()=>{for(;r;)s(r,null),r=i.kt()?i.Ct():null})}Eo(t,e,s){p(!e.vs(),"CollectionGroup queries should be handled in LocalDocumentsView");let n=Ye();const i=e.path.length+1,r={};if(s.isEqual(Tt.MIN)){const t=e.path.rt();r.range=IDBKeyRange.lowerBound(t)}else{const t=e.path.rt(),n=this.serializer.nm(s);r.range=IDBKeyRange.lowerBound([t,n],!0),r.index=gr.collectionReadTimeIndex}return lr(t).yf(r,(t,s,r)=>{if(t.length!==i)return;const o=this.serializer.im(s);e.path.nt(o.key.path)?o instanceof _e&&e.matches(o)&&(n=n.wt(o.key,o)):r.done()}).next(()=>n)}cu(t,e){let s=Ge(),n=this.serializer.nm(e);const i=lr(t),r=IDBKeyRange.lowerBound(n,!0);return i.yf({index:gr.readTimeIndex,range:r},(t,e)=>{const i=this.serializer.im(e);s=s.wt(i.key,i),n=e.readTime}).next(()=>({lu:s,readTime:this.serializer.rm(n)}))}_u(t){const e=lr(t);let s=Tt.MIN;return e.yf({index:gr.readTimeIndex,reverse:!0},(t,e,n)=>{e.readTime&&(s=this.serializer.rm(e.readTime)),n.done()}).next(()=>s)}ya(t){return new ur.om(this,!!t&&t.ba)}hm(t){return this.getMetadata(t).next(t=>t.byteSize)}getMetadata(t){return cr(t).get(yr.key).next(t=>(p(!!t,"Missing document cache metadata"),t))}Hf(t,e){return cr(t).put(yr.key,e)}Jf(t){if(t){const e=this.serializer.im(t);return e instanceof de&&e.version.isEqual(Tt.j())?null:e}return null}}function cr(t){return jr.df(t,yr.store)}function lr(t){return jr.df(t,gr.store)}function _r(t){return t.path.rt()}function dr(t){let e;if(t.document)e=t.document;else if(t.unknownDocument)e=t.unknownDocument;else{if(!t.noDocument)throw V("Unknown remote document type");e=t.noDocument}return JSON.stringify(e).length}ur.om=class extends Qs{constructor(t,e){super(),this.am=t,this.ba=e,this.um=new xs(t=>t.toString())}no(t){const e=[];let s=0,n=new yt((t,e)=>y(t.ot(),e.ot()));return this.Gr.forEach((i,r)=>{const o=this.um.get(i);if(p(void 0!==o,`Cannot modify a document that wasn't read (for ${i})`),r){p(!this.readTime.isEqual(Tt.MIN),"Cannot add a document with a read time of zero");const h=this.am.serializer.cm(r,this.readTime);n=n.add(i.path.Z());const a=dr(h);s+=a-o,e.push(this.am.Yr(t,i,h))}else if(s-=o,this.ba){const s=this.am.serializer.cm(new de(i,Tt.j()),this.readTime);e.push(this.am.Yr(t,i,s))}else e.push(this.am.Zr(t,i))}),n.forEach(s=>{e.push(this.am.uo.Nf(t,s))}),e.push(this.am.updateMetadata(t,s)),Us.zr(e)}eo(t,e){return this.am.Yf(t,e).next(t=>null===t?(this.um.set(e,0),null):(this.um.set(e,t.size),t.Xf))}so(t,e){return this.am.tm(t,e).next(({em:t,sm:e})=>(e.forEach((t,e)=>{this.um.set(t,e)}),t))}};class fr{constructor(){this.lm=new mr}Nf(t,e){return this.lm.add(e),Us.resolve()}Ao(t,e){return Us.resolve(this.lm.getEntries(e))}}class mr{constructor(){this.index={}}add(t){p(t.length%2==1,"Expected a collection path.");const e=t.st(),s=t.Z(),n=this.index[e]||new yt(It.J),i=!n.has(s);return this.index[e]=n.add(s),i}has(t){const e=t.st(),s=t.Z(),n=this.index[e];return n&&n.has(s)}getEntries(t){return(this.index[t]||new yt(It.J)).rt()}}const Tr=9;class Er{constructor(t){this.serializer=t}createOrUpgrade(t,e,s,n){p(s<n&&s>=0&&n<=Tr,`Unexpected schema upgrade from v${s} to v{toVersion}.`);const i=new zi(e);s<1&&n>=1&&(function(t){t.createObjectStore(Ir.store)}(t),function(t){t.createObjectStore(Rr.store,{keyPath:Rr.keyPath}),t.createObjectStore(Ar.store,{keyPath:Ar.keyPath,autoIncrement:!0}).createIndex(Ar.userMutationsIndex,Ar.userMutationsKeyPath,{unique:!0}),t.createObjectStore(Pr.store)}(t),Cr(t),function(t){t.createObjectStore(gr.store)}(t));let r=Us.resolve();return s<3&&n>=3&&(0!==s&&(!function(t){t.deleteObjectStore(vr.store),t.deleteObjectStore(br.store),t.deleteObjectStore(Sr.store)}(t),Cr(t)),r=r.next(()=>(function(t){const e=t.store(Sr.store),s=new Sr(0,0,Tt.MIN.G(),0);return e.put(Sr.key,s)})(i))),s<4&&n>=4&&(0!==s&&(r=r.next(()=>(function(t,e){return e.store(Ar.store).Pf().next(s=>{t.deleteObjectStore(Ar.store),t.createObjectStore(Ar.store,{keyPath:Ar.keyPath,autoIncrement:!0}).createIndex(Ar.userMutationsIndex,Ar.userMutationsKeyPath,{unique:!0});const n=e.store(Ar.store),i=s.map(t=>n.put(t));return Us.zr(i)})})(t,i))),r=r.next(()=>{!function(t){t.createObjectStore(kr.store,{keyPath:kr.keyPath})}(t)})),s<5&&n>=5&&(r=r.next(()=>this.removeAcknowledgedMutations(i))),s<6&&n>=6&&(r=r.next(()=>(function(t){t.createObjectStore(yr.store)}(t),this.addDocumentGlobal(i)))),s<7&&n>=7&&(r=r.next(()=>this.ensureSequenceNumbers(i))),s<8&&n>=8&&(r=r.next(()=>this.createCollectionParentIndex(t,i))),s<9&&n>=9&&(r=r.next(()=>{!function(t){t.objectStoreNames.contains("remoteDocumentChanges")&&t.deleteObjectStore("remoteDocumentChanges")}(t),function(t){const e=t.objectStore(gr.store);e.createIndex(gr.readTimeIndex,gr.readTimeIndexPath,{unique:!1}),e.createIndex(gr.collectionReadTimeIndex,gr.collectionReadTimeIndexPath,{unique:!1})}(e)})),r}addDocumentGlobal(t){let e=0;return t.store(gr.store).yf((t,s)=>{e+=dr(s)}).next(()=>{const s=new yr(e);return t.store(yr.store).put(yr.key,s)})}removeAcknowledgedMutations(t){const e=t.store(Rr.store),s=t.store(Ar.store);return e.Pf().next(e=>Us.forEach(e,e=>{const n=IDBKeyRange.bound([e.userId,Ms],[e.userId,e.lastAcknowledgedBatchId]);return s.Pf(Ar.userMutationsIndex,n).next(s=>Us.forEach(s,s=>{p(s.userId===e.userId,`Cannot process batch ${s.batchId} from unexpected user`);const n=this.serializer.Ff(s);return Zi(t,e.userId,n).next(()=>{})}))}))}ensureSequenceNumbers(t){const e=t.store(vr.store),s=t.store(gr.store);return hr(t).next(t=>{const n=[];return s.yf((s,i)=>{const r=new It(s),o=function(t){return[0,Li(t)]}(r);n.push(e.get(o).next(s=>s?Us.resolve():(s=>e.put(new vr(0,Li(s),t)))(r)))}).next(()=>Us.zr(n))})}createCollectionParentIndex(t,e){t.createObjectStore(Dr.store,{keyPath:Dr.keyPath});const s=e.store(Dr.store),n=new mr,i=t=>{if(n.add(t)){const e=t.st(),n=t.Z();return s.put({collectionId:e,parent:Li(n)})}};return e.store(gr.store).yf({gf:!0},(t,e)=>{const s=new It(t);return i(s.Z())}).next(()=>e.store(Pr.store).yf({gf:!0},([t,e,s],n)=>{const r=Oi(e);return i(r.Z())}))}}class wr{constructor(t,e){this.seconds=t,this.nanoseconds=e}}class Ir{constructor(t,e,s){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=s}}Ir.store="owner",Ir.key="owner";class Rr{constructor(t,e,s){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=s}}Rr.store="mutationQueues",Rr.keyPath="userId";class Ar{constructor(t,e,s,n,i){this.userId=t,this.batchId=e,this.localWriteTimeMs=s,this.baseMutations=n,this.mutations=i}}Ar.store="mutations",Ar.keyPath="batchId",Ar.userMutationsIndex="userMutationsIndex",Ar.userMutationsKeyPath=["userId","batchId"];class Pr{constructor(){}static prefixForUser(t){return[t]}static prefixForPath(t,e){return[t,Li(e)]}static key(t,e,s){return[t,Li(e),s]}}Pr.store="documentMutations",Pr.PLACEHOLDER=new Pr;class Vr{constructor(t,e){this.path=t,this.readTime=e}}class pr{constructor(t,e){this.path=t,this.version=e}}class gr{constructor(t,e,s,n,i,r){this.unknownDocument=t,this.noDocument=e,this.document=s,this.hasCommittedMutations=n,this.readTime=i,this.parentPath=r}}gr.store="remoteDocuments",gr.readTimeIndex="readTimeIndex",gr.readTimeIndexPath="readTime",gr.collectionReadTimeIndex="collectionReadTimeIndex",gr.collectionReadTimeIndexPath=["parentPath","readTime"];class yr{constructor(t){this.byteSize=t}}yr.store="remoteDocumentGlobal",yr.key="remoteDocumentGlobalKey";class br{constructor(t,e,s,n,i,r,o){this.targetId=t,this.canonicalId=e,this.readTime=s,this.resumeToken=n,this.lastListenSequenceNumber=i,this.lastLimboFreeSnapshotVersion=r,this.query=o}}br.store="targets",br.keyPath="targetId",br.queryTargetsIndexName="queryTargetsIndex",br.queryTargetsKeyPath=["canonicalId","targetId"];class vr{constructor(t,e,s){this.targetId=t,this.path=e,this.sequenceNumber=s,p(0===t==(void 0!==s),"A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number")}}vr.store="targetDocuments",vr.keyPath=["targetId","path"],vr.documentTargetsIndex="documentTargetsIndex",vr.documentTargetsKeyPath=["path","targetId"];class Sr{constructor(t,e,s,n){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=s,this.targetCount=n}}Sr.key="targetGlobalKey",Sr.store="targetGlobal";class Dr{constructor(t,e){this.collectionId=t,this.parent=e}}function Cr(t){t.createObjectStore(vr.store,{keyPath:vr.keyPath}).createIndex(vr.documentTargetsIndex,vr.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(br.store,{keyPath:br.keyPath}).createIndex(br.queryTargetsIndexName,br.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(Sr.store)}Dr.store="collectionParents",Dr.keyPath=["collectionId","parent"];class kr{constructor(t,e,s,n){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=s,this.inForeground=n}}kr.store="clientMetadata",kr.keyPath="clientId";const Nr=[...[...[...[Rr.store,Ar.store,Pr.store,gr.store,br.store,Ir.store,Sr.store,vr.store],kr.store],yr.store],Dr.store];class Fr{constructor(){this._m=new mr}Nf(t,e){if(p(e.length%2==1,"Expected a collection path."),!this._m.has(e)){const s=e.st(),n=e.Z();t.ro(()=>{this._m.add(e)});const i={collectionId:s,parent:Li(n)};return $r(t).put(i)}return Us.resolve()}Ao(t,e){const s=[],n=IDBKeyRange.bound([e,""],[v(e),""],!1,!0);return $r(t).Pf(n).next(t=>{for(const n of t){if(n.collectionId!==e)break;s.push(Oi(n.parent))}return s})}}function $r(t){return jr.df(t,Dr.store)}class xr{constructor(t){this.dm=t}im(t){if(t.document)return this.dm.bi(t.document,!!t.hasCommittedMutations);if(t.noDocument){const e=Pt.Tt(t.noDocument.path),s=this.fm(t.noDocument.readTime);return new de(e,s,{hasCommittedMutations:!!t.hasCommittedMutations})}if(t.unknownDocument){const e=Pt.Tt(t.unknownDocument.path),s=this.fm(t.unknownDocument.version);return new fe(e,s)}return V("Unexpected DbRemoteDocument")}cm(t,e){const s=this.nm(e),n=t.key.path.Z().rt();if(t instanceof _e){const e=t.proto?t.proto:this.dm.yi(t),i=t.hasCommittedMutations;return new gr(null,null,e,i,s,n)}if(t instanceof de){const e=t.key.path.rt(),i=this.mm(t.version),r=t.hasCommittedMutations;return new gr(null,new Vr(e,i),null,r,s,n)}if(t instanceof fe){const e=t.key.path.rt(),i=this.mm(t.version);return new gr(new pr(e,i),null,null,!0,s,n)}return V("Unexpected MaybeDocument")}nm(t){const e=t.G();return[e.seconds,e.nanoseconds]}rm(t){const e=new mt(t[0],t[1]);return Tt.W(e)}mm(t){const e=t.G();return new wr(e.seconds,e.nanoseconds)}fm(t){const e=new mt(t.seconds,t.nanoseconds);return Tt.W(e)}kf(t,e){const s=e.baseMutations.map(t=>this.dm.xi(t)),n=e.mutations.map(t=>this.dm.xi(t));return new Ar(t,e.batchId,e.Qe.toMillis(),s,n)}Ff(t){const e=(t.baseMutations||[]).map(t=>this.dm.qi(t)),s=t.mutations.map(t=>this.dm.qi(t)),n=mt.fromMillis(t.localWriteTimeMs);return new Ls(t.batchId,n,e,s)}Tm(t){const e=[];return t.forEach(t=>{e.push(Li(t.path))}),e}Em(t){let e=es();for(const s of t)e=e.add(new Pt(Oi(s)));return e}zf(t){const e=this.fm(t.readTime),s=void 0!==t.lastLimboFreeSnapshotVersion?this.fm(t.lastLimboFreeSnapshotVersion):Tt.MIN,n=t.resumeToken;let i;return i=void 0!==t.query.documents?this.dm.Ki(t.query):this.dm.Xi(t.query),new Ue(i,t.targetId,Le.ks,t.lastListenSequenceNumber,e,s,n)}Kf(t){p(Le.ks===t.$s,"Only queries with purpose "+Le.ks+" may be stored, got "+t.$s);const e=this.mm(t.xs),s=this.mm(t.lastLimboFreeSnapshotVersion);let n,i;return n=t.target.Xe()?this.dm.zi(t.target):this.dm.Gi(t.target),t.resumeToken instanceof Uint8Array?(p(Wi.cf(),"Persisting non-string stream tokens is only supported with mock persistence ."),i=t.resumeToken.toString()):i=t.resumeToken,new br(t.targetId,t.target.canonicalId(),e,i,t.sequenceNumber,s,n)}}const Mr="IndexedDbPersistence",Lr=18e5,Br=5e3,qr=4e3,Or="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.",Ur="This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.",Qr="firestore_zombie";class Wr extends js{constructor(t,e){super(),this.xf=t,this.qa=e}}class jr{constructor(t,e,s,n,i,r,o,h){if(this.allowTabSynchronization=t,this.persistenceKey=e,this.clientId=s,this.Wu=r,this.wm=h,this.Im=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Rm=null,this.inForeground=!1,this.Am=null,this.Pm=null,this.Vm=Number.NEGATIVE_INFINITY,this.pm=t=>Promise.resolve(),this.oa=new Gr(this,i),this.gm=e+jr.ym,this.serializer=new xr(o),this.document=n.document,this.ca=new ir(this.oa,this.serializer),this.uo=new Fr,this.ho=new ur(this.serializer,this.uo),!n.window||!n.window.localStorage)throw new L(M.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=n.window,this.bm=this.window.localStorage}static df(t,e){if(t instanceof Wr)return Wi.df(t.xf,e);throw V("IndexedDbPersistence must use instances of IndexedDbTransaction")}static async vm(t){if(!jr.Zl())throw new L(M.UNIMPLEMENTED,Ur);const e=new jr(t.allowTabSynchronization,t.persistenceKey,t.clientId,t.platform,t.Sm,t.Wu,t.serializer,t.wm);return await e.start(),e}start(){return p(!this.Uh,"IndexedDbPersistence double-started!"),p(null!==this.window,"Expected 'window' to be defined"),Wi.uf(this.gm,Tr,new Er(this.serializer)).then(t=>(this.Dm=t,this.Cm())).then(()=>(this.km(),this.Nm(),this.Fm(),this.Dm.runTransaction("readonly-idempotent",[Sr.store],t=>hr(t)))).then(t=>{this.$m=new Gs(t,this.wm)}).then(()=>{this.Im=!0}).catch(t=>(this.Dm&&this.Dm.close(),Promise.reject(t)))}xm(t){return this.pm=async e=>{if(this.Uh)return t(e)},t(this.isPrimary)}Mm(t){this.Dm.ff(async e=>{null===e.newVersion&&await t()})}au(t){this.networkEnabled!==t&&(this.networkEnabled=t,this.Wu.Yo(async()=>{this.Uh&&await this.Cm()}))}Cm(){return this.Dm.runTransaction("readwrite-idempotent",Nr,t=>{return Kr(t).put(new kr(this.clientId,Date.now(),this.networkEnabled,this.inForeground)).next(()=>{if(this.isPrimary)return this.Lm(t).next(t=>{t||(this.isPrimary=!1,this.Wu.Yo(()=>this.pm(!1)))})}).next(()=>this.Bm(t)).next(e=>this.isPrimary&&!e?this.qm(t).next(()=>!1):!!e&&this.Om(t).next(()=>!0))}).catch(t=>{if(!this.allowTabSynchronization)throw t;return R(Mr,"Releasing owner lease after error during lease refresh",t),!1}).then(t=>{this.isPrimary!==t&&this.Wu.Yo(()=>this.pm(t)),this.isPrimary=t})}Lm(t){return zr(t).get(Ir.key).next(t=>Us.resolve(this.Um(t)))}Qm(t){return Kr(t).delete(this.clientId)}async Wm(){if(this.isPrimary&&!this.jm(this.Vm,Lr)){this.Vm=Date.now(),(await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary-idempotent",t=>{const e=jr.df(t,kr.store);return e.Pf().next(t=>{const s=this.zm(t,Lr),n=t.filter(t=>-1===s.indexOf(t));return Us.forEach(n,t=>e.delete(t.clientId)).next(()=>n)})}).catch(()=>[])).forEach(t=>{this.window.localStorage.removeItem(this.Km(t.clientId))})}}Fm(){this.Pm=this.Wu.lh(Js.Bo,qr,()=>this.Cm().then(()=>this.Wm()).then(()=>this.Fm()))}Um(t){return!!t&&t.ownerId===this.clientId}Bm(t){return zr(t).get(Ir.key).next(e=>{if(null!==e&&this.jm(e.leaseTimestampMs,Br)&&!this.Gm(e.ownerId)){if(this.Um(e)&&this.networkEnabled)return!0;if(!this.Um(e)){if(!e.allowTabSynchronization)throw new L(M.FAILED_PRECONDITION,Or);return!1}}return!(!this.networkEnabled||!this.inForeground)||Kr(t).Pf().next(t=>{return void 0===this.zm(t,Br).find(t=>{if(this.clientId!==t.clientId){const e=!this.networkEnabled&&t.networkEnabled,s=!this.inForeground&&t.inForeground,n=this.networkEnabled===t.networkEnabled;if(e||s&&n)return!0}return!1})})}).next(t=>(this.isPrimary!==t&&R(Mr,`Client ${t?"is":"is not"} eligible for a primary lease.`),t))}async pl(){this.Im=!1,this.Hm(),this.Pm&&(this.Pm.cancel(),this.Pm=null),this.Jm(),this.Ym(),await this.Dm.runTransaction("readwrite-idempotent",[Ir.store,kr.store],t=>this.qm(t).next(()=>this.Qm(t))),this.Dm.close(),this.Xm()}zm(t,e){return t.filter(t=>this.jm(t.updateTimeMs,e)&&!this.Gm(t.clientId))}ru(){return this.Dm.runTransaction("readonly-idempotent",[kr.store],t=>Kr(t).Pf().next(t=>this.zm(t,Lr).map(t=>t.clientId)))}static async clearPersistence(t){if(!jr.Zl())return Promise.resolve();const e=t+jr.ym;await Wi.delete(e)}get Uh(){return this.Im}ha(t){return p(this.Uh,"Cannot initialize MutationQueue before persistence is started."),Yi.Sf(t,this.serializer,this.uo,this.oa)}la(){return p(this.Uh,"Cannot initialize TargetCache before persistence is started."),this.ca}ua(){return p(this.Uh,"Cannot initialize RemoteDocumentCache before persistence is started."),this.ho}da(){return p(this.Uh,"Cannot initialize IndexManager before persistence is started."),this.uo}runTransaction(t,e,s){R(Mr,"Starting transaction:",t);const n=e.endsWith("idempotent"),i=e.startsWith("readonly")?n?"readonly-idempotent":"readonly":n?"readwrite-idempotent":"readwrite";let r;return this.Dm.runTransaction(i,Nr,n=>(r=new Wr(n,this.$m.next()),"readwrite-primary"===e||"readwrite-primary-idempotent"===e?this.Lm(n).next(t=>!!t||this.Bm(n)).next(e=>{if(!e)throw A(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Wu.Yo(()=>this.pm(!1)),new L(M.FAILED_PRECONDITION,Ws);return s(r)}).next(t=>this.Om(n).next(()=>t)):this.Zm(n).next(()=>s(r)))).then(t=>(r.oo(),t))}Zm(t){return zr(t).get(Ir.key).next(t=>{if(null!==t&&this.jm(t.leaseTimestampMs,Br)&&!this.Gm(t.ownerId)&&!this.Um(t)&&!t.allowTabSynchronization)throw new L(M.FAILED_PRECONDITION,Or)})}Om(t){const e=new Ir(this.clientId,this.allowTabSynchronization,Date.now());return zr(t).put(Ir.key,e)}static Zl(){return Wi.Zl()}static tT(t){let e=t.o.projectId;return t.o.h||(e+="."+t.o.database),"firestore/"+t.persistenceKey+"/"+e+"/"}qm(t){const e=zr(t);return e.get(Ir.key).next(t=>this.Um(t)?(R(Mr,"Releasing primary lease."),e.delete(Ir.key)):Us.resolve())}jm(t,e){const s=Date.now();return!(t<s-e)&&(!(t>s)||(A(`Detected an update time that is in the future: ${t} > ${s}`),!1))}km(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Am=()=>{this.Wu.Yo(()=>(this.inForeground="visible"===this.document.visibilityState,this.Cm()))},this.document.addEventListener("visibilitychange",this.Am),this.inForeground="visible"===this.document.visibilityState)}Jm(){this.Am&&(p(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.Am),this.Am=null)}Nm(){"function"==typeof this.window.addEventListener&&(this.Rm=()=>{this.Hm(),this.Wu.Yo(()=>this.pl())},this.window.addEventListener("unload",this.Rm))}Ym(){this.Rm&&(p("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.Rm),this.Rm=null)}Gm(t){try{const e=null!==this.bm.getItem(this.Km(t));return R(Mr,`Client '${t}' ${e?"is":"is not"} zombied in LocalStorage`),e}catch(t){return A(Mr,"Failed to get zombied client id.",t),!1}}Hm(){try{this.bm.setItem(this.Km(this.clientId),String(Date.now()))}catch(t){A("Failed to set zombie client id.",t)}}Xm(){try{this.bm.removeItem(this.Km(this.clientId))}catch(t){}}Km(t){return`${Qr}_${this.persistenceKey}_${t}`}}function zr(t){return t.store(Ir.store)}function Kr(t){return t.store(kr.store)}jr.ym="main";class Gr{constructor(t,e){this.db=t,this.eT=null,this.xh=new an(this,e)}zh(t){const e=this.sT(t);return this.db.la().Gf(t).next(t=>e.next(e=>t+e))}sT(t){let e=0;return this.Gh(t,t=>{e++}).next(()=>e)}Un(t,e){return this.db.la().Un(t,e)}Gh(t,e){return this.nT(t,(t,s)=>e(s))}ra(t){this.eT=t}vr(t,e){return Hr(t,e)}Dr(t,e){return Hr(t,e)}Hh(t,e,s){return this.db.la().Hh(t,e,s)}Mf(t,e){return Hr(t,e)}iT(t,e){return this.eT.xr(e)?Us.resolve(!0):function(t,e){let s=!1;return nr(t).bf(n=>Xi(t,n,e).next(t=>(t&&(s=!0),Us.resolve(!t)))).next(()=>s)}(t,e)}Jh(t,e){const s=this.db.ua().ya(),n=[];let i=0;return this.nT(t,(r,o)=>{if(o<=e){const e=this.iT(t,r).next(e=>{if(!e)return i++,s.to(t,r).next(()=>(s.Zr(r),ar(t).delete(function(t){return[0,Li(t.path)]}(r))))});n.push(e)}}).next(()=>Us.zr(n)).next(()=>s.apply(t)).next(()=>i)}removeTarget(t,e){const s=e.Ms(t.qa);return this.db.la().Ua(t,s)}Qa(t,e){return Hr(t,e)}nT(t,e){const s=ar(t);let n,i=Gs.ko;return s.yf({index:vr.documentTargetsIndex},([t,s],{path:r,sequenceNumber:o})=>{0===t?(i!==Gs.ko&&e(new Pt(Oi(n)),i),i=o,n=r):i=Gs.ko}).next(()=>{i!==Gs.ko&&e(new Pt(Oi(n)),i)})}Xh(t){return this.db.ua().hm(t)}}function Hr(t,e){return ar(t).put(function(t,e){return new vr(0,Li(t.path),e)}(e,t.qa))}class Jr{fa(t){this.rT=t}Eo(t,e,s,n){return p(void 0!==this.rT,"setLocalDocumentsView() not called"),e.ws()?this.oT(t,e):s.isEqual(Tt.MIN)?this.oT(t,e):this.rT.fo(t,n).next(i=>{const r=this.hT(e,i);return(e.gs()||e.ys())&&this.X_(e.ss,r,n,s)?this.oT(t,e):(w()<=E.DEBUG&&R("IndexFreeQueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),e.toString()),this.rT.Eo(t,e,s).next(t=>(r.forEach(e=>{t=t.wt(e.key,e)}),t)))})}hT(t,e){let s=new yt((e,s)=>t.Rs(e,s));return e.forEach((e,n)=>{n instanceof _e&&t.matches(n)&&(s=s.add(n))}),s}X_(t,e,s,n){if(s.size!==e.size)return!0;const i=t===Pe.Ze?e.last():e.first();return!!i&&(i.hasPendingWrites||i.version.u(n)>0)}oT(t,e){return w()<=E.DEBUG&&R("IndexFreeQueryEngine","Using full collection scan to execute query: %s",e.toString()),this.rT.Eo(t,e,Tt.MIN)}}class Yr{constructor(t,e){this.uo=t,this.oa=e,this.ao=[],this.aT=1,this.lastStreamToken=Ds(),this.uT=new yt(Os.ze)}Df(t){return Us.resolve(0===this.ao.length)}ga(t,e,s){const n=e.batchId,i=this.cT(n,"acknowledged");p(0===i,"Can only acknowledge the first batch in the mutation queue");const r=this.ao[i];return p(n===r.batchId,"Queue ordering failure: expected batch "+n+", got batch "+r.batchId),this.lastStreamToken=s,Us.resolve()}Fa(t){return Us.resolve(this.lastStreamToken)}$a(t,e){return this.lastStreamToken=e,Us.resolve()}Pa(t,e,s,n){p(0!==n.length,"Mutation batches should not be empty");const i=this.aT;if(this.aT++,this.ao.length>0){p(this.ao[this.ao.length-1].batchId<i,"Mutation batchIDs must be monotonically increasing order")}const r=new Ls(i,e,s,n);this.ao.push(r);for(const e of n)this.uT=this.uT.add(new Os(e.key,i)),this.uo.Nf(t,e.key.path.Z());return Us.resolve(r)}Ca(t,e){return Us.resolve(this.lT(e))}pa(t,e){const s=this.lT(e);return p(null!=s,"Failed to find local mutation batch."),Us.resolve(s.keys())}Ga(t,e){const s=e+1,n=this._T(s),i=n<0?0:n;return Us.resolve(this.ao.length>i?this.ao[i]:null)}Na(){return Us.resolve(0===this.ao.length?Ms:this.aT-1)}Ea(t){return Us.resolve(this.ao.slice())}lo(t,e){const s=new Os(e,0),n=new Os(e,Number.POSITIVE_INFINITY),i=[];return this.uT.jt([s,n],t=>{p(e.isEqual(t.key),"Should only iterate over a single key's batches");const s=this.lT(t.Mr);p(null!==s,"Batches in the index must exist in the main table"),i.push(s)}),Us.resolve(i)}To(t,e){let s=new yt(y);return e.forEach(t=>{const e=new Os(t,0),n=new Os(t,Number.POSITIVE_INFINITY);this.uT.jt([e,n],e=>{p(t.isEqual(e.key),"For each key, should only iterate over a single key's batches"),s=s.add(e.Mr)})}),Us.resolve(this.dT(s))}Po(t,e){p(!e.vs(),"CollectionGroup queries should be handled in LocalDocumentsView");const s=e.path,n=s.length+1;let i=s;Pt.dt(i)||(i=i.child(""));const r=new Os(new Pt(i),0);let o=new yt(y);return this.uT.zt(t=>{const e=t.key.path;return!!s.nt(e)&&(e.length===n&&(o=o.add(t.Mr)),!0)},r),Us.resolve(this.dT(o))}dT(t){const e=[];return t.forEach(t=>{const s=this.lT(t);null!==s&&e.push(s)}),e}ka(t,e){p(0===this.cT(e.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.ao.shift();let s=this.uT;return Us.forEach(e.mutations,n=>{const i=new Os(n.key,e.batchId);return s=s.delete(i),this.oa.Mf(t,n.key)}).next(()=>{this.uT=s})}hu(t){}xr(t,e){const s=new Os(e,0),n=this.uT.Kt(s);return Us.resolve(e.isEqual(n&&n.key))}Sa(t){return 0===this.ao.length&&p(this.uT.tt(),"Document leak -- detected dangling mutation references when queue is empty."),Us.resolve()}cT(t,e){const s=this._T(t);return p(s>=0&&s<this.ao.length,"Batches must exist to be "+e),s}_T(t){if(0===this.ao.length)return 0;return t-this.ao[0].batchId}lT(t){const e=this._T(t);if(e<0||e>=this.ao.length)return null;const s=this.ao[e];return p(s.batchId===t,"If found batch must match"),s}}class Xr{constructor(t,e){this.uo=t,this.fT=e,this.docs=new Vt(Pt.J),this.size=0}Yr(t,e,s){p(!s.isEqual(Tt.MIN),"Cannot add a document with a read time of zero");const n=e.key,i=this.docs.get(n),r=i?i.size:0,o=this.fT(e);return this.docs=this.docs.wt(n,{Xf:e,size:o,readTime:s}),this.size+=o-r,this.uo.Nf(t,n.path.Z())}Zr(t){const e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)}to(t,e){const s=this.docs.get(e);return Us.resolve(s?s.Xf:null)}getEntries(t,e){let s=He();return e.forEach(t=>{const e=this.docs.get(t);s=s.wt(t,e?e.Xf:null)}),Us.resolve(s)}Eo(t,e,s){p(!e.vs(),"CollectionGroup queries should be handled in LocalDocumentsView");let n=Ye();const i=new Pt(e.path.child("")),r=this.docs.yt(i);for(;r.kt();){const{key:t,value:{Xf:i,readTime:o}}=r.Ct();if(!e.path.nt(t.path))break;o.u(s)<=0||i instanceof _e&&e.matches(i)&&(n=n.wt(i.key,i))}return Us.resolve(n)}mT(t,e){return Us.forEach(this.docs,t=>e(t))}cu(t,e){throw new Error("getNewDocumentChanges() is not supported with MemoryPersistence")}_u(t){return Us.resolve(Tt.MIN)}ya(t){return new Xr.om(this)}hm(t){return Us.resolve(this.size)}}Xr.om=class extends Qs{constructor(t){super(),this.am=t}no(t){const e=[];return this.Gr.forEach((s,n)=>{n?e.push(this.am.Yr(t,n,this.readTime)):this.am.Zr(s)}),Us.zr(e)}eo(t,e){return this.am.to(t,e)}so(t,e){return this.am.getEntries(t,e)}};class Zr{constructor(t){this.persistence=t,this.TT=new xs(t=>t.canonicalId()),this.lastRemoteSnapshotVersion=Tt.MIN,this.highestTargetId=0,this.ET=0,this.wT=new qs,this.targetCount=0,this.Lf=Ai.U_()}Un(t,e){return this.TT.forEach((t,s)=>e(s)),Us.resolve()}xa(t){return Us.resolve(this.lastRemoteSnapshotVersion)}Of(t){return Us.resolve(this.ET)}Xa(t){const e=this.Lf.after(this.highestTargetId);return this.highestTargetId=e,Us.resolve(e)}Wa(t,e,s){return s&&(this.lastRemoteSnapshotVersion=s),e>this.ET&&(this.ET=e),Us.resolve()}Uf(t){this.TT.set(t.target,t);const e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e),t.sequenceNumber>this.ET&&(this.ET=t.sequenceNumber)}Za(t,e){return p(!this.TT.has(e.target),"Adding a target that already exists"),this.Uf(e),this.targetCount+=1,Us.resolve()}Ua(t,e){return p(this.TT.has(e.target),"Updating a non-existent target"),this.Uf(e),Us.resolve()}Wf(t,e){return p(this.targetCount>0,"Removing a target from an empty cache"),p(this.TT.has(e.target),"Removing a non-existent target from the cache"),this.TT.delete(e.target),this.wT.Nr(e.targetId),this.targetCount-=1,Us.resolve()}Hh(t,e,s){let n=0;const i=[];return this.TT.forEach((r,o)=>{o.sequenceNumber<=e&&null===s.get(o.targetId)&&(this.TT.delete(r),i.push(this.jf(t,o.targetId)),n++)}),Us.zr(i).next(()=>n)}Gf(t){return Us.resolve(this.targetCount)}Ya(t,e){const s=this.TT.get(e)||null;return Us.resolve(s)}Zn(t,e){return V("Not yet implemented.")}Ba(t,e,s){this.wT.Sr(e,s);const n=this.persistence.oa,i=[];return n&&e.forEach(e=>{i.push(n.vr(t,e))}),Us.zr(i)}La(t,e,s){this.wT.kr(e,s);const n=this.persistence.oa,i=[];return n&&e.forEach(e=>{i.push(n.Dr(t,e))}),Us.zr(i)}jf(t,e){return this.wT.Nr(e),Us.resolve()}su(t,e){const s=this.wT.$r(e);return Us.resolve(s)}xr(t,e){return Us.resolve(this.wT.xr(e))}}const to="MemoryPersistence";class eo{constructor(t,e){this.clientId=t,this.IT={},this.$m=new Gs(0),this.Im=!1,this.Im=!0,this.oa=e(this),this.ca=new Zr(this);this.uo=new fr,this.ho=new Xr(this.uo,t=>this.oa.RT(t))}static AT(t,e){return new eo(t,t=>new io(t,e))}static PT(t){return new eo(t,t=>new no(t))}pl(){return this.Im=!1,Promise.resolve()}get Uh(){return this.Im}async ru(){return[this.clientId]}xm(t){return t(!0)}Mm(){}au(t){}da(){return this.uo}ha(t){let e=this.IT[t.A()];return e||(e=new Yr(this.uo,this.oa),this.IT[t.A()]=e),e}la(){return this.ca}ua(){return this.ho}runTransaction(t,e,s){R(to,"Starting transaction:",t);const n=new so(this.$m.next());return this.oa.VT(),s(n).next(t=>this.oa.pT(n).next(()=>t)).Wr().then(t=>(n.oo(),t))}gT(t,e){return Us.Kr(function(t){const e=[];return K(t,(t,s)=>e.push(s)),e}(this.IT).map(s=>()=>s.xr(t,e)))}}class so extends js{constructor(t){super(),this.qa=t}}class no{constructor(t){this.persistence=t,this.eT=null,this.yT=null}get bT(){if(this.yT)return this.yT;throw V("orphanedDocuments is only valid during a transaction.")}ra(t){this.eT=t}vr(t,e){return this.bT.delete(e),Us.resolve()}Dr(t,e){return this.bT.add(e),Us.resolve()}Mf(t,e){return this.bT.add(e),Us.resolve()}removeTarget(t,e){const s=this.persistence.la();return s.su(t,e.targetId).next(t=>{t.forEach(t=>this.bT.add(t))}).next(()=>s.Wf(t,e))}VT(){this.yT=new Set}pT(t){const e=this.persistence.ua().ya();return Us.forEach(this.bT,s=>this.vT(t,s).next(t=>{t||e.Zr(s)})).next(()=>(this.yT=null,e.apply(t)))}Qa(t,e){return this.vT(t,e).next(t=>{t?this.bT.delete(e):this.bT.add(e)})}RT(t){return 0}vT(t,e){return Us.Kr([()=>this.persistence.la().xr(t,e),()=>this.persistence.gT(t,e),()=>Us.resolve(this.eT.xr(e))])}}class io{constructor(t,e){this.persistence=t,this.eT=null,this.ST=new xs(t=>Li(t.path)),this.xh=new an(this,e)}VT(){}pT(t){return Us.resolve()}Un(t,e){return this.persistence.la().Un(t,e)}zh(t){const e=this.DT(t);return this.persistence.la().Gf(t).next(t=>e.next(e=>t+e))}DT(t){let e=0;return this.Gh(t,t=>{e++}).next(()=>e)}Gh(t,e){return Us.forEach(this.ST,(s,n)=>this.iT(t,s,n).next(t=>t?Us.resolve():e(n)))}ra(t){this.eT=t}Hh(t,e,s){return this.persistence.la().Hh(t,e,s)}Jh(t,e){let s=0;const n=this.persistence.ua(),i=n.ya();return n.mT(t,n=>this.iT(t,n,e).next(t=>{t||(s++,i.Zr(n))})).next(()=>i.apply(t)).next(()=>s)}Mf(t,e){return this.ST.set(e,t.qa),Us.resolve()}removeTarget(t,e){const s=e.Ms(t.qa);return this.persistence.la().Ua(t,s)}vr(t,e){return this.ST.set(e,t.qa),Us.resolve()}Dr(t,e){return this.ST.set(e,t.qa),Us.resolve()}Qa(t,e){return this.ST.set(e,t.qa),Us.resolve()}RT(t){let e=t.key.toString().length;return t instanceof _e&&(e+=t.data().Le()),e}iT(t,e,s){return Us.Kr([()=>this.persistence.gT(t,e),()=>Us.resolve(this.eT.xr(e)),()=>this.persistence.la().xr(t,e),()=>{const t=this.ST.get(e);return Us.resolve(void 0!==t&&t>s)}])}Xh(t){return this.persistence.ua().hm(t)}}const ro="FirestoreClient",oo=11,ho=20,ao=22;class uo{constructor(t,e){this.cacheSizeBytes=t,this.synchronizeTabs=e}Sm(){return nn.Sh(this.cacheSizeBytes)}}class co{}class lo{constructor(t,e,s,n){this.platform=t,this.CT=e,this.credentials=s,this.Uo=n,this.clientId=g.i()}start(t){this.kT();const e=new Hs,s=new Hs;let n=!1;return this.credentials.S(i=>{n?this.Uo.Yo(()=>this.Ul(i)):(n=!0,this.NT(t,s,i).then(t=>this.FT(i,t)).then(e.resolve,e.reject))}),this.Uo.Yo(()=>e.promise),s.promise}enableNetwork(){return this.kT(),this.Uo.enqueue(()=>this.vl.enableNetwork())}NT(t,e,s){return t instanceof uo?this.$T(s,t).then(t=>(e.resolve(),t)).catch(t=>{if(e.reject(t),!this.xT(t))throw t;return console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+t),this.MT()}):(e.resolve(),this.MT())}xT(t){return t instanceof L?t.code===M.FAILED_PRECONDITION||t.code===M.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(t.code===ao||t.code===ho||t.code===oo)}kT(){if(this.Uo.ih)throw new L(M.FAILED_PRECONDITION,"The client has already been terminated.")}$T(t,e){const s=jr.tT(this.CT),n=new vs(this.CT.o,{ei:!0});return Promise.resolve().then(async()=>{if(e.synchronizeTabs&&!Ti.Zl(this.platform))throw new L(M.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const i=e.Sm();this.Td=e.synchronizeTabs?new Ti(this.Uo,this.platform,s,this.clientId,t):new Ei;const r=await jr.vm({allowTabSynchronization:e.synchronizeTabs,persistenceKey:s,clientId:this.clientId,platform:this.platform,Wu:this.Uo,serializer:n,Sm:i,wm:this.Td});return this.persistence=r,r.oa.xh})}MT(){return this.persistence=eo.PT(this.clientId),this.Td=new Ei,Promise.resolve(null)}FT(t,e){return R(ro,"Initializing. user=",t.uid),this.platform.LT(this.CT).then(async s=>{const n=new Jr;this.Mh=new cn(this.persistence,n,t),await this.Mh.start(),e&&(this.BT=new hn(e,this.Uo,this.Mh));const i=this.platform.qT(),r=this.platform.OT(this.CT.o),o=new Kn(this.Uo,s,this.credentials,r);this.hd=new ei(this.Mh,o,this.Uo,t=>this.vl.sd(t,F.T),i),this.vl=new Di(this.Mh,this.hd,this.Td,t),this.Td.Gc=t=>this.vl.sd(t,F.I),this.hd.vl=this.vl,this.Td.vl=this.vl,this.UT=new ki(this.vl),await this.Td.start(),await this.hd.start(),await this.persistence.xm(async t=>{await this.vl.Ql(t),this.BT&&(t&&!this.BT.Uh?this.BT.start():t||this.BT.stop())}),await this.persistence.Mm(async()=>{await this.terminate()})})}Ul(t){return this.Uo.dh(),R(ro,"Credential Changed. Current user: "+t.uid),this.vl.Ul(t)}disableNetwork(){return this.kT(),this.Uo.enqueue(()=>this.vl.disableNetwork())}terminate(){return this.Uo.uh(async()=>{this.BT&&this.BT.stop(),await this.hd.pl(),await this.Td.pl(),await this.persistence.pl(),this.credentials.D()})}waitForPendingWrites(){this.kT();const t=new Hs;return this.Uo.Yo(()=>this.vl.Md(t)),t.promise}listen(t,e,s){this.kT();const n=new Ni(t,e,s);return this.Uo.Yo(()=>this.UT.listen(n)),n}yl(t){this.QT||this.Uo.Yo(()=>this.UT.yl(t))}WT(t){return this.kT(),this.Uo.enqueue(()=>this.Mh.Ha(t)).then(t=>{if(t instanceof _e)return t;if(t instanceof de)return null;throw new L(M.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")})}jT(t){return this.kT(),this.Uo.enqueue(async()=>{const e=await this.Mh.eu(t,!0),s=new pi(t,e.nu),n=s.H_(e.documents);return s.no(n,!1).snapshot})}write(t){this.kT();const e=new Hs;return this.Uo.Yo(()=>this.vl.write(t,e)),e.promise}o(){return this.CT.o}Xd(t){this.kT(),this.Uo.Yo(()=>(this.UT.Xd(t),Promise.resolve()))}Zd(t){this.QT||this.UT.Zd(t)}get QT(){return this.Uo.ih}transaction(t){this.kT();const e=new Hs;return this.Uo.Yo(()=>(this.vl.runTransaction(this.Uo,t,e),Promise.resolve())),e.promise}}class _o{constructor(t){this.observer=t,this.muted=!1}next(t){this.zT(this.observer.next,t)}error(t){this.zT(this.observer.error,t)}KT(){this.muted=!0}zT(t,e){this.muted||setTimeout(()=>{this.muted||t(e)},0)}}function fo(t){return function(t,e){if("object"!=typeof t||null===t)return!1;const s=t;for(const t of e)if(t in s&&"function"==typeof s[t])return!0;return!1}(t,["next","error","complete"])}const mo="firestore.googleapis.com",To=!0,Eo=!0,wo=!1,Io=nn.kh,Ro=!1;class Ao{constructor(t){if(void 0===t.host){if(void 0!==t.ssl)throw new L(M.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=mo,this.ssl=To}else et("settings","non-empty string","host",t.host),this.host=t.host,st("settings","boolean","ssl",t.ssl),this.ssl=j(t.ssl,To);if(ut("settings",t,["host","ssl","credentials","timestampsInSnapshots","cacheSizeBytes","experimentalForceLongPolling"]),st("settings","object","credentials",t.credentials),this.credentials=t.credentials,st("settings","boolean","timestampsInSnapshots",t.timestampsInSnapshots),!0===t.timestampsInSnapshots?A("\n  The timestampsInSnapshots setting now defaults to true and you no\n  longer need to explicitly set it. In a future release, the setting\n  will be removed entirely and so it is recommended that you remove it\n  from your firestore.settings() call now."):!1===t.timestampsInSnapshots&&A("\n  The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\n  YOUR CODE.\n\n  To hide this warning, stop using the timestampsInSnapshots setting in your\n  firestore.settings({ ... }) call.\n\n  Once you remove the setting, Timestamps stored in Cloud Firestore will be\n  read back as Firebase Timestamp objects instead of as system Date objects.\n  So you will also need to update code expecting a Date to instead expect a\n  Timestamp. For example:\n\n  // Old:\n  const date = snapshot.get('created_at');\n  // New:\n  const timestamp = snapshot.get('created_at'); const date =\n  timestamp.toDate();\n\n  Please audit all existing usages of Date when you enable the new\n  behavior."),this.timestampsInSnapshots=j(t.timestampsInSnapshots,Eo),st("settings","number","cacheSizeBytes",t.cacheSizeBytes),void 0===t.cacheSizeBytes)this.cacheSizeBytes=nn.Fh;else{if(t.cacheSizeBytes!==Io&&t.cacheSizeBytes<nn.Nh)throw new L(M.INVALID_ARGUMENT,`cacheSizeBytes must be at least ${nn.Nh}`);this.cacheSizeBytes=t.cacheSizeBytes}st("settings","boolean","experimentalForceLongPolling",t.experimentalForceLongPolling),this.forceLongPolling=void 0===t.experimentalForceLongPolling?wo:t.experimentalForceLongPolling}isEqual(t){return this.host===t.host&&this.ssl===t.ssl&&this.timestampsInSnapshots===t.timestampsInSnapshots&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes&&this.forceLongPolling===t.forceLongPolling}}class Po{constructor(t,e){if(this.GT=null,this.HT=new Zs,this.INTERNAL={delete:async()=>{this.JT(),await this.YT.terminate()}},"object"==typeof t.options){const s=t;this.GT=s,this.XT=Po.ZT(s),this.tE=s.name,this.eE=new O(e)}else{const e=t;if(!e.projectId)throw new L(M.INVALID_ARGUMENT,"Must provide projectId");this.XT=new C(e.projectId,e.database),this.tE="[DEFAULT]",this.eE=new q}this.sE=new Ao({}),this.nE=this.iE(this.XT)}settings(t){if(J("Firestore.settings",arguments,1),Z("Firestore.settings","object",1,t),W(t,"persistence"))throw new L(M.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');const e=new Ao(t);if(this.YT&&!this.sE.isEqual(e))throw new L(M.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");this.sE=e,void 0!==e.credentials&&(this.eE=function(t){if(!t)return new q;switch(t.type){case"gapi":const e=t.rE;return p(!("object"!=typeof e||null===e||!e.auth||!e.auth.getAuthHeaderValueForFirstParty),"unexpected gapi interface"),new Q(e,t.M||"0");case"provider":return t.rE;default:throw new L(M.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}(e.credentials))}enableNetwork(){return this.JT(),this.YT.enableNetwork()}disableNetwork(){return this.JT(),this.YT.disableNetwork()}enablePersistence(t){if(this.YT)throw new L(M.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");let e=!1;return t&&(void 0!==t.experimentalTabSynchronization&&A("The 'experimentalTabSynchronization' setting has been renamed to 'synchronizeTabs'. In a future release, the setting will be removed and it is recommended that you update your firestore.enablePersistence() call to use 'synchronizeTabs'."),e=j(void 0!==t.synchronizeTabs?t.synchronizeTabs:t.experimentalTabSynchronization,Ro)),this.oE(new uo(this.sE.cacheSizeBytes,e))}clearPersistence(){const t=jr.tT(this.hE()),e=new Hs;return this.HT.rh(async()=>{try{if(void 0!==this.YT&&!this.YT.QT)throw new L(M.FAILED_PRECONDITION,"Persistence cannot be cleared after this Firestore instance is initialized.");await jr.clearPersistence(t),e.resolve()}catch(t){e.reject(t)}}),e.promise}terminate(){return this.app._removeServiceInstance("firestore"),this.INTERNAL.delete()}get aE(){return this.JT(),this.YT.QT}waitForPendingWrites(){return this.JT(),this.YT.waitForPendingWrites()}onSnapshotsInSync(t){if(this.JT(),fo(t))return this.uE(t);{Z("Firestore.onSnapshotsInSync","function",1,t);const e={next:t};return this.uE(e)}}uE(t){const e=new _o({next:()=>{t.next&&t.next()},error:t=>{throw V("Uncaught Error in onSnapshotsInSync")}});return this.YT.Xd(e),()=>{e.KT(),this.YT.Zd(e)}}JT(){return this.YT||this.oE(new co),this.YT}hE(){return new S(this.XT,this.tE,this.sE.host,this.sE.ssl,this.sE.forceLongPolling)}oE(t){p(!!this.sE.host,"FirestoreSettings.host is not set"),p(!this.YT,"configureClient() called multiple times");const e=this.hE();return this.YT=new lo(Ss.t(),e,this.eE,this.HT),this.YT.start(t)}iE(t){return new Sn(e=>{if(e instanceof go){const s=t,n=e.firestore.XT;if(!n.isEqual(s))throw new L(M.INVALID_ARGUMENT,"Document reference is for database "+`${n.projectId}/${n.database} but should be `+`for database ${s.projectId}/${s.database}`);return new vn(t,e.cE)}return e})}static ZT(t){const e=t.options;if(!W(e,"projectId"))throw new L(M.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');const s=e.projectId;if(!s||"string"!=typeof s)throw new L(M.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new C(s)}get app(){if(!this.GT)throw new L(M.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this.GT}collection(t){return J("Firestore.collection",arguments,1),Z("Firestore.collection","non-empty string",1,t),this.JT(),new Co(It.ht(t),this)}doc(t){return J("Firestore.doc",arguments,1),Z("Firestore.doc","non-empty string",1,t),this.JT(),go.lE(It.ht(t),this)}collectionGroup(t){if(J("Firestore.collectionGroup",arguments,1),Z("Firestore.collectionGroup","non-empty string",1,t),t.indexOf("/")>=0)throw new L(M.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function `+"Firestore.collectionGroup(). Collection IDs must not contain '/'.");return this.JT(),new So(new pe(It.at,t),this)}runTransaction(t){return J("Firestore.runTransaction",arguments,1),Z("Firestore.runTransaction","function",1,t),this.JT().transaction(e=>t(new Vo(this,e)))}batch(){return this.JT(),new po(this)}static get logLevel(){switch(w()){case E.DEBUG:return"debug";case E.ERROR:return"error";case E.SILENT:return"silent";default:return V("Unknown log level: "+w())}}static setLogLevel(t){switch(J("Firestore.setLogLevel",arguments,1),Z("Firestore.setLogLevel","non-empty string",1,t),t){case"debug":I(E.DEBUG);break;case"error":I(E.ERROR);break;case"silent":I(E.SILENT);break;default:throw new L(M.INVALID_ARGUMENT,"Invalid log level: "+t)}}_E(){return this.sE.timestampsInSnapshots}}class Vo{constructor(t,e){this.dE=t,this.fE=e}get(t){J("Transaction.get",arguments,1);const e=$o("Transaction.get",t,this.dE);return this.fE.Lc([e.cE]).then(t=>{if(!t||1!==t.length)return V("Mismatch in docs returned from document lookup.");const s=t[0];if(s instanceof de)return new bo(this.dE,e.cE,null,!1,!1,e.mE);if(s instanceof _e)return new bo(this.dE,e.cE,s,!1,!1,e.mE);throw V(`BatchGetDocumentsRequest returned unexpected document type: ${s.constructor.name}`)})}set(t,e,s){X("Transaction.set",arguments,2,3);const n=$o("Transaction.set",t,this.dE);s=ko("Transaction.set",s);const[i,r]=Mo(n.mE,e,"Transaction.set"),o=s.merge||s.mergeFields?this.dE.nE.Fu(r,i,s.mergeFields):this.dE.nE.ku(r,i);return this.fE.set(n.cE,o),this}update(t,e,s,...n){let i,r;return"string"==typeof e||e instanceof _n?(Y("Transaction.update",arguments,3),i=$o("Transaction.update",t,this.dE),r=this.dE.nE.Mu("Transaction.update",e,s,n)):(J("Transaction.update",arguments,2),i=$o("Transaction.update",t,this.dE),r=this.dE.nE.$u("Transaction.update",e)),this.fE.update(i.cE,r),this}delete(t){J("Transaction.delete",arguments,1);const e=$o("Transaction.delete",t,this.dE);return this.fE.delete(e.cE),this}}class po{constructor(t){this.dE=t,this.TE=[],this.EE=!1}set(t,e,s){X("WriteBatch.set",arguments,2,3),this.wE();const n=$o("WriteBatch.set",t,this.dE);s=ko("WriteBatch.set",s);const[i,r]=Mo(n.mE,e,"WriteBatch.set"),o=s.merge||s.mergeFields?this.dE.nE.Fu(r,i,s.mergeFields):this.dE.nE.ku(r,i);return this.TE=this.TE.concat(o.wu(n.cE,Ut.NONE)),this}update(t,e,s,...n){let i,r;return this.wE(),"string"==typeof e||e instanceof _n?(Y("WriteBatch.update",arguments,3),i=$o("WriteBatch.update",t,this.dE),r=this.dE.nE.Mu("WriteBatch.update",e,s,n)):(J("WriteBatch.update",arguments,2),i=$o("WriteBatch.update",t,this.dE),r=this.dE.nE.$u("WriteBatch.update",e)),this.TE=this.TE.concat(r.wu(i.cE,Ut.exists(!0))),this}delete(t){J("WriteBatch.delete",arguments,1),this.wE();const e=$o("WriteBatch.delete",t,this.dE);return this.TE=this.TE.concat(new Kt(e.cE,Ut.NONE)),this}async commit(){if(this.wE(),this.EE=!0,this.TE.length>0)return this.dE.JT().write(this.TE)}wE(){if(this.EE)throw new L(M.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}class go{constructor(t,e,s){this.cE=t,this.firestore=e,this.mE=s,this.YT=this.firestore.JT()}static lE(t,e,s){if(t.length%2!=0)throw new L(M.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+`${t.ot()} has ${t.length}`);return new go(new Pt(t),e,s)}get id(){return this.cE.path.st()}get parent(){return new Co(this.cE.path.Z(),this.firestore,this.mE)}get path(){return this.cE.path.ot()}collection(t){if(J("DocumentReference.collection",arguments,1),Z("DocumentReference.collection","non-empty string",1,t),!t)throw new L(M.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");const e=It.ht(t);return new Co(this.cE.path.child(e),this.firestore)}isEqual(t){if(!(t instanceof go))throw ct("isEqual","DocumentReference",1,t);return this.firestore===t.firestore&&this.cE.isEqual(t.cE)&&this.mE===t.mE}set(t,e){X("DocumentReference.set",arguments,1,2),e=ko("DocumentReference.set",e);const[s,n]=Mo(this.mE,t,"DocumentReference.set"),i=e.merge||e.mergeFields?this.firestore.nE.Fu(n,s,e.mergeFields):this.firestore.nE.ku(n,s);return this.YT.write(i.wu(this.cE,Ut.NONE))}update(t,e,...s){let n;return"string"==typeof t||t instanceof _n?(Y("DocumentReference.update",arguments,2),n=this.firestore.nE.Mu("DocumentReference.update",t,e,s)):(J("DocumentReference.update",arguments,1),n=this.firestore.nE.$u("DocumentReference.update",t)),this.YT.write(n.wu(this.cE,Ut.exists(!0)))}delete(){return J("DocumentReference.delete",arguments,0),this.YT.write([new Kt(this.cE,Ut.NONE)])}onSnapshot(...t){X("DocumentReference.onSnapshot",arguments,1,4);let e,s={includeMetadataChanges:!1},n=0;"object"!=typeof t[n]||fo(t[n])||(ut("DocumentReference.onSnapshot",s=t[n],["includeMetadataChanges"]),st("DocumentReference.onSnapshot","boolean","includeMetadataChanges",s.includeMetadataChanges),n++);const i={includeMetadataChanges:s.includeMetadataChanges};return fo(t[n])?e=t[n]:(Z("DocumentReference.onSnapshot","function",n,t[n]),tt("DocumentReference.onSnapshot","function",n+1,t[n+1]),tt("DocumentReference.onSnapshot","function",n+2,t[n+2]),e={next:t[n],error:t[n+1],complete:t[n+2]}),this.IE(i,e)}IE(t,e){let s=t=>{console.error("Uncaught Error in onSnapshot:",t)};e.error&&(s=e.error.bind(e));const n=new _o({next:t=>{if(e.next){p(t.docs.size<=1,"Too many documents returned on a document query");const s=t.docs.get(this.cE);e.next(new bo(this.firestore,this.cE,s,t.fromCache,t.hasPendingWrites,this.mE))}},error:s}),i=this.YT.listen(pe.hs(this.cE.path),n,t);return()=>{n.KT(),this.YT.yl(i)}}get(t){return X("DocumentReference.get",arguments,0,1),Fo("DocumentReference.get",t),new Promise((e,s)=>{t&&"cache"===t.source?this.firestore.JT().WT(this.cE).then(t=>{e(new bo(this.firestore,this.cE,t,!0,t instanceof _e&&t.de,this.mE))},s):this.RE(e,s,t)})}RE(t,e,s){const n=this.IE({includeMetadataChanges:!0,hf:!0},{next:i=>{n(),!i.exists&&i.metadata.fromCache?e(new L(M.UNAVAILABLE,"Failed to get document because the client is offline.")):i.exists&&i.metadata.fromCache&&s&&"server"===s.source?e(new L(M.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):t(i)},error:e})}withConverter(t){return new go(this.cE,this.firestore,t)}}class yo{constructor(t,e){this.hasPendingWrites=t,this.fromCache=e}isEqual(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache}}class bo{constructor(t,e,s,n,i,r){this.dE=t,this.cE=e,this.AE=s,this.PE=n,this.VE=i,this.mE=r}data(t){if(X("DocumentSnapshot.data",arguments,0,1),t=No("DocumentSnapshot.data",t),this.AE){if(this.mE){const e=new vo(this.dE,this.cE,this.AE,this.PE,this.VE);return this.mE.fromFirestore(e,t)}return this.pE(this.AE.data(),Ht.$e(t,this.dE._E()))}}get(t,e){if(X("DocumentSnapshot.get",arguments,1,2),e=No("DocumentSnapshot.get",e),this.AE){const s=this.AE.data().field(kn("DocumentSnapshot.get",t));if(null!==s)return this.gE(s,Ht.$e(e,this.dE._E()))}}get id(){return this.cE.path.st()}get ref(){return new go(this.cE,this.dE,this.mE)}get exists(){return null!==this.AE}get metadata(){return new yo(this.VE,this.PE)}isEqual(t){if(!(t instanceof bo))throw ct("isEqual","DocumentSnapshot",1,t);return this.dE===t.dE&&this.PE===t.PE&&this.cE.isEqual(t.cE)&&(null===this.AE?null===t.AE:this.AE.isEqual(t.AE))&&this.mE===t.mE}pE(t,e){const s={};return t.forEach((t,n)=>{s[t]=this.gE(n,e)}),s}gE(t,e){if(t instanceof ue)return this.pE(t,e);if(t instanceof ce)return this.yE(t,e);if(t instanceof he){const s=t.value(e),n=this.dE.JT().o();return t.o.isEqual(n)||A(`Document ${this.cE.path} contains a document `+"reference within a different database ("+`${t.o.projectId}/${t.o.database}) which is not `+"supported. It will be treated as a reference in the current "+`database (${n.projectId}/${n.database}) `+"instead."),new go(s,this.dE,this.mE)}return t.value(e)}yE(t,e){return t.te.map(t=>this.gE(t,e))}}class vo extends bo{data(t){const e=super.data(t);return p(void 0!==e,"Document in a QueryDocumentSnapshot should exist"),e}}class So{constructor(t,e,s){this.bE=t,this.firestore=e,this.mE=s}where(t,e,s){J("Query.where",arguments,3),at("Query.where",3,s);let n;!function(t,e,s,n){if(!e.some(t=>t===n))throw new L(M.INVALID_ARGUMENT,`Invalid value ${ht(n)} provided to function `+`${t}() for its ${_t(s)} argument. Acceptable `+`values: ${e.join(", ")}`)}("Query.where",["<","<=","==",">=",">","array-contains","in","array-contains-any"],2,e);const i=kn("Query.where",t),r=ye.ht(e);if(i.ct()){if(r===ye.ARRAY_CONTAINS||r===ye.ARRAY_CONTAINS_ANY)throw new L(M.INVALID_ARGUMENT,`Invalid Query. You can't perform '${r.toString()}' `+"queries on FieldPath.documentId().");if(r===ye.IN){this.vE(s,r);const t=[];for(const e of s)t.push(this.SE(e));n=new ce(t)}else n=this.SE(s)}else r!==ye.IN&&r!==ye.ARRAY_CONTAINS_ANY||this.vE(s,r),n=this.firestore.nE.Lu("Query.where",s,r===ye.IN);const o=be.create(i,r,n);return this.DE(o),new So(this.bE.cs(o),this.firestore,this.mE)}orderBy(t,e){let s;if(X("Query.orderBy",arguments,1,2),tt("Query.orderBy","non-empty string",2,e),void 0===e||"asc"===e)s=Ne.ASCENDING;else{if("desc"!==e)throw new L(M.INVALID_ARGUMENT,`Function Query.orderBy() has unknown direction '${e}', `+"expected 'asc' or 'desc'.");s=Ne.DESCENDING}if(null!==this.bE.startAt)throw new L(M.INVALID_ARGUMENT,"Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");if(null!==this.bE.endAt)throw new L(M.INVALID_ARGUMENT,"Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");const n=kn("Query.orderBy",t),i=new $e(n,s);return this.CE(i),new So(this.bE._s(i),this.firestore,this.mE)}limit(t){return J("Query.limit",arguments,1),Z("Query.limit","number",1,t),lt("Query.limit",1,t),new So(this.bE.ds(t),this.firestore,this.mE)}limitToLast(t){return J("Query.limitToLast",arguments,1),Z("Query.limitToLast","number",1,t),lt("Query.limitToLast",1,t),new So(this.bE.fs(t),this.firestore,this.mE)}startAt(t,...e){Y("Query.startAt",arguments,1);const s=this.kE("Query.startAt",t,e,!0);return new So(this.bE.ms(s),this.firestore,this.mE)}startAfter(t,...e){Y("Query.startAfter",arguments,1);const s=this.kE("Query.startAfter",t,e,!1);return new So(this.bE.ms(s),this.firestore,this.mE)}endBefore(t,...e){Y("Query.endBefore",arguments,1);const s=this.kE("Query.endBefore",t,e,!0);return new So(this.bE.Ts(s),this.firestore,this.mE)}endAt(t,...e){Y("Query.endAt",arguments,1);const s=this.kE("Query.endAt",t,e,!1);return new So(this.bE.Ts(s),this.firestore,this.mE)}isEqual(t){if(!(t instanceof So))throw ct("isEqual","Query",1,t);return this.firestore===t.firestore&&this.bE.isEqual(t.bE)}withConverter(t){return new So(this.bE,this.firestore,t)}kE(t,e,s,n){if(at(t,1,e),e instanceof bo){if(s.length>0)throw new L(M.INVALID_ARGUMENT,`Too many arguments provided to ${t}().`);const i=e;if(!i.exists)throw new L(M.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+`${t}().`);return this.NE(t,i.AE,n)}{const i=[e].concat(s);return this.FE(t,i,n)}}NE(t,e,s){const n=[];for(const t of this.bE.orderBy)if(t.field.ct())n.push(new he(this.firestore.XT,e.key));else{const s=e.field(t.field);if(s instanceof re)throw new L(M.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+t.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===s){const e=t.field.ot();throw new L(M.INVALID_ARGUMENT,"Invalid query. You are trying to start or end a query using a "+`document for which the field '${e}' (used as the `+"orderBy) does not exist.")}n.push(s)}return new Fe(n,s)}FE(t,e,s){const n=this.bE.es;if(e.length>n.length)throw new L(M.INVALID_ARGUMENT,`Too many arguments provided to ${t}(). `+"The number of arguments must be less than or equal to the number of Query.orderBy() clauses");const i=[];for(let s=0;s<e.length;s++){const r=e[s];if(n[s].field.ct()){if("string"!=typeof r)throw new L(M.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in "+`${t}(), but got a ${typeof r}`);if(!this.bE.vs()&&-1!==r.indexOf("/"))throw new L(M.INVALID_ARGUMENT,"Invalid query. When querying a collection and ordering by FieldPath.documentId(), "+`the value passed to ${t}() must be a plain document ID, but `+`'${r}' contains a slash.`);const e=this.bE.path.child(It.ht(r));if(!Pt.dt(e))throw new L(M.INVALID_ARGUMENT,"Invalid query. When querying a collection group and ordering by "+`FieldPath.documentId(), the value passed to ${t}() must result in a `+`valid document path, but '${e}' is not because it contains an odd number `+"of segments.");const s=new Pt(e);i.push(new he(this.firestore.XT,s))}else{const e=this.firestore.nE.Lu(t,r);i.push(e)}}return new Fe(i,s)}onSnapshot(...t){X("Query.onSnapshot",arguments,1,4);let e,s={},n=0;return"object"!=typeof t[n]||fo(t[n])||(ut("Query.onSnapshot",s=t[n],["includeMetadataChanges"]),st("Query.onSnapshot","boolean","includeMetadataChanges",s.includeMetadataChanges),n++),fo(t[n])?e=t[n]:(Z("Query.onSnapshot","function",n,t[n]),tt("Query.onSnapshot","function",n+1,t[n+1]),tt("Query.onSnapshot","function",n+2,t[n+2]),e={next:t[n],error:t[n+1],complete:t[n+2]}),this.$E(this.bE),this.IE(s,e)}IE(t,e){let s=t=>{console.error("Uncaught Error in onSnapshot:",t)};e.error&&(s=e.error.bind(e));const n=new _o({next:t=>{e.next&&e.next(new Do(this.firestore,this.bE,t,this.mE))},error:s}),i=this.firestore.JT(),r=i.listen(this.bE,n,t);return()=>{n.KT(),i.yl(r)}}$E(t){if(t.ys()&&0===t.es.length)throw new L(M.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}get(t){return X("Query.get",arguments,0,1),Fo("Query.get",t),this.$E(this.bE),new Promise((e,s)=>{t&&"cache"===t.source?this.firestore.JT().jT(this.bE).then(t=>{e(new Do(this.firestore,this.bE,t,this.mE))},s):this.RE(e,s,t)})}RE(t,e,s){const n=this.IE({includeMetadataChanges:!0,hf:!0},{next:i=>{n(),i.metadata.fromCache&&s&&"server"===s.source?e(new L(M.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.)')):t(i)},error:e})}SE(t){if("string"==typeof t){if(""===t)throw new L(M.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");if(!this.bE.vs()&&-1!==t.indexOf("/"))throw new L(M.INVALID_ARGUMENT,"Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but "+`'${t}' contains a '/' character.`);const e=this.bE.path.child(It.ht(t));if(!Pt.dt(e))throw new L(M.INVALID_ARGUMENT,"Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, "+`but '${e}' is not because it has an odd number of segments (${e.length}).`);return new he(this.firestore.XT,new Pt(e))}if(t instanceof go){const e=t;return new he(this.firestore.XT,e.cE)}throw new L(M.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: "+`${ht(t)}.`)}vE(t,e){if(!Array.isArray(t)||0===t.length)throw new L(M.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for "+`'${e.toString()}' filters.`);if(t.length>10)throw new L(M.INVALID_ARGUMENT,`Invalid Query. '${e.toString()}' filters support a `+"maximum of 10 elements in the value array.");if(t.indexOf(null)>=0)throw new L(M.INVALID_ARGUMENT,`Invalid Query. '${e.toString()}' filters cannot contain 'null' `+"in the value array.");if(t.filter(t=>Number.isNaN(t)).length>0)throw new L(M.INVALID_ARGUMENT,`Invalid Query. '${e.toString()}' filters cannot contain 'NaN' `+"in the value array.")}DE(t){if(t instanceof be){const e=[ye.ARRAY_CONTAINS,ye.ARRAY_CONTAINS_ANY],s=[ye.IN,ye.ARRAY_CONTAINS_ANY],n=e.indexOf(t.op)>=0,i=s.indexOf(t.op)>=0;if(t.ls()){const e=this.bE.as();if(null!==e&&!e.isEqual(t.field))throw new L(M.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have"+` inequality filters on '${e.toString()}'`+` and '${t.field.toString()}'`);const s=this.bE.us();null!==s&&this.xE(t.field,s)}else if(i||n){let r=null;if(i&&(r=this.bE.bs(s)),null===r&&n&&(r=this.bE.bs(e)),null!=r)throw r===t.op?new L(M.INVALID_ARGUMENT,"Invalid query. You cannot use more than one "+`'${t.op.toString()}' filter.`):new L(M.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters `+`with '${r.toString()}' filters.`)}}}CE(t){if(null===this.bE.us()){const e=this.bE.as();null!==e&&this.xE(e,t.field)}}xE(t,e){if(!e.isEqual(t))throw new L(M.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality "+`(<, <=, >, or >=) on field '${t.toString()}' `+`and so you must also use '${t.toString()}' `+"as your first Query.orderBy(), but your first Query.orderBy() "+`is on field '${e.toString()}' instead.`)}}class Do{constructor(t,e,s,n){this.dE=t,this.ME=e,this.LE=s,this.mE=n,this.BE=null,this.qE=null,this.metadata=new yo(s.hasPendingWrites,s.fromCache)}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get empty(){return this.LE.docs.tt()}get size(){return this.LE.docs.size}forEach(t,e){X("QuerySnapshot.forEach",arguments,1,2),Z("QuerySnapshot.forEach","function",1,t),this.LE.docs.forEach(s=>{t.call(e,this.OE(s))})}get query(){return new So(this.ME,this.dE,this.mE)}docChanges(t){t&&(ut("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),st("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));const e=!(!t||!t.includeMetadataChanges);if(e&&this.LE.tn)throw new L(M.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this.BE&&this.qE===e||(this.BE=function(t,e,s,n){if(s.Ys.tt()){let e,i=0;return s.docChanges.map(r=>{const o=new vo(t,r.doc.key,r.doc,s.fromCache,s.Xs.has(r.doc.key),n);return p(r.type===rs.Qs,"Invalid event type for first snapshot"),p(!e||s.query.Rs(e,r.doc)<0,"Got added events in wrong order"),e=r.doc,{type:"added",doc:o,oldIndex:-1,newIndex:i++}})}{let i=s.Ys;return s.docChanges.filter(t=>e||t.type!==rs.zs).map(e=>{const r=new vo(t,e.doc.key,e.doc,s.fromCache,s.Xs.has(e.doc.key),n);let o=-1,h=-1;return e.type!==rs.Qs&&(p((o=i.indexOf(e.doc.key))>=0,"Index for document not found"),i=i.delete(e.doc.key)),e.type!==rs.Ws&&(h=(i=i.add(e.doc)).indexOf(e.doc.key)),{type:xo(e.type),doc:r,oldIndex:o,newIndex:h}})}}(this.dE,e,this.LE,this.mE),this.qE=e),this.BE}isEqual(t){if(!(t instanceof Do))throw ct("isEqual","QuerySnapshot",1,t);return this.dE===t.dE&&this.ME.isEqual(t.ME)&&this.LE.isEqual(t.LE)&&this.mE===t.mE}OE(t){return new vo(this.dE,t.key,t,this.metadata.fromCache,this.LE.Xs.has(t.key),this.mE)}}["length","forEach","map",..."undefined"!=typeof Symbol?[Symbol.iterator]:[]].forEach(t=>{try{Object.defineProperty(Do.prototype.docChanges,t,{get:()=>(function(){throw new L(M.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')})()})}catch(t){}});class Co extends So{constructor(t,e,s){if(super(pe.hs(t),e,s),this.UE=t,t.length%2!=1)throw new L(M.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+`${t.ot()} has ${t.length}`)}get id(){return this.bE.path.st()}get parent(){const t=this.bE.path.Z();return t.tt()?null:new go(new Pt(t),this.firestore)}get path(){return this.bE.path.ot()}doc(t){if(X("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=g.i()),Z("CollectionReference.doc","non-empty string",1,t),""===t)throw new L(M.INVALID_ARGUMENT,"Document path must be a non-empty string");const e=It.ht(t);return go.lE(this.bE.path.child(e),this.firestore,this.mE)}add(t){J("CollectionReference.add",arguments,1),Z("CollectionReference.add","object",1,t);const e=this.doc();return e.set(t).then(()=>e)}withConverter(t){return new Co(this.UE,this.firestore,t)}}function ko(t,e){if(void 0===e)return{merge:!1};if(ut(t,e,["merge","mergeFields"]),st(t,"boolean","merge",e.merge),nt(t,"mergeFields","a string or a FieldPath",e.mergeFields,t=>"string"==typeof t||t instanceof _n),void 0!==e.mergeFields&&void 0!==e.merge)throw new L(M.INVALID_ARGUMENT,`Invalid options passed to function ${t}(): You cannot specify both "merge" `+'and "mergeFields".');return e}function No(t,e){return void 0===e?{}:(ut(t,e,["serverTimestamps"]),it(t,0,"serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function Fo(t,e){tt(t,"object",1,e),e&&(ut(t,e,["source"]),it(t,0,"source",e.source,["default","server","cache"]))}function $o(t,e,s){if(e instanceof go){if(e.firestore!==s)throw new L(M.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw ct(t,"DocumentReference",1,e)}function xo(t){switch(t){case rs.Qs:return"added";case rs.js:case rs.zs:return"modified";case rs.Ws:return"removed";default:return V("Unknown change type: "+t)}}function Mo(t,e,s){let n;return t?(n=t.toFirestore(e),s="toFirestore() in "+s):n=e,[n,s]}const Lo=Cs(Po,"Use firebase.firestore() instead."),Bo=Cs(Vo,"Use firebase.firestore().runTransaction() instead."),qo=Cs(po,"Use firebase.firestore().batch() instead."),Oo=Cs(go,"Use firebase.firestore().doc() instead."),Uo=Cs(bo),Qo=Cs(vo),Wo=Cs(So),jo=Cs(Do),zo=Cs(Co,"Use firebase.firestore().collection() instead."),Ko={Firestore:Lo,GeoPoint:ft,Timestamp:mt,Blob:$s,Transaction:Bo,WriteBatch:qo,DocumentReference:Oo,DocumentSnapshot:Uo,Query:Wo,QueryDocumentSnapshot:Qo,QuerySnapshot:jo,CollectionReference:zo,FieldPath:_n,FieldValue:Rn,setLogLevel:Po.setLogLevel,CACHE_SIZE_UNLIMITED:Io};function Go(t){t.INTERNAL.registerComponent(new u("firestore",t=>{const e=t.getProvider("app").getImmediate();return new Po(e,t.getProvider("auth-internal"))},"PUBLIC").setServiceProps(function(t){p(t&&"object"==typeof t,"shallowCopy() expects object parameter.");const e={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e}(Ko)))}class Ho{hl(t){}pl(){}}const Jo="ConnectivityMonitor";class Yo{constructor(){this.QE=()=>this.WE(),this.jE=()=>this.zE(),this.KE=[],this.GE()}hl(t){this.KE.push(t)}pl(){window.removeEventListener("online",this.QE),window.removeEventListener("offline",this.jE)}GE(){window.addEventListener("online",this.QE),window.addEventListener("offline",this.jE)}WE(){R(Jo,"Network connectivity changed: AVAILABLE");for(const t of this.KE)t(0)}zE(){R(Jo,"Network connectivity changed: UNAVAILABLE");for(const t of this.KE)t(1)}static Zl(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}class Xo{constructor(t){this.HE=t.HE,this.JE=t.JE}pc(t){p(!this.YE,"Called onOpen on stream twice!"),this.YE=t}Ic(t){p(!this.XE,"Called onClose on stream twice!"),this.XE=t}onMessage(t){p(!this.ZE,"Called onMessage on stream twice!"),this.ZE=t}close(){this.JE()}send(t){this.HE(t)}tw(){p(void 0!==this.YE,"Cannot call onOpen because no callback was set"),this.YE()}ew(t){p(void 0!==this.XE,"Cannot call onClose because no callback was set"),this.XE(t)}sw(t){p(void 0!==this.ZE,"Cannot call onMessage because no callback was set"),this.ZE(t)}}const Zo="Connection",th="google.firestore.v1.Firestore",eh="v1",sh={BatchGetDocuments:"batchGet",Commit:"commit"},nh="gl-js/ fire/"+m,ih=15;class rh{constructor(t){this.o=t.o;const e=t.ssl?"https":"http";this.nw=e+"://"+t.host,this.forceLongPolling=t.forceLongPolling}iw(t,e){if(e)for(const s in e.p)e.p.hasOwnProperty(s)&&(t[s]=e.p[s]);t["X-Goog-Api-Client"]=nh}Mc(t,e,s){const n=this.rw(t);return new Promise((i,r)=>{const o=new c;o.listenOnce(l.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case _.NO_ERROR:const e=o.getResponseJson();R(Zo,"XHR received:",JSON.stringify(e)),i(e);break;case _.TIMEOUT:R(Zo,'RPC "'+t+'" timed out'),r(new L(M.DEADLINE_EXCEEDED,"Request time out"));break;case _.HTTP_ERROR:const s=o.getStatus();if(R(Zo,'RPC "'+t+'" failed with status:',s,"response text:",o.getResponseText()),s>0){const t=o.getResponseJson().error;if(t&&t.status&&t.message){const e=function(t){const e=t.toLowerCase().replace("_","-");return Object.values(M).indexOf(e)>=0?e:M.UNKNOWN}(t.status);r(new L(e,t.message))}else r(new L(M.UNKNOWN,"Server responded with status "+o.getStatus()))}else R(Zo,'RPC "'+t+'" failed'),r(new L(M.UNAVAILABLE,"Connection failed."));break;default:V('RPC "'+t+'" failed with unanticipated webchannel error '+o.getLastErrorCode()+": "+o.getLastError()+", giving up.")}}finally{R(Zo,'RPC "'+t+'" completed.')}});const h=Object.assign({},e);delete h.database;const a=JSON.stringify(h);R(Zo,"XHR sending: ",n+" "+a);const u={"Content-Type":"text/plain"};this.iw(u,s),o.send(n,"POST",a,u,ih)})}Bc(t,e,s){return this.Mc(t,e,s)}gc(t,e){const s=[this.nw,"/",th,"/",t,"/channel"],n=d(),u={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.o.projectId}/databases/${this.o.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling};this.iw(u.initMessageHeaders,e),i()||r()||o()||h()||a()||(u.httpHeadersOverwriteParam="$httpHeaders");const c=s.join("");R(Zo,"Creating WebChannel: "+c+" "+u);const l=n.createWebChannel(c,u);let _=!1,m=!1;const T=new Xo({HE:t=>{m?R(Zo,"Not sending because WebChannel is closed:",t):(_||(R(Zo,"Opening WebChannel transport."),l.open(),_=!0),R(Zo,"WebChannel sending:",t),l.send(t))},JE:()=>l.close()}),E=(t,e)=>{l.listen(t,t=>{try{e(t)}catch(t){setTimeout(()=>{throw t},0)}})};return E(f.EventType.OPEN,()=>{m||R(Zo,"WebChannel transport opened.")}),E(f.EventType.CLOSE,()=>{m||(m=!0,R(Zo,"WebChannel transport closed"),T.ew())}),E(f.EventType.ERROR,t=>{m||(m=!0,R(Zo,"WebChannel transport errored:",t),T.ew(new L(M.UNAVAILABLE,"The operation could not be completed")))}),E(f.EventType.MESSAGE,t=>{var e;if(!m){const s=t.data[0];p(!!s,"Got a webchannel message without data.");const n=s,i=n.error||(null===(e=n[0])||void 0===e?void 0:e.error);if(i){R(Zo,"WebChannel received error:",i);const t=i.status;let e=function(t){const e=qe[t];if(void 0!==e)return je(e)}(t),s=i.message;void 0===e&&(e=M.INTERNAL,s="Unknown error status: "+t+" with message "+i.message),m=!0,T.ew(new L(e,s)),l.close()}else R(Zo,"WebChannel received:",s),T.sw(s)}}),setTimeout(()=>{T.tw()},0),T}rw(t){const e=sh[t];return p(void 0!==e,"Unknown REST mapping for: "+t),this.nw+"/"+eh+"/projects/"+this.o.projectId+"/databases/"+this.o.database+"/documents:"+e}}Ss.Tr(new class{constructor(){this.ti="",this.Er="undefined"!=typeof atob}get document(){return"undefined"!=typeof document?document:null}get window(){return"undefined"!=typeof window?window:null}LT(t){return Promise.resolve(new rh(t))}qT(){return Yo.Zl()?new Yo:new Ho}OT(t){return new vs(t,{ei:!0})}s(t){return JSON.stringify(t)}atob(t){return atob(t)}btoa(t){return btoa(t)}});const oh="@firebase/firestore",hh="1.10.1";function ah(t){Go(t),t.registerVersion(oh,hh)}ah(t);export{ah as __PRIVATE_registerFirestore};
  //# sourceMappingURL=index.esm2017.min.js.map
  