!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app"],e):e(t.firebase)}(this,function(t){"use strict";try{(function(){var e;t=t&&t.hasOwnProperty("default")?t.default:t,function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(e||(e={}));var n=e.INFO,r=function(t,n){for(var r=[],i=2;i0&&i[i.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]>>0),S=0;function T(t,e,n){return t.call.apply(t.bind,arguments)}function I(t,e,n){if(!t)throw Error();if(2n&&(n=Math.max(0,t.length+n)),d(t))return d(e)&&1==e.length?t.lastIndexOf(e,n):-1;for(;0<=n;n--)if(n in t&&t[n]===e)return n;return-1},q=Array.prototype.forEach?function(t,e,n){Array.prototype.forEach.call(t,e,n)}:function(t,e,n){for(var r=t.length,i=d(t)?t.split(""):t,o=0;oe?1:0}t:{var z=f.navigator;if(z){var G=z.userAgent;if(G){K=G;break t}}K=""}function H(t){return-1!=K.indexOf(t)}function X(t,e,n){for(var r in t)e.call(n,t[r],r,t)}function Y(t){var e,n=[],r=0;for(e in t)n[r++]=t[e];return n}function J(t){var e,n=[],r=0;for(e in t)n[r++]=e;return n}function Z(t){var e,n={};for(e in t)n[e]=t[e];return n}var $="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function tt(t,e){for(var n,r,i=1;iparseFloat(lt)){nt=String(dt);break t}}nt=lt}var pt,mt={};function yt(t){return function(t,e){var n=mt;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=e(t)}(t,function(){for(var e=0,n=W(String(nt)).split("."),r=W(String(t)).split("."),i=Math.max(n.length,r.length),o=0;0==e&&o=t.keyCode)&&(t.keyCode=-1)}catch(t){}};var Ct="closure_listenable_"+(1e6*Math.random()|0);function Dt(t){return!(!t||!t[Ct])}var Nt=0;function At(t,e,n,r,i){this.listener=t,this.proxy=null,this.src=e,this.type=n,this.capture=!!r,this.Ob=i,this.key=++Nt,this.Sa=this.Eb=!1}function kt(t){this.src=t,this.J={},this.xb=0}function Rt(t,e,n,r){for(var i=0;in.keyCode||void 0!=n.returnValue)){t:{var i=!1;if(0==n.keyCode)try{n.keyCode=-1;break t}catch(t){i=!0}(i||void 0==n.returnValue)&&(n.returnValue=!0)}for(n=[],i=e.currentTarget;i;i=i.parentNode)n.push(i);for(t=t.type,i=n.length-1;!e.Ea&&0<=i;i--){e.currentTarget=n[i];var o=Ft(n[i],t,!0,e);r=r&&o}for(i=0;!e.Ea&&i>>0);function Kt(t){return b(t)?t:(t[Qt]||(t[Qt]=function(e){return t.handleEvent(e)}),t[Qt])}function Wt(){M.call(this),this.ka=new kt(this),this.Pe=this,this.Uc=null}A(Wt,M),Wt.prototype[Ct]=!0,(c=Wt.prototype).addEventListener=function(t,e,n,r){_t(this,t,e,n,r)},c.removeEventListener=function(t,e,n,r){!function t(e,n,r,i,o){if(g(n))for(var s=0;s=this.Qd().value},c.log=function(t,e,n){this.Pf(t)&&(b(e)&&(e=e()),this.gf(this.uf(t,e,n)))},c.uf=function(t,e,n){return t=new ue(t,String(e),this.pe),n&&t.Bg(n),t},c.ca=function(t,e){this.log(le,t,e)},c.T=function(t,e){this.log(fe,t,e)},c.info=function(t,e){this.log(de,t,e)},c.lf=function(t){this.log(me,t,void 0)},c.gf=function(t){for(var e=this;e;)e.We(t),e=e.getParent()},c.We=function(t){if(this.Zd)for(var e,n=0;e=this.Zd[n];n++)e(t)},c.Fg=function(t){this.$b=t},c.Qe=function(t,e){this.pf()[t]=e};var ye={},ge=null;function ve(t){var e;if(ge||(ge=new ce(""),ye[""]=ge,ge.Ge(pe)),!(e=ye[t])){e=new ce(t);var n=t.lastIndexOf("."),r=t.substr(n+1);(n=ve(t.substr(0,n))).Qe(r,e),e.Fg(n),ye[t]=e}return e}function be(t,e){t&&t.info(e,void 0)}function we(t,e){t&&t.lf(e)}function Ee(){this.s=ve("goog.labs.net.webChannel.WebChannelDebug"),this.Wc=!0}(c=Ee.prototype).Id=function(){this.Wc=!1},c.Tg=function(t,e,n,r,i){var o=this;this.info(function(){return"XMLHTTP REQ ("+n+") [attempt "+r+"]: "+t+"\n"+e+"\n"+o.Xf(i)})},c.Ug=function(t,e,n,r,i,o){this.info(function(){return"XMLHTTP RESP ("+n+") [ attempt "+r+"]: "+t+"\n"+e+"\n"+i+" "+o})},c.Wa=function(t,e,n){var r=this;this.info(function(){return"XMLHTTP TEXT ("+t+"): "+r.ng(e)+(n?" "+n:"")})},c.Sg=function(t){this.info(function(){return"TIMEOUT: "+t})},c.debug=function(t){we(this.s,t)},c.cb=function(t,e){var n=this.s;n&&n.ca(e||"Exception",t)},c.info=function(t){be(this.s,t)},c.T=function(t){var e=this.s;e&&e.T(t,void 0)},c.ca=function(t){var e=this.s;e&&e.ca(t,void 0)},c.ng=function(t){if(!this.Wc)return t;if(!t)return null;try{var e=JSON.parse(t);if(e)for(var n=0;nt.length||(t=t[1],!g(t)||1>t.length))){var e=t[0];if("noop"!=e&&"stop"!=e&&"close"!=e)for(e=1;et||3==t&&!at&&!this.h.ya())){this.Za||4!=t||7==e||Ie(8==e||0>=n?3:2),this.Fb();var r=this.h.za();if(this.w=r,!(e=this.h.ya())){var i=this;this.a.debug(function(){return"No response text for uri "+i.pa+" status "+r})}if(this.S=200==r,this.a.Ug(this.Fa,this.pa,this.R,this.Xc,t,r),this.S){if(this.Ig()){if(!(n=this.sf()))return this.S=!1,this.I=3,De(12),this.a.T("XMLHTTP Missing X_HTTP_INITIAL_RESPONSE ("+this.R+")"),this.Ia(),void this.Kb();this.a.Wa(this.R,n,"Initial handshake response via X-HTTP-Initial-Response"),this.lb=!0,this.Yc(n)}this.yc?(this.Fd(t,e),at&&this.S&&3==t&&this.Ng()):(this.a.Wa(this.R,e,null),this.Yc(e)),4==t&&this.Ia(),this.S&&!this.Za&&(4==t?this.b.Tc(this):(this.S=!1,this.eb()))}else 400==r&&0t.length?Ve:(t=t.substr(n,e),this.Bb=n+e,t))},c.yg=function(t){this.ic=2,this.ua=t.clone().Ub(),t=!1,f.navigator&&f.navigator.sendBeacon&&(t=f.navigator.sendBeacon(this.ua.toString(),"")),!t&&f.Image&&((new Image).src=this.ua,t=!0),t||(this.h=this.b.Jb(null),this.h.send(this.ua)),this.qb=N(),this.eb()},c.cancel=function(){this.Za=!0,this.Ia()},c.tg=function(t){t&&this.setTimeout(t),this.Ga&&(this.Fb(),this.eb())},c.eb=function(){this.hd=N()+this.Ua,this.Ke(this.Ua)},c.Ke=function(t){if(null!=this.Ga)throw Error("WatchDog timer not null");this.Ga=Ae(C(this.gg,this),t)},c.Fb=function(){this.Ga&&(f.clearTimeout(this.Ga),this.Ga=null)},c.gg=function(){this.Ga=null;var t=N();0<=t-this.hd?this.Df():(this.a.T("WatchDog timer called too early"),this.Ke(this.hd-t))},c.Df=function(){this.S&&this.a.ca("Received watchdog timeout even though request loaded successfully"),this.a.Sg(this.pa),2!=this.ic&&(Ie(3),De(17)),this.Ia(),this.I=2,this.Kb()},c.Kb=function(){this.b.de()||this.Za||this.b.Tc(this)},c.Ia=function(){this.Fb();var t=this.ac;t&&"function"==typeof t.bb&&t.bb(),this.ac=null,this.Vc.stop(),this.Fc.pb(),this.h&&(t=this.h,this.h=null,t.abort(),t.bb())},c.Hc=function(){return this.I},c.Yc=function(t){try{this.b.ue(this,t),Ie(4)}catch(t){this.a.cb(t,"Error in httprequest callback")}},(c=We.prototype).C=function(){return this.j},c.H=function(){this.wc();for(var t=[],e=0;e2*this.j&&this.wc(),!0)},c.wc=function(){if(this.j!=this.o.length){for(var t=0,e=0;t>4&15).toString(16)+(15&t).toString(16)}(c=Ge.prototype).toString=function(){var t=[],e=this.qa;e&&t.push(Xe(e,Je,!0),":");var n=this.xa;return(n||"file"==e)&&(t.push("//"),(e=this.zb)&&t.push(Xe(e,Je,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.Ca)&&t.push(":",String(n))),(n=this.K)&&(this.Ic()&&"/"!=n.charAt(0)&&t.push("/"),t.push(Xe(n,"/"==n.charAt(0)?$e:Ze,!0))),(n=this.Rd())&&t.push("?",n),(n=this.ib)&&t.push("#",Xe(n,en)),t.join("")},c.resolve=function(t){var e=this.clone(),n=t.Hf();n?e.tb(t.qa):n=t.If(),n?e.cd(t.zb):n=t.Ic(),n?e.rb(t.xa):n=t.Ff();var r=t.K;if(n)e.sb(t.Ca);else if(n=t.ae()){if("/"!=r.charAt(0))if(this.Ic()&&!this.ae())r="/"+r;else{var i=e.K.lastIndexOf("/");-1!=i&&(r=e.K.substr(0,i+1)+r)}if(".."==(i=r)||"."==i)r="";else if(-1!=i.indexOf("./")||-1!=i.indexOf("/.")){r=0==i.lastIndexOf("/",0),i=i.split("/");for(var o=[],s=0;st)throw Error("Bad port number "+t);this.Ca=t}else this.Ca=null},c.Ff=function(){return null!=this.Ca},c.ec=function(t,e){this.U(),this.K=e?He(t,!0):t},c.ae=function(){return!!this.K},c.Gf=function(){return""!==this.P.toString()},c.bd=function(t,e){this.U(),t instanceof nn?(this.P=t,this.P.ad(this.O)):(e||(t=Xe(t,tn)),this.P=new nn(t,this.O))},c.Rd=function(){return this.P.toString()},c.getQuery=function(){return this.Rd()},c.l=function(t,e){this.U(),this.P.set(t,e)},c.dc=function(t,e){this.U(),g(e)||(e=[String(e)]),this.P.Ie(t,e)},c.$c=function(t,e){this.U(),this.ib=e?He(t):t},c.Ef=function(){return!!this.ib},c.Ub=function(){return this.U(),this.l("zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^N()).toString(36)),this},c.removeParameter=function(t){return this.U(),this.P.remove(t),this},c.U=function(){if(this.Qf)throw Error("Tried to modify a read-only Uri")},c.ad=function(t){this.O=t,this.P&&this.P.ad(t)};var Je=/[#\/\?@]/g,Ze=/[#\?:]/g,$e=/[#\?]/g,tn=/[#\?@]/g,en=/#/g;function nn(t,e){this.j=this.m=null,this.ja=t||null,this.O=!!e}function rn(t,e){this.b=t,this.a=e,this.f=this.A=null,this.bc=!1,this.K=null,this.w=-1,this.Ad=this.na=null}function on(t){this.D=new We,t&&this.addAll(t)}function sn(t){var e=typeof t;return"object"==e&&t||"function"==e?"o"+(t[E]||(t[E]=++S)):e.substr(0,1)+t}function an(t){this.me=t||un,f.PerformanceNavigationTiming?t=0<(t=f.performance.getEntriesByType("navigation")).length&&("hq"==t[0].nextHopProtocol||"h2"==t[0].nextHopProtocol):t=!!(f.vc&&f.vc.ke&&f.vc.ke()&&f.vc.ke().nh),this.Xb=t?this.me:1,this.v=null,1=this.Xb},c.xf=function(){return this.f?1:this.v?this.v.C():0},c.Jc=function(t){return this.f?this.f==t:!!this.v&&this.v.contains(t)},c.oc=function(t){this.v?this.v.add(t):this.f=t},c.ze=function(t){this.f&&this.f==t?this.f=null:this.v&&this.v.contains(t)&&this.v.remove(t)},c.cancel=function(){this.ba=this.la(),this.f?(this.f.cancel(),this.f=null):this.v&&!this.v.X()&&(q(this.v.H(),function(t){t.cancel()}),this.v.clear())},c.la=function(){if(null!=this.f)return this.ba.concat(this.f.la());if(null!=this.v&&!this.v.X()){var t=this.ba;return q(this.v.H(),function(e){t=t.concat(e.la())}),t}return V(this.ba)},c.Re=function(t){this.ba=this.ba.concat(t)},c.$e=function(){this.ba.length=0},cn.prototype.stringify=function(t){return f.JSON.stringify(t,this.rg)},cn.prototype.parse=function(t){return f.JSON.parse(t,this.xg)},hn.prototype.hf=function(t,e,n){var r=n||"";try{Ke(t,function(t,n){var i=t;w(t)&&(i=jt(t)),e.push(r+n+"="+encodeURIComponent(i))})}catch(t){throw e.push(r+"type="+encodeURIComponent("_badmap")),t}},hn.prototype.jf=function(t,e,n){for(var r=-1;;){var i=["count="+e];-1==r?0(a-=r))r=Math.max(0,t[s].Pc-100),o=!1;else try{this.hf(u,i,"req"+a+"_")}catch(t){n&&n(u)}}if(o)return i.join("&")}},hn.prototype.zc=function(t){return this.jg.parse(t)};var fn=f.JSON.parse;function dn(t){Wt.call(this),this.headers=new We,this.Xa=t||null,this.ha=!1,this.mc=this.c=null,this.ge=this.Tb="",this.Pa=0,this.I="",this.Aa=this.Lc=this.Qb=this.Ec=!1,this.vb=0,this.hc=null,this.Ae=pn,this.jc=this.lg=this.Ab=!1}A(dn,Wt);var pn="";dn.prototype.s=ve("goog.net.XhrIo");var mn=/^https?$/i,yn=["POST","PUT"];function gn(t){return"content-type"==t.toLowerCase()}function vn(t,e){return{type:e,lengthComputable:t.lengthComputable,loaded:t.loaded,total:t.total}}function bn(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=function(t){var e="";return X(t,function(t,n){e+=n,e+=":",e+=t,e+="\r\n"}),e}(n),d(t)){if(e=encodeURIComponent(String(e)),e+=n=null!=n?"="+encodeURIComponent(String(n)):""){if(0>(n=t.indexOf("#"))&&(n=t.length),0>(r=t.indexOf("?"))||r>n){r=n;var i=""}else i=t.substring(r+1,n);n=(t=[t.substr(0,r),i,t.substr(n)])[1],t[1]=e?n?n+"&"+e:e:n,t=t[0]+(t[1]?"?"+t[1]:"")+t[2]}return t}return t.l(e,n),t}function wn(t){this.Bd=22,this.De=0,this.M=[],this.a=new Ee,this.Ib=new function(){this.od=this.$d=null},this.na=this.md=this.hb=this.K=this.u=this.Kc=this.aa=this.gb=this.N=this.Rb=this.A=null,this.Te=!0,this.ag=this.Yb=0,this.kf=!!p("internalChannelParams.failFast",t),this.fd=this.Ja=this.wa=this.ia=this.ea=this.i=null,this.Se=!0,this.w=this.he=this.Sb=-1,this.rc=this.Ha=this.La=0,this.Ve=p("internalChannelParams.baseRetryDelayMs",t)||5e3,this.vg=p("internalChannelParams.retryDelaySeedMs",t)||1e4,this.nf=p("internalChannelParams.forwardChannelMaxRetries",t)||2,this.Od=p("internalChannelParams.forwardChannelRequestTimeoutMs",t)||2e4,this.Xa=t&&t.oh||void 0,this.Db=void 0,this.Ra=0,this.gc=t&&t.supportsCrossDomainXhr||!1,this.ra="",this.G=new an(t&&t.concurrentRequestLimit),this.kc=new hn,this.ta=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,(this.Nd=t&&t.fastHandshake||!1)&&!this.ta&&(this.a.T("Force backgroundChannelTest when fastHandshake is enabled."),this.ta=!0),t&&t.Id&&this.a.Id()}function En(){}function Sn(){if(ot&&!(10<=Number(pt)))throw Error("Environmental error: no available transport.")}function Tn(t,e){Wt.call(this),this.b=new wn(e),this.yb=t,this.Qg=e&&e.testUrl?e.testUrl:function(t){for(var e=arguments[0],n=1;ne?null:d(t)?t.charAt(e):t[e]}(i.W()),n=f.FormData&&t instanceof f.FormData,!(0<=P(yn,e))||r||n||i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach(function(t,e){this.c.setRequestHeader(e,t)},this),this.Ae&&(this.c.responseType=this.Ae),"withCredentials"in this.c&&this.c.withCredentials!==this.Ab&&(this.c.withCredentials=this.Ab);try{this.yd(),0=this.G.Xb-(this.ea?1:0)?(this.a.ca("Unexpected retry request is scheduled."),!1):this.ea?(this.a.debug("Use the retry request that is already scheduled."),this.M=t.la().concat(this.M),!0):!(1==this.g||2==this.g||this.La>=this.qf())&&(this.a.debug("Going to retry POST"),this.ea=Ae(C(this.we,this,t),this.Xd(this.La)),this.La++,!0)},c.we=function(t){this.ea=null,this.Mg(t)},c.Mg=function(t){this.a.debug("startForwardChannel_"),1==this.g?t?this.a.ca("Not supposed to retry the open"):(this.ig(),this.g=2):3==this.g&&(t?this.le(t):0==this.M.length?this.a.debug("startForwardChannel_ returned: nothing to send"):this.G.ee()?this.a.ca("startForwardChannel_ returned: connection already in progress"):(this.le(),this.a.debug("startForwardChannel_ finished, sent request")))},c.ig=function(){this.a.debug("open_()"),this.Yb=Math.floor(1e5*Math.random());var t=this.Yb++,e=new Fe(this,this.a,"",t,void 0),n=this.A;this.Rb&&(n?tt(n=Z(n),this.Rb):n=this.Rb),null===this.N&&e.ga(n);var r=this.Hd(e),i=this.hb.clone();i.l("RID",t),0t&&!this.Nf()&&0==this.Ha},c.$a=function(t){return this.Te?this.i?this.i.$a(t):t:null},c.bg=function(){null!=this.wa&&(this.wa=null,this.u.cancel(),this.u=null,this.Qc(),De(19))},c.Hb=function(){null!=this.wa&&(f.clearTimeout(this.wa),this.wa=null)},c.Tc=function(t){this.a.debug("Request complete");var e=null;if(this.u==t){this.Hb(),this.u=null;var n=2}else{if(!this.G.Jc(t))return;e=t.la(),this.G.ze(t),n=1}if(this.w=t.w,0!=this.g)if(t.S)1==n?(function(t,e,n){Se.dispatchEvent(new Ne(Se,t,e,n))}(t.Da?t.Da.length:0,N()-t.qb,this.La),this.Dc()):this.Kd();else{var r=t.Hc();if(3==r||0==r&&0this.Wb)throw Error(Rn);this.fa=new An,this.oa=new on,this.Ac=0,this.Nc=null,this.Cb()}(c=An.prototype).Vf=function(){0==this.V.length&&(this.V=this.Z,this.V.reverse(),this.Z=[])},c.enqueue=function(t){this.Z.push(t)},c.ab=function(){return this.Vf(),this.V.pop()},c.C=function(){return this.V.length+this.Z.length},c.X=function(){return 0==this.V.length&&0==this.Z.length},c.clear=function(){this.V=[],this.Z=[]},c.contains=function(t){return 0<=P(this.V,t)||0<=P(this.Z,t)},c.remove=function(t){var e=this.V,n=L(e,t);return 0<=n?(Array.prototype.splice.call(e,n,1),e=!0):e=!1,e||B(this.Z,t)},c.H=function(){for(var t=[],e=this.V.length-1;0<=e;--e)t.push(this.V[e]);var n=this.Z.length;for(e=0;ethis.Wb&&0=this.C()){for(var n=this.Y,r=0;r=e))return 1==e?F(t):(t[0]=t.pop(),this.Zf()),n.gd},c.Zf=function(){for(var t=0,e=this.Y,n=e.length,r=e[t];t>1;){var i=this.tf(t),o=this.zf(t);if(e[i=or.getKey())break;e[t]=e[i],t=i}e[t]=r},c.$f=function(t){for(var e=this.Y,n=e[t];0n.getKey()))break;e[t]=e[r],t=r}e[t]=n},c.tf=function(t){return 2*t+1},c.zf=function(t){return 2*t+2},c.wf=function(t){return t-1>>1},c.H=function(){for(var t=this.Y,e=[],n=t.length,r=0;rr)throw new nr(er.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+Cr(e.length,"argument")+".")}function fr(t,e,n,r){vr(t,e,Ir(n)+" argument",r)}function dr(t,e,n,r){void 0!==r&&fr(t,e,n,r)}function pr(t,e,n,r){vr(t,e,n+" option",r)}function mr(t,e,n,r){void 0!==r&&pr(t,e,n,r)}function yr(t,e,n,r,i){void 0!==r&&function(t,e,n,r,i){if(!(r instanceof Array))throw new nr(er.INVALID_ARGUMENT,"Function "+t+"() requires its "+e+" option to be an array, but it was: "+wr(r));for(var o=0;o20&&(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";var e=function(t){if(t.constructor){var 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":Jn("Unknown wrong type: "+typeof t)}function Er(t,e,n){if(void 0===n)throw new nr(er.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+Ir(e)+" argument, but it was undefined.")}function Sr(t,e,n){ar(e,function(e,r){if(n.indexOf(e)<0)throw new nr(er.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function Tr(t,e,n,r){var i=wr(r);return new nr(er.INVALID_ARGUMENT,"Function "+t+"() requires its "+Ir(n)+" argument to be a "+e+", but it was: "+i)}function Ir(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function Cr(t,e){return t+" "+e+(1===t?"":"s")}var Dr=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return Zn(20===e.length,"Invalid auto ID: "+e),e},t}();function Nr(t,e){return te?1:0}function Ar(t,e){if(t.length!==e.length)return!1;for(var n=0;n90)throw new nr(er.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new nr(er.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this._long},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){return this._lat===t._lat&&this._long===t._long},t.prototype._compareTo=function(t){return Nr(this._lat,t._lat)||Nr(this._long,t._long)},t}(),qr=function(){function t(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new nr(er.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new nr(er.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new nr(er.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new nr(er.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}return t.now=function(){return t.fromMillis(Date.now())},t.fromDate=function(e){return t.fromMillis(e.getTime())},t.fromMillis=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.prototype.toDate=function(){return new Date(this.toMillis())},t.prototype.toMillis=function(){return 1e3*this.seconds+this.nanoseconds/1e6},t.prototype._compareTo=function(t){return this.seconds===t.seconds?Nr(this.nanoseconds,t.nanoseconds):Nr(this.seconds,t.seconds)},t.prototype.isEqual=function(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"},t}(),xr=function(){return function(t,e,n,r){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r}}(),Fr="(default)",Br=function(){function t(t,e){this.projectId=t,this.database=e||Fr}return Object.defineProperty(t.prototype,"isDefaultDatabase",{get:function(){return this.database===Fr},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return e instanceof t&&e.projectId===this.projectId&&e.database===this.database},t.prototype.compareTo=function(t){return Nr(this.projectId,t.projectId)||Nr(this.database,t.database)},t}(),Ur=function(){function t(t,e,n){this.init(t,e,n)}return t.prototype.init=function(t,e,n){void 0===e?e=0:e>t.length&&Jn("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&Jn("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n},t.prototype.construct=function(t,e,n){var r=Object.create(Object.getPrototypeOf(this));return r.init(t,e,n),r},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return 0===t.comparator(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach(function(t){n.push(t)}):"string"==typeof e?n.push(e):Jn("Unknown parameter type for Path.child(): "+e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,Zn(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return Zn(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return Zn(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return Zn(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},t.prototype.get=function(t){return Zn(to)return 1}return t.lengthe.length?1:0},t}(),Vr=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(t){if(t.indexOf("//")>=0)throw new nr(er.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(Ur),Qr=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Kr=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.isValidIdentifier=function(t){return Qr.test(t)},e.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(t){for(var n=[],r="",i=0,o=function(){if(0===r.length)throw new nr(er.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},s=!1;i0&&(e=e.right)}return null},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.isEmpty();){var r=this.comparator(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal(function(e,n){return t(e,n),!1})},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(){return new Yr(this.root,null,this.comparator,!1)},t.prototype.getIteratorFrom=function(t){return new Yr(this.root,t,this.comparator,!1)},t.prototype.getReverseIterator=function(){return new Yr(this.root,null,this.comparator,!0)},t.prototype.getReverseIteratorFrom=function(t){return new Yr(this.root,t,this.comparator,!0)},t}(),Yr=function(){function t(t,e,n,r){this.isReverse=r,this.nodeStack=[];for(var i=1;!t.isEmpty();)if(i=e?n(t.key,e):1,r&&(i*=-1),i<0)t=this.isReverse?t.left:t.right;else{if(0===i){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){Zn(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t=this.nodeStack.pop(),e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}},t}(),Jr=function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:t.EMPTY,this.right=null!=o?o:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,i=n(t,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===i?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n))).fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()},t.prototype.remove=function(e,n){var r,i=this;if(n(e,i.key)<0)i.left.isEmpty()||i.left.isRed()||i.left.left.isRed()||(i=i.moveRedLeft()),i=i.copy(null,null,null,i.left.remove(e,n),null);else{if(i.left.isRed()&&(i=i.rotateRight()),i.right.isEmpty()||i.right.isRed()||i.right.left.isRed()||(i=i.moveRedRight()),0===n(e,i.key)){if(i.right.isEmpty())return t.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.removeMin())}i=i.copy(null,null,null,null,i.right.remove(e,n))}return i.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=(t=(t=t.copy(null,null,null,null,t.right.rotateRight())).rotateLeft()).colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=(t=t.rotateRight()).colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw Jn("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw Jn("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw Jn("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),Zr=function(){function t(){this.size=0}return t.prototype.copy=function(t,e,n,r,i){return this},t.prototype.insert=function(t,e,n){return new Jr(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();Jr.EMPTY=new Zr,function(t){t[t.NullValue=0]="NullValue",t[t.BooleanValue=1]="BooleanValue",t[t.NumberValue=2]="NumberValue",t[t.TimestampValue=3]="TimestampValue",t[t.StringValue=4]="StringValue",t[t.BlobValue=5]="BlobValue",t[t.RefValue=6]="RefValue",t[t.GeoPointValue=7]="GeoPointValue",t[t.ArrayValue=8]="ArrayValue",t[t.ObjectValue=9]="ObjectValue"}(Mr||(Mr={})),function(t){t[t.Default=0]="Default",t[t.Estimate=1]="Estimate",t[t.Previous=2]="Previous"}(Or||(Or={}));var $r=function(){function t(t,e){this.serverTimestampBehavior=t,this.timestampsInSnapshots=e}return t.fromSnapshotOptions=function(e,n){switch(e.serverTimestamps){case"estimate":return new t(Or.Estimate,n);case"previous":return new t(Or.Previous,n);case"none":case void 0:return new t(Or.Default,n);default:return Jn("fromSnapshotOptions() called with invalid options.")}},t}(),ti=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":t.toString()},t.prototype.defaultCompareTo=function(t){return Zn(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),Nr(this.typeOrder,t.typeOrder)},t}(),ei=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=Mr.NullValue,e.internalValue=null,e}return s(e,t),e.prototype.value=function(t){return null},e.prototype.isEqual=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(ti),ni=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.BooleanValue,n}return s(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?Nr(this,t):this.defaultCompareTo(t)},e.of=function(t){return t?e.TRUE:e.FALSE},e.TRUE=new e(!0),e.FALSE=new e(!1),e}(ti),ri=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.NumberValue,n}return s(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?(n=this.internalValue,r=t.internalValue,nr?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1):this.defaultCompareTo(t);var n,r},e}(ti);function ii(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}var oi=function(t){function e(e){return t.call(this,e)||this}return s(e,t),e.prototype.isEqual=function(t){return t instanceof e&&ii(this.internalValue,t.internalValue)},e}(ri),si=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return s(e,t),e.prototype.isEqual=function(t){return t instanceof e&&ii(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(ri),ai=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.StringValue,n}return s(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?Nr(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ti),ui=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.TimestampValue,n}return s(e,t),e.prototype.value=function(t){return t&&t.timestampsInSnapshots?this.internalValue:this.internalValue.toDate()},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):t instanceof ci?-1:this.defaultCompareTo(t)},e}(ti),ci=function(t){function e(e,n){var r=t.call(this)||this;return r.localWriteTime=e,r.previousValue=n,r.typeOrder=Mr.TimestampValue,r}return s(e,t),e.prototype.value=function(t){return t&&t.serverTimestampBehavior===Or.Estimate?new ui(this.localWriteTime).value(t):t&&t.serverTimestampBehavior===Or.Previous&&this.previousValue?this.previousValue.value(t):null},e.prototype.isEqual=function(t){return t instanceof e&&this.localWriteTime.isEqual(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime._compareTo(t.localWriteTime):t instanceof ui?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return""},e}(ti),hi=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.BlobValue,n}return s(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(ti),li=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=Mr.RefValue,r}return s(e,t),e.prototype.value=function(t){return this.key},e.prototype.isEqual=function(t){return t instanceof e&&(this.key.isEqual(t.key)&&this.databaseId.isEqual(t.databaseId))},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:Wr.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(ti),fi=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.GeoPointValue,n}return s(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(ti),di=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.ObjectValue,n}return s(e,t),e.prototype.value=function(t){var e={};return this.internalValue.inorderTraversal(function(n,r){e[n]=r.value(t)}),e},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.isEqual=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext();if(i.key!==o.key||!i.value.isEqual(o.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext(),s=Nr(i.key,o.key)||i.value.compareTo(o.value);if(s)return s}return Nr(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(t,n){if(Zn(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),n);var r=this.child(t.firstSegment());r instanceof e||(r=e.EMPTY);var i=r.set(t.popFirst(),n);return this.setChild(t.firstSegment(),i)},e.prototype.delete=function(t){if(Zn(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.internalValue.remove(t.firstSegment()));var n=this.child(t.firstSegment());if(n instanceof e){var r=n.delete(t.popFirst());return new e(this.internalValue.insert(t.firstSegment(),r))}return this},e.prototype.contains=function(t){return void 0!==this.field(t)},e.prototype.field=function(t){Zn(!t.isEmpty(),"Can't get field of empty path");var n=this;return t.forEach(function(t){n=n instanceof e&&n.internalValue.get(t)||void 0}),n},e.prototype.toString=function(){return JSON.stringify(this.value())},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new Xr(Nr)),e}(ti),pi=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Mr.ArrayValue,n}return s(e,t),e.prototype.value=function(t){return this.internalValue.map(function(e){return e.value(t)})},e.prototype.forEach=function(t){this.internalValue.forEach(t)},e.prototype.isEqual=function(t){if(t instanceof e){if(this.internalValue.length!==t.internalValue.length)return!1;for(var n=0;n=yi}var Ei,Si=function(){function t(t,e,n,r,i,o){void 0===e&&(e=[]),void 0===n&&(n=[]),void 0===r&&(r=null),void 0===i&&(i=null),void 0===o&&(o=null),this.path=t,this.explicitOrderBy=e,this.filters=n,this.limit=r,this.startAt=i,this.endAt=o,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}return t.atPath=function(e){return new t(e)},Object.defineProperty(t.prototype,"orderBy",{get:function(){if(null===this.memoizedOrderBy){var t=this.getInequalityFilterField(),e=this.getFirstOrderByField();if(null!==t&&null===e)t.isKeyField()?this.memoizedOrderBy=[Mi]:this.memoizedOrderBy=[new Ri(t),Mi];else{Zn(null===t||null!==e&&t.isEqual(e),"First orderBy should match inequality field."),this.memoizedOrderBy=[];for(var n=!1,r=0,i=this.explicitOrderBy;r0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:Ai.ASCENDING;this.memoizedOrderBy.push(s===Ai.ASCENDING?Mi:Oi)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(e){Zn(null==this.getInequalityFilterField()||!(e instanceof Ci)||!e.isInequality()||e.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),Zn(!Wr.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){Zn(!Wr.isDocumentKey(this.path),"No ordering allowed for document query"),Zn(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", filters: ["+this.filters.join(", ")+"]"),bi(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.isEqual=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;case"array-contains":return t.ARRAY_CONTAINS;default:return Jn("Unknown relation: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.isEqual=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t.ARRAY_CONTAINS=new t("array-contains"),t}(),Ci=function(t){function e(e,n,r){var i=t.call(this)||this;return i.field=e,i.op=n,i.value=r,i}return s(e,t),e.prototype.matches=function(t){if(this.field.isKeyField()){Zn(this.value instanceof li,"Comparing on key, but filter value not a RefValue"),Zn(this.op!==Ii.ARRAY_CONTAINS,"array-contains queries don't make sense on document keys.");var e=this.value,n=Wr.comparator(t.key,e.key);return this.matchesComparison(n)}var r=t.field(this.field);return void 0!==r&&this.matchesValue(r)},e.prototype.matchesValue=function(t){var e=this;return this.op===Ii.ARRAY_CONTAINS?t instanceof pi&&void 0!==t.internalValue.find(function(t){return t.isEqual(e.value)}):this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},e.prototype.matchesComparison=function(t){switch(this.op){case Ii.LESS_THAN:return t<0;case Ii.LESS_THAN_OR_EQUAL:return t<=0;case Ii.EQUAL:return 0===t;case Ii.GREATER_THAN:return t>0;case Ii.GREATER_THAN_OR_EQUAL:return t>=0;default:return Jn("Unknown relation op"+this.op)}},e.prototype.isInequality=function(){return this.op!==Ii.EQUAL&&this.op!==Ii.ARRAY_CONTAINS},e.prototype.canonicalId=function(){return this.field.canonicalString()+this.op.toString()+this.value.toString()},e.prototype.isEqual=function(t){return t instanceof e&&(this.op.isEqual(t.op)&&this.field.isEqual(t.field)&&this.value.isEqual(t.value))},e.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},e}(Ti),Di=function(t){function e(e){var n=t.call(this)||this;return n.field=e,n}return s(e,t),e.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&null===e.value()},e.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},e.prototype.toString=function(){return this.field.canonicalString()+" IS null"},e.prototype.isEqual=function(t){return t instanceof e&&this.field.isEqual(t.field)},e}(Ti),Ni=function(t){function e(e){var n=t.call(this)||this;return n.field=e,n}return s(e,t),e.prototype.matches=function(t){var e=t.field(this.field),n=e&&e.value();return"number"==typeof n&&isNaN(n)},e.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},e.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},e.prototype.isEqual=function(t){return t instanceof e&&this.field.isEqual(t.field)},e}(Ti),Ai=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),ki=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();){if(!t(n.getNext().key))return}},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=function(t){var e=this;return t.forEach(function(t){e=e.add(t)}),e},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.getIterator(),r=e.data.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(0!==this.comparator(i,o))return!1}return!0},t.prototype.toArray=function(){var t=[];return this.forEach(function(e){t.push(e)}),t},t.prototype.toString=function(){var t=[];return this.forEach(function(e){return t.push(e)}),"SortedSet("+t.toString()+")"},t.prototype.copy=function(e){var n=new t(this.comparator);return n.data=e,n},t}(),xi=function(){function t(t){this.fields=t}return t.fromArray=function(e){var n=new qi(Kr.comparator);return e.forEach(function(t){return n=n.add(t)}),new t(n)},t.prototype.covers=function(t){var e=!1;return this.fields.forEach(function(n){n.isPrefixOf(t)&&(e=!0)}),e},t.prototype.isEqual=function(t){return this.fields.isEqual(t.fields)},t}(),Fi=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.isEqual=function(t){return this.field.isEqual(t.field)&&this.transform.isEqual(t.transform)},t}(),Bi=function(){return function(t,e){this.version=t,this.transformResults=e}}();!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(Pi||(Pi={}));var Ui=function(){function t(t,e){this.updateTime=t,this.exists=e,Zn(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof zr&&t.version.isEqual(this.updateTime):void 0!==this.exists?this.exists===t instanceof zr:(Zn(this.isNone,"Precondition should be empty"),!0)},t.prototype.isEqual=function(t){return e=this.updateTime,n=t.updateTime,(null!==e&&void 0!==e?!(!n||!e.isEqual(n)):e===n)&&this.exists===t.exists;var e,n},t.NONE=new t,t}(),Vi=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&Zn(t.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof zr?t.version:_i.MIN},t}(),Qi=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.value=n,i.precondition=r,i.type=Pi.Set,i}return s(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),Zn(null==e.transformResults,"Transform results received by SetMutation.");var n=e.version;return new zr(this.key,n,this.value,{hasCommittedMutations:!0})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Vi.getPostMutationVersion(t);return new zr(this.key,r,this.value,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.value.isEqual(t.value)&&this.precondition.isEqual(t.precondition)},e}(Vi),Ki=function(t){function e(e,n,r,i){var o=t.call(this)||this;return o.key=e,o.data=n,o.fieldMask=r,o.precondition=i,o.type=Pi.Patch,o}return s(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),Zn(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return new Hr(this.key,e.version);var n=this.patchDocument(t);return new zr(this.key,e.version,n,{hasCommittedMutations:!0})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Vi.getPostMutationVersion(t),i=this.patchDocument(t);return new zr(this.key,r,i,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.fieldMask.isEqual(t.fieldMask)&&this.precondition.isEqual(t.precondition)},e.prototype.patchDocument=function(t){var e;return e=t instanceof zr?t.data:di.EMPTY,this.patchObject(e)},e.prototype.patchObject=function(t){var e=this;return this.fieldMask.fields.forEach(function(n){if(!n.isEmpty()){var r=e.data.field(n);t=void 0!==r?t.set(n,r):t.delete(n)}}),t},e}(Vi),Wi=function(t){function e(e,n){var r=t.call(this)||this;return r.key=e,r.fieldTransforms=n,r.type=Pi.Transform,r.precondition=Ui.exists(!0),r}return s(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),Zn(null!=e.transformResults,"Transform results missing for TransformMutation."),!this.precondition.isValidFor(t))return new Hr(this.key,e.version);var n=this.requireDocument(t),r=this.serverTransformResults(t,e.transformResults),i=e.version,o=this.transformObject(n.data,r);return new zr(this.key,i,o,{hasCommittedMutations:!0})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=this.requireDocument(t),i=this.localTransformResults(n,e),o=this.transformObject(r.data,i);return new zr(this.key,r.version,o,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&Ar(this.fieldTransforms,t.fieldTransforms)&&this.precondition.isEqual(t.precondition)},e.prototype.requireDocument=function(t){Zn(t instanceof zr,"Unknown MaybeDocument type "+t);var e=t;return Zn(e.key.isEqual(this.key),"Can only transform a document with the same key"),e},e.prototype.serverTransformResults=function(t,e){var n=[];Zn(this.fieldTransforms.length===e.length,"server transform result count ("+e.length+") should match field transform count ("+this.fieldTransforms.length+")");for(var r=0;r0&&(this._hasPendingChanges=!0,this._resumeToken=t)},t.prototype.toTargetChange=function(){var t=ao(),e=ao(),n=ao();return this.documentChanges.forEach(function(r,i){switch(i){case ho.Added:t=t.add(r);break;case ho.Modified:e=e.add(r);break;case ho.Removed:n=n.add(r);break;default:Jn("Encountered invalid change type: "+i)}}),new vo(this._resumeToken,this._current,t,e,n)},t.prototype.clearPendingChanges=function(){this._hasPendingChanges=!1,this.documentChanges=Co()},t.prototype.addDocumentChange=function(t,e){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.insert(t,e)},t.prototype.removeDocumentChange=function(t){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.remove(t)},t.prototype.recordPendingTargetRequest=function(){this.pendingResponses+=1},t.prototype.recordTargetResponse=function(){this.pendingResponses-=1},t.prototype.markCurrent=function(){this._hasPendingChanges=!0,this._current=!0},t}(),To=function(){function t(t){this.metadataProvider=t,this.targetStates={},this.pendingDocumentUpdates=eo(),this.pendingDocumentTargetMapping=Io(),this.pendingTargetResets=new qi(Nr)}return t.prototype.handleDocumentChange=function(t){for(var e=0,n=t.updatedTargetIds;e0?t.targetIds.forEach(e):sr(this.targetStates,e)},t.prototype.handleExistenceFilter=function(t){var e=t.targetId,n=t.existenceFilter.count,r=this.queryDataForActiveTarget(e);if(r){var i=r.query;if(i.isDocumentQuery())if(0===n){var o=new Wr(i.path);this.removeDocumentFromTarget(e,o,new Gr(o,_i.forDeletedDoc()))}else Zn(1===n,"Single document existence filter with count: "+n);else this.getCurrentDocumentCountForTarget(e)!==n&&(this.resetTarget(e),this.pendingTargetResets=this.pendingTargetResets.add(e))}},t.prototype.createRemoteEvent=function(t){var e=this,n={};sr(this.targetStates,function(r,i){var o=e.queryDataForActiveTarget(r);if(o){if(i.current&&o.query.isDocumentQuery()){var s=new Wr(o.query.path);null!==e.pendingDocumentUpdates.get(s)||e.targetContainsDocument(r,s)||e.removeDocumentFromTarget(r,s,new Gr(s,t))}i.hasPendingChanges&&(n[r]=i.toTargetChange(),i.clearPendingChanges())}});var r=ao();this.pendingDocumentTargetMapping.forEach(function(t,n){var i=!0;n.forEachWhile(function(t){var n=e.queryDataForActiveTarget(t);return!n||n.purpose===Ei.LimboResolution||(i=!1,!1)}),i&&(r=r.add(t))});var i=new go(t,n,this.pendingTargetResets,this.pendingDocumentUpdates,r);return this.pendingDocumentUpdates=eo(),this.pendingDocumentTargetMapping=Io(),this.pendingTargetResets=new qi(Nr),i},t.prototype.addDocumentToTarget=function(t,e){if(this.isActiveTarget(t)){var n=this.targetContainsDocument(t,e.key)?ho.Modified:ho.Added;this.ensureTargetState(t).addDocumentChange(e.key,n),this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e.key,e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e.key,this.ensureDocumentTargetMapping(e.key).add(t))}},t.prototype.removeDocumentFromTarget=function(t,e,n){if(this.isActiveTarget(t)){var r=this.ensureTargetState(t);this.targetContainsDocument(t,e)?r.addDocumentChange(e,ho.Removed):r.removeDocumentChange(e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e,this.ensureDocumentTargetMapping(e).delete(t)),n&&(this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e,n))}},t.prototype.removeTarget=function(t){delete this.targetStates[t]},t.prototype.getCurrentDocumentCountForTarget=function(t){var e=this.ensureTargetState(t).toTargetChange();return this.metadataProvider.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size},t.prototype.recordPendingTargetRequest=function(t){this.ensureTargetState(t).recordPendingTargetRequest()},t.prototype.ensureTargetState=function(t){return this.targetStates[t]||(this.targetStates[t]=new So),this.targetStates[t]},t.prototype.ensureDocumentTargetMapping=function(t){var e=this.pendingDocumentTargetMapping.get(t);return e||(e=new qi(Nr),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(t,e)),e},t.prototype.isActiveTarget=function(t){return null!==this.queryDataForActiveTarget(t)},t.prototype.queryDataForActiveTarget=function(t){var e=this.targetStates[t];return e&&e.isPending?null:this.metadataProvider.getQueryDataForTarget(t)},t.prototype.resetTarget=function(t){var e=this;Zn(!this.targetStates[t].isPending,"Should only reset active targets"),this.targetStates[t]=new So,this.metadataProvider.getRemoteKeysForTarget(t).forEach(function(n){e.removeDocumentFromTarget(t,n,null)})},t.prototype.targetContainsDocument=function(t,e){return this.metadataProvider.getRemoteKeysForTarget(t).has(e)},t}();function Io(){return new Xr(Wr.comparator)}function Co(){return new Xr(Wr.comparator)}var Do,No,Ao=((Do={})[Ai.ASCENDING.name]="ASCENDING",Do[Ai.DESCENDING.name]="DESCENDING",Do),ko=((No={})[Ii.LESS_THAN.name]="LESS_THAN",No[Ii.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",No[Ii.GREATER_THAN.name]="GREATER_THAN",No[Ii.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",No[Ii.EQUAL.name]="EQUAL",No[Ii.ARRAY_CONTAINS.name]="ARRAY_CONTAINS",No),Ro=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Mo(t,e){Zn(!bi(t),e+" is missing")}function Oo(t){return"number"==typeof t?t:"string"==typeof t?Number(t):Jn("can't parse "+t)}var _o=function(){function t(t,e){this.databaseId=t,this.options=e}return t.prototype.emptyByteString=function(){return this.options.useProto3Json?"":new Uint8Array(0)},t.prototype.unsafeCastProtoByteString=function(t){return t},t.prototype.fromRpcStatus=function(t){var e=void 0===t.code?er.UNKNOWN:$i(t.code);return new nr(e,t.message||"")},t.prototype.toInt32Value=function(t){return bi(t)?void 0:{value:t}},t.prototype.fromInt32Value=function(t){var e;return bi(e="object"==typeof t?t.value:t)?null:e},t.prototype.toTimestamp=function(t){return{seconds:t.seconds,nanos:t.nanoseconds}},t.prototype.fromTimestamp=function(t){if("string"==typeof t)return this.fromIso8601String(t);Zn(!!t,"Cannot deserialize null or undefined timestamp.");var e=Oo(t.seconds||"0"),n=t.nanos||0;return new qr(e,n)},t.prototype.fromIso8601String=function(t){var e=0,n=Ro.exec(t);if(Zn(!!n,"invalid timestamp: "+t),n[1]){var r=n[1];r=(r+"000000000").substr(0,9),e=Number(r)}var i=new Date(t),o=Math.floor(i.getTime()/1e3);return new qr(o,e)},t.prototype.toBytes=function(t){return this.options.useProto3Json?t.toBase64():this.unsafeCastProtoByteString(t.toUint8Array())},t.prototype.fromBlob=function(t){return"string"==typeof t?(Zn(this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),_r.fromBase64String(t)):(Zn(!this.options.useProto3Json,"Expected bytes to be passed in as string, but got something else instead."),_r.fromUint8Array(t))},t.prototype.toVersion=function(t){return this.toTimestamp(t.toTimestamp())},t.prototype.fromVersion=function(t){return Zn(!!t,"Trying to deserialize version that isn't set"),_i.fromTimestamp(this.fromTimestamp(t))},t.prototype.toResourceName=function(t,e){return this.fullyQualifiedPrefixPath(t).child("documents").child(e).canonicalString()},t.prototype.fromResourceName=function(t){var e=Vr.fromString(t);return Zn(this.isValidResourceName(e),"Tried to deserialize invalid key "+e.toString()),e},t.prototype.toName=function(t){return this.toResourceName(this.databaseId,t.path)},t.prototype.fromName=function(t){var e=this.fromResourceName(t);return Zn(e.get(1)===this.databaseId.projectId,"Tried to deserialize key from different project: "+e.get(1)+" vs "+this.databaseId.projectId),Zn(!e.get(3)&&!this.databaseId.database||e.get(3)===this.databaseId.database,"Tried to deserialize key from different database: "+e.get(3)+" vs "+this.databaseId.database),new Wr(this.extractLocalPathFromResourceName(e))},t.prototype.toQueryPath=function(t){return 0===t.length?this.encodedDatabaseId:this.toResourceName(this.databaseId,t)},t.prototype.fromQueryPath=function(t){var e=this.fromResourceName(t);return 4===e.length?Vr.EMPTY_PATH:this.extractLocalPathFromResourceName(e)},Object.defineProperty(t.prototype,"encodedDatabaseId",{get:function(){return new Vr(["projects",this.databaseId.projectId,"databases",this.databaseId.database]).canonicalString()},enumerable:!0,configurable:!0}),t.prototype.fullyQualifiedPrefixPath=function(t){return new Vr(["projects",t.projectId,"databases",t.database])},t.prototype.extractLocalPathFromResourceName=function(t){return Zn(t.length>4&&"documents"===t.get(4),"tried to deserialize invalid key "+t.toString()),t.popFirst(5)},t.prototype.isValidResourceName=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.toValue=function(t){if(t instanceof ei)return{nullValue:"NULL_VALUE"};if(t instanceof ni)return{booleanValue:t.value()};if(t instanceof oi)return{integerValue:""+t.value()};if(t instanceof si){var e=t.value();if(this.options.useProto3Json){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 ai?{stringValue:t.value()}:t instanceof di?{mapValue:this.toMapValue(t)}:t instanceof pi?{arrayValue:this.toArrayValue(t)}:t instanceof ui?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof fi?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof hi?{bytesValue:this.toBytes(t.value())}:t instanceof li?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:Jn("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this,n=t.value_type;if(Po(t,n,"nullValue"))return ei.INSTANCE;if(Po(t,n,"booleanValue"))return ni.of(t.booleanValue);if(Po(t,n,"integerValue"))return new oi(Oo(t.integerValue));if(Po(t,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return si.NAN;if("Infinity"===t.doubleValue)return si.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return si.NEGATIVE_INFINITY}return new si(t.doubleValue)}if(Po(t,n,"stringValue"))return new ai(t.stringValue);if(Po(t,n,"mapValue"))return this.fromFields(t.mapValue.fields||{});if(Po(t,n,"arrayValue")){Mo(t.arrayValue,"arrayValue");var r=t.arrayValue.values||[];return new pi(r.map(function(t){return e.fromValue(t)}))}if(Po(t,n,"timestampValue"))return Mo(t.timestampValue,"timestampValue"),new ui(this.fromTimestamp(t.timestampValue));if(Po(t,n,"geoPointValue")){Mo(t.geoPointValue,"geoPointValue");var i=t.geoPointValue.latitude||0,o=t.geoPointValue.longitude||0;return new fi(new Lr(i,o))}if(Po(t,n,"bytesValue")){Mo(t.bytesValue,"bytesValue");var s=this.fromBlob(t.bytesValue);return new hi(s)}if(Po(t,n,"referenceValue")){Mo(t.referenceValue,"referenceValue");var a=this.fromResourceName(t.referenceValue),u=new Br(a.get(1),a.get(3)),c=new Wr(this.extractLocalPathFromResourceName(a));return new li(u,c)}return Jn("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return Zn(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t,e){return new zr(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasCommittedMutations:!!e})},t.prototype.toFields=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.toValue(r)}),n},t.prototype.fromFields=function(t){var e=this,n=t,r=di.EMPTY;return ar(n,function(t,n){r=r.set(new Kr([t]),e.fromValue(n))}),r},t.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},t.prototype.fromFound=function(t){Zn(!!t.found,"Tried to deserialize a found document from a missing document."),Mo(t.found.name,"doc.found.name"),Mo(t.found.updateTime,"doc.found.updateTime");var e=this.fromName(t.found.name),n=this.fromVersion(t.found.updateTime),r=this.fromFields(t.found.fields||{});return new zr(e,n,r,{})},t.prototype.fromMissing=function(t){Zn(!!t.missing,"Tried to deserialize a missing document from a found document."),Zn(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.fromName(t.missing),n=this.fromVersion(t.readTime);return new Gr(e,n)},t.prototype.fromMaybeDocument=function(t){var e=t.result;return Po(t,e,"found")?this.fromFound(t):Po(t,e,"missing")?this.fromMissing(t):Jn("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case po.Added:return"ADD";case po.Current:return"CURRENT";case po.NoChange:return"NO_CHANGE";case po.Removed:return"REMOVE";case po.Reset:return"RESET";default:return Jn("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof wo)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof bo){if(t.newDoc instanceof zr){var e=t.newDoc;return{documentChange:{document:{name:this.toName(e.key),fields:this.toFields(e.data),updateTime:this.toVersion(e.version)},targetIds:t.updatedTargetIds,removedTargetIds:t.removedTargetIds}}}if(t.newDoc instanceof Gr){e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof Eo){var n=void 0;return t.cause&&(n={code:function(t){if(void 0===t)return Yi.OK;switch(t){case er.OK:return Yi.OK;case er.CANCELLED:return Yi.CANCELLED;case er.UNKNOWN:return Yi.UNKNOWN;case er.DEADLINE_EXCEEDED:return Yi.DEADLINE_EXCEEDED;case er.RESOURCE_EXHAUSTED:return Yi.RESOURCE_EXHAUSTED;case er.INTERNAL:return Yi.INTERNAL;case er.UNAVAILABLE:return Yi.UNAVAILABLE;case er.UNAUTHENTICATED:return Yi.UNAUTHENTICATED;case er.INVALID_ARGUMENT:return Yi.INVALID_ARGUMENT;case er.NOT_FOUND:return Yi.NOT_FOUND;case er.ALREADY_EXISTS:return Yi.ALREADY_EXISTS;case er.PERMISSION_DENIED:return Yi.PERMISSION_DENIED;case er.FAILED_PRECONDITION:return Yi.FAILED_PRECONDITION;case er.ABORTED:return Yi.ABORTED;case er.OUT_OF_RANGE:return Yi.OUT_OF_RANGE;case er.UNIMPLEMENTED:return Yi.UNIMPLEMENTED;case er.DATA_LOSS:return Yi.DATA_LOSS;default:return Jn("Unknown status code: "+t)}}(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return Jn("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=t.response_type;if(Po(t,n,"targetChange")){Mo(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],o=t.targetChange.resumeToken||this.emptyByteString(),s=t.targetChange.cause,a=s&&this.fromRpcStatus(s);e=new Eo(r,i,o,a||null)}else if(Po(t,n,"documentChange")){Mo(t.documentChange,"documentChange"),Mo(t.documentChange.document,"documentChange.name"),Mo(t.documentChange.document.name,"documentChange.document.name"),Mo(t.documentChange.document.updateTime,"documentChange.document.updateTime");var u=t.documentChange,c=this.fromName(u.document.name),h=this.fromVersion(u.document.updateTime),l=this.fromFields(u.document.fields||{}),f=new zr(c,h,l,{}),d=u.targetIds||[],p=u.removedTargetIds||[];e=new bo(d,p,f.key,f)}else if(Po(t,n,"documentDelete")){Mo(t.documentDelete,"documentDelete"),Mo(t.documentDelete.document,"documentDelete.document");var m=t.documentDelete;c=this.fromName(m.document),h=m.readTime?this.fromVersion(m.readTime):_i.forDeletedDoc(),f=new Gr(c,h),p=m.removedTargetIds||[];e=new bo([],p,f.key,f)}else if(Po(t,n,"documentRemove")){Mo(t.documentRemove,"documentRemove"),Mo(t.documentRemove.document,"documentRemove");var y=t.documentRemove;c=this.fromName(y.document),p=y.removedTargetIds||[];e=new bo([],p,c,null)}else{if(!Po(t,n,"filter"))return Jn("Unknown change type "+JSON.stringify(t));Mo(t.filter,"filter"),Mo(t.filter.targetId,"filter.targetId");var g=t.filter,v=g.count||0,b=new Ji(v),w=g.targetId;e=new wo(w,b)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?po.NoChange:"ADD"===t?po.Added:"REMOVE"===t?po.Removed:"CURRENT"===t?po.Current:"RESET"===t?po.Reset:Jn("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!Po(t,t.response_type,"targetChange"))return _i.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?_i.MIN:e.readTime?this.fromVersion(e.readTime):_i.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof Qi)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof ji)e={delete:this.toName(t.key)};else if(t instanceof Ki)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof Wi))return Jn("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map(function(t){return n.toFieldTransform(t)})}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):Ui.NONE;if(t.update){Mo(t.update.name,"name");var r=this.fromName(t.update.name),i=this.fromFields(t.update.fields||{});if(t.updateMask){var o=this.fromDocumentMask(t.updateMask);return new Ki(r,i,o,n)}return new Qi(r,i,n)}if(t.delete){r=this.fromName(t.delete);return new ji(r,n)}if(t.transform){r=this.fromName(t.transform.document);var s=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return Zn(!0===n.exists,'Transforms only support precondition "exists == true"'),new Wi(r,s)}return Jn("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return Zn(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:Jn("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?Ui.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?Ui.exists(t.exists):Ui.NONE},t.prototype.fromWriteResult=function(t,e){var n=this,r=t.updateTime?this.fromVersion(t.updateTime):this.fromVersion(e),i=null;return t.transformResults&&t.transformResults.length>0&&(i=t.transformResults.map(function(t){return n.fromValue(t)})),new Bi(r,i)},t.prototype.fromWriteResults=function(t,e){var n=this;return t&&t.length>0?(Zn(void 0!==e,"Received a write result without a commit time"),t.map(function(t){return n.fromWriteResult(t,e)})):[]},t.prototype.toFieldTransform=function(t){var e=this,n=t.transform;if(n instanceof zi)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Gi)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements.map(function(t){return e.toValue(t)})}};if(n instanceof Hi)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements.map(function(t){return e.toValue(t)})}};throw Jn("Unknown transform: "+t.transform)},t.prototype.fromFieldTransform=function(t){var e=this,n=t.transform_type,r=null;if(Po(t,n,"setToServerValue"))Zn("REQUEST_TIME"===t.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(t)),r=zi.instance;else if(Po(t,n,"appendMissingElements")){var i=t.appendMissingElements.values||[];r=new Gi(i.map(function(t){return e.fromValue(t)}))}else if(Po(t,n,"removeAllFromArray")){i=t.removeAllFromArray.values||[];r=new Hi(i.map(function(t){return e.fromValue(t)}))}else Jn("Unknown transform proto: "+JSON.stringify(t));var o=Kr.fromServerFormat(t.fieldPath);return new Fi(o,r)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;Zn(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return Si.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}};if(t.path.isEmpty())e.parent=this.toQueryPath(Vr.EMPTY_PATH);else{var n=t.path;Zn(n.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(n.popLast()),e.structuredQuery.from=[{collectionId:n.lastSegment()}]}var r=this.toFilter(t.filters);r&&(e.structuredQuery.where=r);var i=this.toOrder(t.orderBy);i&&(e.structuredQuery.orderBy=i);var o=this.toInt32Value(t.limit);return void 0!==o&&(e.structuredQuery.limit=o),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0;if(r>0){Zn(1===r,"StructuredQuery.from with more than one collection is not supported.");var i=n.from[0];e=e.child(i.collectionId)}var o=[];n.where&&(o=this.fromFilter(n.where));var s=[];n.orderBy&&(s=this.fromOrder(n.orderBy));var a=null;n.limit&&(a=this.fromInt32Value(n.limit));var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var c=null;return n.endAt&&(c=this.fromCursor(n.endAt)),new Si(e,s,o,a,u,c)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case Ei.Listen:return null;case Ei.ExistenceFilterMismatch:return"existence-filter-mismatch";case Ei.LimboResolution:return"limbo-document";default:return Jn("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return(e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)}).targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(t){return t instanceof Ci?e.toRelationFilter(t):e.toUnaryFilter(t)});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromRelationFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):Jn("Unknown filter: "+JSON.stringify(t)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},t.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},t.prototype.toCursor=function(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},t.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new ki(r,n)},t.prototype.toDirection=function(t){return Ao[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return Ai.ASCENDING;case"DESCENDING":return Ai.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return ko[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return Ii.EQUAL;case"GREATER_THAN":return Ii.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return Ii.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return Ii.LESS_THAN;case"LESS_THAN_OR_EQUAL":return Ii.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return Ii.ARRAY_CONTAINS;case"OPERATOR_UNSPECIFIED":return Jn("Unspecified relation");default:return Jn("Unknown relation")}},t.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return Kr.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new Ri(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.toRelationFilter=function(t){return t instanceof Ci?{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}:Jn("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromRelationFilter=function(t){return new Ci(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},t.prototype.toUnaryFilter=function(t){return t instanceof Ni?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}}:t instanceof Di?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}:Jn("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return new Ni(e);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return new Di(n);case"OPERATOR_UNSPECIFIED":return Jn("Unspecified filter");default:return Jn("Unknown filter")}},t.prototype.toDocumentMask=function(t){var e=[];return t.fields.forEach(function(t){return e.push(t.canonicalString())}),{fieldPaths:e}},t.prototype.fromDocumentMask=function(t){var e=(t.fieldPaths||[]).map(function(t){return Kr.fromServerFormat(t)});return xi.fromArray(e)},t}();function Po(t,e,n){return e===n||!e&&n in t}var Lo="FirebaseError",qo=Error.captureStackTrace,xo=function(){return function(t,e){if(this.code=t,this.message=e,qo)qo(this,Fo.prototype.create);else try{throw Error.apply(this,arguments)}catch(t){this.name=Lo,Object.defineProperty(this,"stack",{get:function(){return t.stack}})}}}();xo.prototype=Object.create(Error.prototype),xo.prototype.constructor=xo,xo.prototype.name=Lo;var Fo=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n,this.pattern=/\{\$([^}]+)}/g}return t.prototype.create=function(t,e){void 0===e&&(e={});var n,r=this.errors[t],i=this.service+"/"+t;n=void 0===r?"Error":r.replace(this.pattern,function(t,n){var r=e[n];return void 0!==r?r.toString():"<"+n+"?>"}),n=this.serviceName+": "+n+" ("+i+").";var o=new xo(i,n);for(var s in e)e.hasOwnProperty(s)&&"_"!==s.slice(-1)&&(o[s]=e[s]);return o},t}(),Bo=(function(t){function e(){var e=t.call(this)||this;e.chain_=[],e.buf_=[],e.W_=[],e.pad_=[],e.inbuf_=0,e.total_=0,e.blockSize=64,e.pad_[0]=128;for(var n=1;n>>31)}var o,s,a=this.chain_[0],u=this.chain_[1],c=this.chain_[2],h=this.chain_[3],l=this.chain_[4];for(r=0;r<80;r++){r<40?r<20?(o=h^u&(c^h),s=1518500249):(o=u^c^h,s=1859775393):r<60?(o=u&c|h&(u|c),s=2400959708):(o=u^c^h,s=3395469782);i=(a<<5|a>>>27)+o+l+s+n[r]&4294967295;l=h,h=c,c=4294967295&(u<<30|u>>>2),u=a,a=i}this.chain_[0]=this.chain_[0]+a&4294967295,this.chain_[1]=this.chain_[1]+u&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+h&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295},e.prototype.update=function(t,e){if(null!=t){void 0===e&&(e=t.length);for(var n=e-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r=56;n--)this.buf_[n]=255&e,e/=256;this.compress_(this.buf_);var r=0;for(n=0;n<5;n++)for(var i=24;i>=0;i-=8)t[r]=this.chain_[n]>>i&255,++r;return t}}(function(){return function(){this.blockSize=-1}}()),function(){function t(t){this.sendFn=t.sendFn,this.closeFn=t.closeFn}return t.prototype.onOpen=function(t){Zn(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},t.prototype.onClose=function(t){Zn(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},t.prototype.onMessage=function(t){Zn(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},t.prototype.close=function(){this.closeFn()},t.prototype.send=function(t){this.sendFn(t)},t.prototype.callOnOpen=function(){Zn(void 0!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},t.prototype.callOnClose=function(t){Zn(void 0!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},t.prototype.callOnMessage=function(t){Zn(void 0!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},t}()),Uo="Connection",Vo={BatchGetDocuments:"batchGet",Commit:"commit"},Qo="gl-js/ fire/"+Wn,Ko=function(){function t(t){this.databaseId=t.databaseId,this.pool=new Kn;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host}return t.prototype.modifyHeadersForRequest=function(t,e){if(e)for(var n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n]);t["X-Goog-Api-Client"]=Qo},t.prototype.invokeRPC=function(t,e,n){var r=this,i=this.makeUrl(t);return new Promise(function(o,s){r.pool.getObject(function(a){a.listenOnce(Vn.COMPLETE,function(){try{switch(a.getLastErrorCode()){case Un.NO_ERROR:var e=a.getResponseJson();Hn(Uo,"XHR received:",JSON.stringify(e)),o(e);break;case Un.TIMEOUT:Hn(Uo,'RPC "'+t+'" timed out'),s(new nr(er.DEADLINE_EXCEEDED,"Request time out"));break;case Un.HTTP_ERROR:var n=a.getStatus();Hn(Uo,'RPC "'+t+'" failed with status:',n,"response text:",a.getResponseText()),n>0?s(new nr(function(t){switch(t){case 200:return er.OK;case 400:return er.INVALID_ARGUMENT;case 401:return er.UNAUTHENTICATED;case 403:return er.PERMISSION_DENIED;case 404:return er.NOT_FOUND;case 409:return er.ABORTED;case 416:return er.OUT_OF_RANGE;case 429:return er.RESOURCE_EXHAUSTED;case 499:return er.CANCELLED;case 500:return er.UNKNOWN;case 501:return er.UNIMPLEMENTED;case 503:return er.UNAVAILABLE;case 504:return er.DEADLINE_EXCEEDED;default:return t>=200&&t<300?er.OK:t>=400&&t<500?er.FAILED_PRECONDITION:t>=500&&t<600?er.INTERNAL:er.UNKNOWN}}(n),"Server responded with status "+a.getStatusText())):(Hn(Uo,'RPC "'+t+'" failed'),s(new nr(er.UNAVAILABLE,"Connection failed.")));break;default:Jn('RPC "'+t+'" failed with unanticipated webchannel error '+a.getLastErrorCode()+": "+a.getLastError()+", giving up.")}}finally{Hn(Uo,'RPC "'+t+'" completed.'),r.pool.releaseObject(a)}});var u=JSON.stringify(e);Hn(Uo,"XHR sending: ",i+" "+u);var c={"Content-Type":"text/plain"};r.modifyHeadersForRequest(c,n),a.send(i,"POST",u,c,15)})})},t.prototype.invokeStreamingRPC=function(t,e,n){return this.invokeRPC(t,e,n)},t.prototype.openStream=function(t,e){var n=[this.baseUrl,"/","google.firestore.v1beta1.Firestore","/",t,"/channel"],r=Bn(),i={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(i.initMessageHeaders,e),"object"==typeof navigator&&"ReactNative"===navigator.product||(i.httpHeadersOverwriteParam="$httpHeaders");var o=n.join("");Hn(Uo,"Creating WebChannel: "+o+" "+i);var s=r.createWebChannel(o,i),a=!1,u=!1,c=new Bo({sendFn:function(t){u?Hn(Uo,"Not sending because WebChannel is closed:",t):(a||(Hn(Uo,"Opening WebChannel transport."),s.open(),a=!0),Hn(Uo,"WebChannel sending:",t),s.send(t))},closeFn:function(){return s.close()}}),h=function(t,e){s.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})};return h(Qn.EventType.OPEN,function(){u||Hn(Uo,"WebChannel transport opened.")}),h(Qn.EventType.CLOSE,function(){u||(u=!0,Hn(Uo,"WebChannel transport closed"),c.callOnClose())}),h(Qn.EventType.ERROR,function(t){u||(u=!0,Hn(Uo,"WebChannel transport errored:",t),c.callOnClose(new nr(er.UNAVAILABLE,"The operation could not be completed")))}),h(Qn.EventType.MESSAGE,function(t){if(!u){var e=t.data[0];Zn(!!e,"Got a webchannel message without data.");var n=e.error||e[0]&&e[0].error;if(n){Hn(Uo,"WebChannel received error:",n);var r=n.status,i=function(t){var e=Yi[t];if(void 0!==e)return $i(e)}(r),o=n.message;void 0===i&&(i=er.INTERNAL,o="Unknown error status: "+r+" with message "+n.message),u=!0,c.callOnClose(new nr(i,o)),s.close()}else Hn(Uo,"WebChannel received:",e),c.callOnMessage(e)}}),setTimeout(function(){c.callOnOpen()},0),c},t.prototype.makeUrl=function(t){var e=Vo[t];Zn(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1beta1"];return n.push("/projects/"),n.push(this.databaseId.projectId),n.push("/databases/"),n.push(this.databaseId.database),n.push("/documents"),n.push(":"),n.push(e),n.join("")},t}(),Wo=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return Object.defineProperty(t.prototype,"document",{get:function(){return"undefined"!=typeof document?document:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"window",{get:function(){return"undefined"!=typeof window?window:null},enumerable:!0,configurable:!0}),t.prototype.loadConnection=function(t){return Promise.resolve(new Ko(t))},t.prototype.newSerializer=function(t){return new _o(t,{useProto3Json:!0})},t.prototype.formatJSON=function(t){return JSON.stringify(t)},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();$n.setPlatform(new Wo);var jo,zo=function(){function t(t,e){var n=this;this.previousValue=t,e&&(e.sequenceNumberHandler=function(t){return n.setPreviousValue(t)},this.writeNewSequenceNumber=function(t){return e.writeSequenceNumber(t)})}return t.prototype.setPreviousValue=function(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue},t.prototype.next=function(){var t=++this.previousValue;return this.writeNewSequenceNumber&&this.writeNewSequenceNumber(t),t},t.INVALID=-1,t}(),Go=function(){return function(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}}();!function(t){t.All="all",t.ListenStreamIdle="listen_stream_idle",t.ListenStreamConnectionBackoff="listen_stream_connection_backoff",t.WriteStreamIdle="write_stream_idle",t.WriteStreamConnectionBackoff="write_stream_connection_backoff",t.OnlineStateTimeout="online_state_timeout",t.ClientMetadataRefresh="client_metadata_refresh",t.LruGarbageCollection="lru_garbage_collection"}(jo||(jo={}));var Ho=function(){function t(t,e,n,r,i){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new Go,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.catch=this.deferred.promise.catch.bind(this.deferred.promise),this.deferred.promise.catch(function(t){})}return t.createAndSchedule=function(e,n,r,i,o){var s=new t(e,n,Date.now()+r,i,o);return s.start(r),s},t.prototype.start=function(t){var e=this;this.timerHandle=setTimeout(function(){return e.handleDelayElapsed()},t)},t.prototype.skipDelay=function(){return this.handleDelayElapsed()},t.prototype.cancel=function(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new nr(er.CANCELLED,"Operation cancelled"+(t?": "+t:""))))},t.prototype.handleDelayElapsed=function(){var t=this;this.asyncQueue.enqueueAndForget(function(){return null!==t.timerHandle?(t.clearTimeout(),t.op().then(function(e){return t.deferred.resolve(e)})):Promise.resolve()})},t.prototype.clearTimeout=function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)},t}(),Xo=function(){function t(){this.tail=Promise.resolve(),this.delayedOperations=[],this.operationInProgress=!1}return t.prototype.enqueueAndForget=function(t){this.enqueue(t)},t.prototype.enqueue=function(t){var e=this;this.verifyNotFailed();var n=this.tail.then(function(){return e.operationInProgress=!0,t().catch(function(t){e.failure=t,e.operationInProgress=!1;var n=t.stack||t.message||"";throw Xn("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout(function(){throw t},0),t}).then(function(t){return e.operationInProgress=!1,t})});return this.tail=n,n},t.prototype.enqueueAfterDelay=function(t,e,n){var r=this;this.verifyNotFailed(),Zn(e>=0,"Attempted to schedule an operation with a negative delay of "+e),Zn(!this.containsDelayedOperation(t),"Attempted to schedule multiple operations with timer id "+t+".");var i=Ho.createAndSchedule(this,t,e,n,function(t){return r.removeDelayedOperation(t)});return this.delayedOperations.push(i),i},t.prototype.verifyNotFailed=function(){this.failure&&Jn("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},t.prototype.verifyOperationInProgress=function(){Zn(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(){return this.enqueue(function(){return Promise.resolve()})},t.prototype.containsDelayedOperation=function(t){for(var e=0,n=this.delayedOperations;e=0,"Delayed operation not found."),this.delayedOperations.splice(e,1)},t}(),Yo="",Jo="",Zo="",$o="";function ts(t){for(var e="",n=0;n0&&(e=ns(e)),e=es(t.get(n),e);return ns(e)}function es(t,e){for(var n=e,r=t.length,i=0;i=2,"Invalid path "+t),2===e)return Zn(t.charAt(0)===Yo&&t.charAt(1)===Jo,"Non-empty path "+t+" had length 2"),Vr.EMPTY_PATH;for(var n=e-2,r=[],i="",o=0;on)&&Jn('Invalid encoded resource path: "'+t+'"'),t.charAt(s+1)){case Jo:var a=t.substring(o,s),u=void 0;0===i.length?u=a:(u=i+=a,i=""),r.push(u);break;case Zo:i+=t.substring(o,s),i+="\0";break;case $o:i+=t.substring(o,s+1);break;default:Jn('Invalid encoded resource path: "'+t+'"')}o=s+2}return new Vr(r)}var is,os=-1,ss=function(){function t(t,e,n){this.batchId=t,this.localWriteTime=e,this.mutations=n,Zn(n.length>0,"Cannot create an empty mutation batch")}return t.prototype.applyToRemoteDocument=function(t,e,n){e&&Zn(e.key.isEqual(t),"applyToRemoteDocument: key "+t+" should match maybeDoc key\n "+e.key);var r=n.mutationResults;Zn(r.length===this.mutations.length,"Mismatch between mutations length\n ("+this.mutations.length+") and mutation results length\n ("+r.length+").");for(var i=0;i0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0)},t.getStore=function(t,e){return t.store(e)},t.prototype.runTransaction=function(t,e,n){var r=ds.open(this.db,t,e),i=n(r).catch(function(t){r.abort(t)}).toPromise();return r.completionPromise.then(function(){return i})},t.prototype.close=function(){this.db.close()},t}(),fs=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return ms(this.dbCursor.delete())},t}(),ds=function(){function t(t){var e=this;this.transaction=t,this.aborted=!1,this.completionDeferred=new Go,this.transaction.oncomplete=function(){e.completionDeferred.resolve()},this.transaction.onabort=function(){t.error?e.completionDeferred.reject(t.error):e.completionDeferred.resolve()},this.transaction.onerror=function(t){e.completionDeferred.reject(t.target.error)}}return t.open=function(e,n,r){return new t(e.transaction(r,n))},Object.defineProperty(t.prototype,"completionPromise",{get:function(){return this.completionDeferred.promise},enumerable:!0,configurable:!0}),t.prototype.abort=function(t){t&&this.completionDeferred.reject(t),this.aborted||(Hn("SimpleDb","Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return Zn(!!e,"Object store not part of transaction: "+t),new ps(e)},t}(),ps=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(Hn("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(Hn("SimpleDb","PUT",this.store.name,"",t),n=this.store.put(t)),ms(n)},t.prototype.add=function(t){return Hn("SimpleDb","ADD",this.store.name,t,t),ms(this.store.add(t))},t.prototype.get=function(t){var e=this;return ms(this.store.get(t)).next(function(n){return void 0===n&&(n=null),Hn("SimpleDb","GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return Hn("SimpleDb","DELETE",this.store.name,t),ms(this.store.delete(t))},t.prototype.count=function(){return Hn("SimpleDb","COUNT",this.store.name),ms(this.store.count())},t.prototype.loadAll=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.iterateCursor(n,function(t,e){r.push(e)}).next(function(){return r})},t.prototype.deleteAll=function(t,e){Hn("SimpleDb","DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},t.prototype.iterateSerial=function(t){var e=this.cursor({});return new hs(function(n,r){e.onerror=function(t){r(t.target.error)},e.onsuccess=function(e){var r=e.target.result;r?t(r.primaryKey,r.value).next(function(t){t?r.continue():n()}):n()}})},t.prototype.iterateCursor=function(t,e){var n=[];return new hs(function(r,i){t.onerror=function(t){i(t.target.error)},t.onsuccess=function(t){var i=t.target.result;if(i){var o=new fs(i),s=e(i.primaryKey,i.value,o);if(s instanceof hs){var a=s.catch(function(t){return o.done(),hs.reject(t)});n.push(a)}o.isDone?r():null===o.skipToKey?i.continue():i.continue(o.skipToKey)}else r()}}).next(function(){return hs.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(Zn(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}();function ms(t){return new hs(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){n(t.target.error)}})}var ys=function(){function t(t,e){this.referenceDelegate=t,this.serializer=e,this.targetIdGenerator=cs.forQueryCache()}return t.prototype.allocateTargetId=function(t){var e=this;return this.retrieveMetadata(t).next(function(n){return n.highestTargetId=e.targetIdGenerator.after(n.highestTargetId),e.saveMetadata(t,n).next(function(){return n.highestTargetId})})},t.prototype.getLastRemoteSnapshotVersion=function(t){return this.retrieveMetadata(t).next(function(t){return _i.fromTimestamp(new qr(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds))})},t.prototype.getHighestSequenceNumber=function(t){return bs(t.simpleDbTransaction)},t.prototype.setTargetsMetadata=function(t,e,n){var r=this;return this.retrieveMetadata(t).next(function(i){return i.highestListenSequenceNumber=e,n&&(i.lastRemoteSnapshotVersion=n.toTimestamp()),e>i.highestListenSequenceNumber&&(i.highestListenSequenceNumber=e),r.saveMetadata(t,i)})},t.prototype.addQueryData=function(t,e){var n=this;return this.saveQueryData(t,e).next(function(){return n.retrieveMetadata(t).next(function(r){return r.targetCount+=1,n.updateMetadataFromQueryData(e,r),n.saveMetadata(t,r)})})},t.prototype.updateQueryData=function(t,e){return this.saveQueryData(t,e)},t.prototype.removeQueryData=function(t,e){var n=this;return this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){return gs(t).delete(e.targetId)}).next(function(){return n.retrieveMetadata(t)}).next(function(e){return Zn(e.targetCount>0,"Removing from an empty query cache"),e.targetCount-=1,n.saveMetadata(t,e)})},t.prototype.removeTargets=function(t,e,n){var r=this,i=0,o=[];return gs(t).iterate(function(s,a){var u=r.serializer.fromDbTarget(a);u.sequenceNumber<=e&&void 0===n[u.targetId]&&(i++,o.push(r.removeQueryData(t,u)))}).next(function(){return hs.waitFor(o)}).next(function(){return i})},t.prototype.forEachTarget=function(t,e){var n=this;return gs(t).iterate(function(t,r){var i=n.serializer.fromDbTarget(r);e(i)})},t.prototype.retrieveMetadata=function(t){return vs(t.simpleDbTransaction)},t.prototype.saveMetadata=function(t,e){return(n=t,pa.getStore(n,Ws.store)).put(Ws.key,e);var n},t.prototype.saveQueryData=function(t,e){return gs(t).put(this.serializer.toDbTarget(e))},t.prototype.updateMetadataFromQueryData=function(t,e){var n=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n},t.prototype.getQueryCount=function(t){return this.retrieveMetadata(t).next(function(t){return t.targetCount})},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),i=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),o=null;return gs(t).iterate({range:i,index:Qs.queryTargetsIndexName},function(t,r,i){var s=n.serializer.fromDbTarget(r);e.isEqual(s.query)&&(o=s,i.done())}).next(function(){return o})},t.prototype.addMatchingKeys=function(t,e,n){var r=this,i=[],o=ws(t);return e.forEach(function(e){var s=ts(e.path);i.push(o.put(new Ks(n,s))),i.push(r.referenceDelegate.addReference(t,e))}),hs.waitFor(i)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,i=ws(t);return hs.forEach(e,function(e){var o=ts(e.path);return hs.waitFor([i.delete([n,o]),r.referenceDelegate.removeReference(t,e)])})},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=ws(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=ws(t),i=ao();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=rs(t[1]),o=new Wr(r);i=i.add(o)}).next(function(){return i})},t.prototype.containsKey=function(t,e){var n,r=ts(e.path),i=IDBKeyRange.bound([r],[(n=r,n+"\0")],!1,!0),o=0;return ws(t).iterate({index:Ks.documentTargetsIndex,keysOnly:!0,range:i},function(t,e,n){var r=t[0];t[1];0!==r&&(o++,n.done())}).next(function(){return o>0})},t.prototype.getQueryDataForTarget=function(t,e){var n=this;return gs(t).get(e).next(function(t){return t?n.serializer.fromDbTarget(t):null})},t}();function gs(t){return pa.getStore(t,Qs.store)}function vs(t){return ls.getStore(t,Ws.store).get(Ws.key).next(function(t){return Zn(null!==t,"Missing metadata row."),t})}function bs(t){return vs(t).next(function(t){return t.highestListenSequenceNumber})}function ws(t){return pa.getStore(t,Ks.store)}var Es=function(){function t(t){this.mapKeyFn=t,this.inner={}}return t.prototype.get=function(t){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0!==n)for(var r=0,i=n;r0){for(var i=Ns(t),o=ao(),s=0,a=e;s=0&&r<=Ms,"Unexpected schema upgrade from v"+n+" to v{toVersion}."),n<1&&r>=1&&(function(t){t.createObjectStore(Ps.store)}(t),function(t){t.createObjectStore(Ls.store,{keyPath:Ls.keyPath}),t.createObjectStore(qs.store,{keyPath:qs.keyPath,autoIncrement:!0}).createIndex(qs.userMutationsIndex,qs.userMutationsKeyPath,{unique:!0}),t.createObjectStore(xs.store)}(t),js(t),function(t){t.createObjectStore(Us.store)}(t));var o=hs.resolve();return n<3&&r>=3&&(0!==n&&(!function(t){t.deleteObjectStore(Ks.store),t.deleteObjectStore(Qs.store),t.deleteObjectStore(Ws.store)}(t),js(t)),o=o.next(function(){return function(t){var e=t.store(Ws.store),n=new Ws(0,0,_i.MIN.toTimestamp(),0);return e.put(Ws.key,n)}(e)})),n<4&&r>=4&&(0!==n&&(o=o.next(function(){return function(t,e){return e.store(qs.store).loadAll().next(function(n){t.deleteObjectStore(qs.store);var r=t.createObjectStore(qs.store,{keyPath:qs.keyPath,autoIncrement:!0});r.createIndex(qs.userMutationsIndex,qs.userMutationsKeyPath,{unique:!0});var i=e.store(qs.store),o=n.map(function(t){return i.put(t)});return hs.waitFor(o)})}(t,e)})),o=o.next(function(){!function(t){t.createObjectStore(Gs.store,{keyPath:Gs.keyPath})}(t),function(t){t.createObjectStore(zs.store,{keyPath:"id",autoIncrement:!0})}(t)})),n<5&&r>=5&&(o=o.next(function(){return i.removeAcknowledgedMutations(e)})),n<6&&r>=6&&(o=o.next(function(){return function(t){t.createObjectStore(Vs.store)}(t),i.addDocumentGlobal(e)})),n<7&&r>=7&&(o=o.next(function(){return i.ensureSequenceNumbers(e)})),o},t.prototype.addDocumentGlobal=function(t){var e=0;return t.store(Us.store).iterate(function(t,n){e+=Rs(n)}).next(function(){var n=new Vs(e);return t.store(Vs.store).put(Vs.key,n)})},t.prototype.removeAcknowledgedMutations=function(t){var e=this,n=t.store(Ls.store),r=t.store(qs.store);return n.loadAll().next(function(n){return hs.forEach(n,function(n){var i=IDBKeyRange.bound([n.userId,os],[n.userId,n.lastAcknowledgedBatchId]);return r.loadAll(qs.userMutationsIndex,i).next(function(r){return hs.forEach(r,function(r){Zn(r.userId===n.userId,"Cannot process batch "+r.batchId+" from unexpected user");var i=e.serializer.fromDbMutationBatch(r);return Js(t,n.userId,i).next(function(){})})})})})},t.prototype.ensureSequenceNumbers=function(t){var e=t.store(Ks.store),n=t.store(Us.store);return bs(t).next(function(t){var r=[];return n.iterate(function(n,i){var o=new Vr(n),s=function(t){return[0,ts(t)]}(o);r.push(e.get(s).next(function(n){return n?hs.resolve():function(n){return e.put(new Ks(0,ts(n),t))}(o)}))}).next(function(){return hs.waitFor(r)})})},t}();var _s=function(){return function(t,e){this.seconds=t,this.nanoseconds=e}}(),Ps=function(){function t(t,e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n}return t.store="owner",t.key="owner",t}();var Ls=function(){function t(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}return t.store="mutationQueues",t.keyPath="userId",t}(),qs=function(){function t(t,e,n,r){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.mutations=r}return t.store="mutations",t.keyPath="batchId",t.userMutationsIndex="userMutationsIndex",t.userMutationsKeyPath=["userId","batchId"],t}();var xs=function(){function t(){}return t.prefixForUser=function(t){return[t]},t.prefixForPath=function(t,e){return[t,ts(e)]},t.key=function(t,e,n){return[t,ts(e),n]},t.store="documentMutations",t.PLACEHOLDER=new t,t}();var Fs=function(){return function(t,e){this.path=t,this.readTime=e}}(),Bs=function(){return function(t,e){this.path=t,this.version=e}}(),Us=function(){function t(t,e,n,r){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r}return t.store="remoteDocuments",t}(),Vs=function(){function t(t){this.byteSize=t}return t.store="remoteDocumentGlobal",t.key="remoteDocumentGlobalKey",t}();var Qs=function(){function t(t,e,n,r,i,o){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.query=o}return t.store="targets",t.keyPath="targetId",t.queryTargetsIndexName="queryTargetsIndex",t.queryTargetsKeyPath=["canonicalId","targetId"],t}(),Ks=function(){function t(t,e,n){this.targetId=t,this.path=e,this.sequenceNumber=n,Zn(0===t==(void 0!==n),"A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number")}return t.store="targetDocuments",t.keyPath=["targetId","path"],t.documentTargetsIndex="documentTargetsIndex",t.documentTargetsKeyPath=["path","targetId"],t}(),Ws=function(){function t(t,e,n,r){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n,this.targetCount=r}return t.key="targetGlobalKey",t.store="targetGlobal",t}();function js(t){t.createObjectStore(Ks.store,{keyPath:Ks.keyPath}).createIndex(Ks.documentTargetsIndex,Ks.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(Qs.store,{keyPath:Qs.keyPath}).createIndex(Qs.queryTargetsIndexName,Qs.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(Ws.store)}var zs=function(){function t(t){this.changes=t}return t.store="remoteDocumentChanges",t.keyPath="id",t}();var Gs=function(){function t(t,e,n,r,i){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r,this.lastProcessedDocumentChangeId=i}return t.store="clientMetadata",t.keyPath="clientId",t}();var Hs=[Ls.store,qs.store,xs.store,Us.store,Qs.store,Ps.store,Ws.store,Ks.store].concat([Gs.store,zs.store]).concat([Vs.store]),Xs=function(){function t(t,e,n){this.userId=t,this.serializer=e,this.referenceDelegate=n,this.documentKeysByBatchId={}}return t.forUser=function(e,n,r){return Zn(""!==e.uid,"UserID must not be an empty string."),new t(e.isAuthenticated()?e.uid:"",n,r)},t.prototype.checkEmpty=function(t){var e=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return $s(t).iterate({index:qs.userMutationsIndex,range:n},function(t,n,r){e=!1,r.done()}).next(function(){return e})},t.prototype.acknowledgeBatch=function(t,e,n){return this.getMutationQueueMetadata(t).next(function(r){var i=e.batchId;return Zn(i>r.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),r.lastAcknowledgedBatchId=i,r.lastStreamToken=Zs(n),ea(t).put(r)})},t.prototype.getLastStreamToken=function(t){return this.getMutationQueueMetadata(t).next(function(t){return t.lastStreamToken})},t.prototype.setLastStreamToken=function(t,e){return this.getMutationQueueMetadata(t).next(function(n){return n.lastStreamToken=Zs(e),ea(t).put(n)})},t.prototype.addMutationBatch=function(t,e,n){var r=this,i=ta(t),o=$s(t);return o.add({}).next(function(t){Zn("number"==typeof t,"Auto-generated key is not a number");var s=new ss(t,e,n),a=r.serializer.toDbMutationBatch(r.userId,s);r.documentKeysByBatchId[t]=s.keys();for(var u=[],c=0,h=n;c=i,"Should have found mutation after "+i),s=n.serializer.fromDbMutationBatch(e)),r.done()}).next(function(){return s})})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound([this.userId,os],[this.userId,Number.POSITIVE_INFINITY]);return $s(t).loadAll(qs.userMutationsIndex,n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=xs.prefixForPath(this.userId,e.path),i=IDBKeyRange.lowerBound(r),o=[];return ta(t).iterate({range:i},function(r,i,s){var a=r[0],u=r[1],c=r[2],h=rs(u);if(a===n.userId&&e.path.isEqual(h))return $s(t).get(c).next(function(t){if(!t)throw Jn("Dangling document-mutation reference found: "+r+" which points to "+c);Zn(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+c),o.push(n.serializer.fromDbMutationBatch(t))});s.done()}).next(function(){return o})},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new qi(Nr),i=[];return e.forEach(function(e){var o=xs.prefixForPath(n.userId,e.path),s=IDBKeyRange.lowerBound(o),a=ta(t).iterate({range:s},function(t,i,o){var s=t[0],a=t[1],u=t[2],c=rs(a);s===n.userId&&e.path.isEqual(c)?r=r.add(u):o.done()});i.push(a)}),hs.waitFor(i).next(function(){return n.lookupMutationBatches(t,r)})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;Zn(!e.isDocumentQuery(),"Document queries shouldn't go down this path");var r=e.path,i=r.length+1,o=xs.prefixForPath(this.userId,r),s=IDBKeyRange.lowerBound(o),a=new qi(Nr);return ta(t).iterate({range:s},function(t,e,o){var s=t[0],u=t[1],c=t[2],h=rs(u);s===n.userId&&r.isPrefixOf(h)?h.length===i&&(a=a.add(c)):o.done()}).next(function(){return n.lookupMutationBatches(t,a)})},t.prototype.lookupMutationBatches=function(t,e){var n=this,r=[],i=[];return e.forEach(function(e){i.push($s(t).get(e).next(function(t){if(null===t)throw Jn("Dangling document-mutation reference found, which points to "+e);Zn(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),r.push(n.serializer.fromDbMutationBatch(t))}))}),hs.waitFor(i).next(function(){return r})},t.prototype.removeMutationBatch=function(t,e){var n=this;return Js(t.simpleDbTransaction,this.userId,e).next(function(r){return n.removeCachedMutationKeys(e.batchId),hs.forEach(r,function(e){return n.referenceDelegate.removeMutationReference(t,e)})})},t.prototype.removeCachedMutationKeys=function(t){delete this.documentKeysByBatchId[t]},t.prototype.performConsistencyCheck=function(t){var e=this;return this.checkEmpty(t).next(function(n){if(!n)return hs.resolve();var r=IDBKeyRange.lowerBound(xs.prefixForUser(e.userId)),i=[];return ta(t).iterate({range:r},function(t,n,r){if(t[0]===e.userId){var o=rs(t[1]);i.push(o)}else r.done()}).next(function(){Zn(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map(function(t){return t.canonicalString()}))})})},t.prototype.containsKey=function(t,e){return Ys(t,this.userId,e)},t.prototype.getMutationQueueMetadata=function(t){var e=this;return ea(t).get(this.userId).next(function(t){return t||new Ls(e.userId,os,"")})},t}();function Ys(t,e,n){var r=xs.prefixForPath(e,n.path),i=r[1],o=IDBKeyRange.lowerBound(r),s=!1;return ta(t).iterate({range:o,keysOnly:!0},function(t,n,r){var o=t[0],a=t[1];t[2];o===e&&a===i&&(s=!0),r.done()}).next(function(){return s})}function Js(t,e,n){var r=t.store(qs.store),i=t.store(xs.store),o=[],s=IDBKeyRange.only(n.batchId),a=0,u=r.iterate({range:s},function(t,e,n){return a++,n.delete()});o.push(u.next(function(){Zn(1===a,"Dangling document-mutation reference found: Missing batch "+n.batchId)}));for(var c=[],h=0,l=n.mutations;hh.params.maximumSequenceNumbersToCollect?(Hn("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+h.params.maximumSequenceNumbersToCollect+" from "+e),r=h.params.maximumSequenceNumbersToCollect):r=e,s=Date.now(),h.nthSequenceNumber(t,r)}).next(function(r){return n=r,a=Date.now(),h.removeTargets(t,n,e)}).next(function(e){return i=e,u=Date.now(),h.removeOrphanedDocuments(t,n)}).next(function(t){(c=Date.now(),zn()<=qn.DEBUG)&&Hn("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(s-o)+"ms\n\tDetermined least recently used "+r+" in "+(a-s)+"ms\n\tRemoved "+i+" targets in "+(u-a)+"ms\n\tRemoved "+t+" documents in "+(c-u)+"ms\nTotal Duration: "+(c-o)+"ms");return hs.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:t})})},t}(),ca="IndexedDbPersistence",ha="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",la="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `experimentalTabSynchronization:true` in all tabs.",fa="This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.",da=function(t){function e(e,n){var r=t.call(this)||this;return r.simpleDbTransaction=e,r.currentSequenceNumber=n,r}return s(e,t),e}(function(){return function(){}}()),pa=function(){function t(e,n,r,i,o,s,a){if(this.persistenceKey=e,this.clientId=n,this.queue=i,this.multiClientParams=a,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.inForeground=!1,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(t){return Promise.resolve()},!t.isAvailable())throw new nr(er.UNIMPLEMENTED,fa);if(this.referenceDelegate=new va(this,s),this.dbName=e+t.MAIN_DATABASE,this.serializer=new na(o),this.document=r.document,this.allowTabSynchronization=void 0!==a,this.queryCache=new ys(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new Is(this.serializer,this.allowTabSynchronization),!r.window||!r.window.localStorage)throw new nr(er.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=r.window,this.webStorage=this.window.localStorage}return t.getStore=function(t,e){if(t instanceof da)return ls.getStore(t.simpleDbTransaction,e);throw Jn("IndexedDbPersistence must use instances of IndexedDbTransaction")},t.createIndexedDbPersistence=function(e,n,r,i,o,s){return a(this,void 0,void 0,function(){var a;return u(this,function(u){switch(u.label){case 0:return[4,(a=new t(e,n,r,i,o,s)).start()];case 1:return u.sent(),[2,a]}})})},t.createMultiClientIndexedDbPersistence=function(e,n,r,i,o,s,c){return a(this,void 0,void 0,function(){var a;return u(this,function(u){switch(u.label){case 0:return[4,(a=new t(e,n,r,i,o,s,c)).start()];case 1:return u.sent(),[2,a]}})})},t.prototype.start=function(){var t=this;return Zn(!this.started,"IndexedDbPersistence double-started!"),Zn(null!==this.window,"Expected 'window' to be defined"),ls.openOrCreate(this.dbName,Ms,new Os(this.serializer)).then(function(e){t.simpleDb=e}).then(function(){return t.startRemoteDocumentCache()}).then(function(){return t.attachVisibilityHandler(),t.attachWindowUnloadHook(),t.updateClientMetadataAndTryBecomePrimary().then(function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()})}).then(function(){return t.simpleDb.runTransaction("readonly",[Ws.store],function(e){return bs(e).next(function(e){var n=t.multiClientParams?t.multiClientParams.sequenceNumberSyncer:void 0;t.listenSequence=new zo(e,n)})})}).then(function(){t._started=!0}).catch(function(e){return t.simpleDb&&t.simpleDb.close(),Promise.reject(e)})},t.prototype.startRemoteDocumentCache=function(){var t=this;return this.simpleDb.runTransaction("readonly",Hs,function(e){return t.remoteDocumentCache.start(e)})},t.prototype.setPrimaryStateListener=function(t){var e=this;return this.primaryStateListener=function(n){return a(e,void 0,void 0,function(){return u(this,function(e){return this.started?[2,t(n)]:[2]})})},t(this.isPrimary)},t.prototype.setNetworkEnabled=function(t){var e=this;this.networkEnabled!==t&&(this.networkEnabled=t,this.queue.enqueueAndForget(function(){return a(e,void 0,void 0,function(){return u(this,function(t){switch(t.label){case 0:return this.started?[4,this.updateClientMetadataAndTryBecomePrimary()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})}))},t.prototype.updateClientMetadataAndTryBecomePrimary=function(){var t=this;return this.simpleDb.runTransaction("readwrite",Hs,function(e){return ga(e).put(new Gs(t.clientId,Date.now(),t.networkEnabled,t.inForeground,t.remoteDocumentCache.lastProcessedDocumentChangeId)).next(function(){if(t.isPrimary)return t.verifyPrimaryLease(e).next(function(e){e||(t.isPrimary=!1,t.queue.enqueueAndForget(function(){return t.primaryStateListener(!1)}))})}).next(function(){return t.canActAsPrimary(e)}).next(function(n){var r=t.isPrimary;return t.isPrimary=n,r!==t.isPrimary&&t.queue.enqueueAndForget(function(){return t.primaryStateListener(t.isPrimary)}),r&&!t.isPrimary?t.releasePrimaryLeaseIfHeld(e):t.isPrimary?t.acquireOrExtendPrimaryLease(e):void 0})})},t.prototype.verifyPrimaryLease=function(t){var e=this;return ya(t).get(Ps.key).next(function(t){return hs.resolve(e.isLocalClient(t))})},t.prototype.removeClientMetadata=function(t){return ga(t).delete(this.clientId)},t.prototype.maybeGarbageCollectMultiClientState=function(){return a(this,void 0,void 0,function(){var e,n,r=this;return u(this,function(i){switch(i.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,18e5)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),n=[],[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(i){var o=t.getStore(i,Gs.store);return o.loadAll().next(function(t){e=r.filterActiveClients(t,18e5),n=t.filter(function(t){return-1===e.indexOf(t)})}).next(function(){return hs.forEach(n,function(t){return o.delete(t.clientId)})}).next(function(){if((e=e.filter(function(t){return t.clientId!==r.clientId})).length>0){var t=e.map(function(t){return t.lastProcessedDocumentChangeId||0}),n=Math.min.apply(Math,t);return r.remoteDocumentCache.removeDocumentChangesThroughChangeId(i,n)}})})]);case 1:i.sent(),n.forEach(function(t){r.window.localStorage.removeItem(r.zombiedClientLocalStorageKey(t.clientId))}),i.label=2;case 2:return[2]}})})},t.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var t=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(jo.ClientMetadataRefresh,4e3,function(){return t.updateClientMetadataAndTryBecomePrimary().then(function(){return t.maybeGarbageCollectMultiClientState()}).then(function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()})})},t.prototype.isLocalClient=function(t){return!!t&&t.ownerId===this.clientId},t.prototype.canActAsPrimary=function(t){var e=this;return ya(t).get(Ps.key).next(function(n){if(null!==n&&e.isWithinAge(n.leaseTimestampMs,5e3)&&!e.isClientZombied(n.ownerId)){if(e.isLocalClient(n)&&e.networkEnabled)return!0;if(!e.isLocalClient(n)){if(!n.allowTabSynchronization)throw new nr(er.FAILED_PRECONDITION,la);return!1}}return!(!e.networkEnabled||!e.inForeground)||ga(t).loadAll().next(function(t){return void 0===e.filterActiveClients(t,5e3).find(function(t){if(e.clientId!==t.clientId){var n=!e.networkEnabled&&t.networkEnabled,r=!e.inForeground&&t.inForeground,i=e.networkEnabled===t.networkEnabled;if(n||r&&i)return!0}return!1})})}).next(function(t){return e.isPrimary!==t&&Hn(ca,"Client "+(t?"is":"is not")+" eligible for a primary lease."),t})},t.prototype.shutdown=function(t){return a(this,void 0,void 0,function(){var e=this;return u(this,function(n){switch(n.label){case 0:return this._started=!1,this.markClientZombied(),this.clientMetadataRefresher&&this.clientMetadataRefresher.cancel(),this.detachVisibilityHandler(),this.detachWindowUnloadHook(),[4,this.simpleDb.runTransaction("readwrite",[Ps.store,Gs.store],function(t){return e.releasePrimaryLeaseIfHeld(t).next(function(){return e.removeClientMetadata(t)})})];case 1:return n.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),t?[4,ls.delete(this.dbName)]:[3,3];case 2:n.sent(),n.label=3;case 3:return[2]}})})},t.prototype.filterActiveClients=function(t,e){var n=this;return t.filter(function(t){return n.isWithinAge(t.updateTimeMs,e)&&!n.isClientZombied(t.clientId)})},t.prototype.getActiveClients=function(){var t=this;return this.simpleDb.runTransaction("readonly",[Gs.store],function(e){return ga(e).loadAll().next(function(e){return t.filterActiveClients(e,18e5).map(function(t){return t.clientId})})})},Object.defineProperty(t.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),t.prototype.getMutationQueue=function(t){return Zn(this.started,"Cannot initialize MutationQueue before persistence is started."),Xs.forUser(t,this.serializer,this.referenceDelegate)},t.prototype.getQueryCache=function(){return Zn(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},t.prototype.getRemoteDocumentCache=function(){return Zn(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},t.prototype.runTransaction=function(t,e,n){var r=this;return Hn(ca,"Starting transaction:",t),this.simpleDb.runTransaction("readonly"===e?"readonly":"readwrite",Hs,function(i){return"readwrite-primary"===e?r.verifyPrimaryLease(i).next(function(e){if(!e)throw Xn("Failed to obtain primary lease for action '"+t+"'."),r.isPrimary=!1,r.queue.enqueueAndForget(function(){return r.primaryStateListener(!1)}),new nr(er.FAILED_PRECONDITION,ha);return n(new da(i,r.listenSequence.next()))}).next(function(t){return r.acquireOrExtendPrimaryLease(i).next(function(){return t})}):r.verifyAllowTabSynchronization(i).next(function(){return n(new da(i,r.listenSequence.next()))})})},t.prototype.verifyAllowTabSynchronization=function(t){var e=this;return ya(t).get(Ps.key).next(function(t){if(null!==t&&e.isWithinAge(t.leaseTimestampMs,5e3)&&!e.isClientZombied(t.ownerId)&&!e.isLocalClient(t)&&!t.allowTabSynchronization)throw new nr(er.FAILED_PRECONDITION,la)})},t.prototype.acquireOrExtendPrimaryLease=function(t){var e=new Ps(this.clientId,this.allowTabSynchronization,Date.now());return ya(t).put(Ps.key,e)},t.isAvailable=function(){return ls.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.releasePrimaryLeaseIfHeld=function(t){var e=this,n=ya(t);return n.get(Ps.key).next(function(t){return e.isLocalClient(t)?(Hn(ca,"Releasing primary lease."),n.delete(Ps.key)):hs.resolve()})},t.prototype.isWithinAge=function(t,e){var n=Date.now();return!(tn)||(Xn("Detected an update time that is in the future: "+t+" > "+n),!1))},t.prototype.attachVisibilityHandler=function(){var t=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.documentVisibilityHandler=function(){t.queue.enqueueAndForget(function(){return t.inForeground="visible"===t.document.visibilityState,t.updateClientMetadataAndTryBecomePrimary()})},this.document.addEventListener("visibilitychange",this.documentVisibilityHandler),this.inForeground="visible"===this.document.visibilityState)},t.prototype.detachVisibilityHandler=function(){this.documentVisibilityHandler&&(Zn(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.documentVisibilityHandler),this.documentVisibilityHandler=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;"function"==typeof this.window.addEventListener&&(this.windowUnloadHandler=function(){t.markClientZombied(),t.queue.enqueueAndForget(function(){return t.shutdown()})},this.window.addEventListener("unload",this.windowUnloadHandler))},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(Zn("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.isClientZombied=function(t){try{var e=null!==this.webStorage.getItem(this.zombiedClientLocalStorageKey(t));return Hn(ca,"Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return Xn(ca,"Failed to get zombied client id.",t),!1}},t.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(t){Xn("Failed to set zombie client id.",t)}},t.prototype.removeClientZombiedEntry=function(){try{this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId))}catch(t){}},t.prototype.zombiedClientLocalStorageKey=function(t){return"firestore_zombie_"+this.persistenceKey+"_"+t},t.MAIN_DATABASE="main",t}();function ma(t){return t.code===er.FAILED_PRECONDITION&&t.message===ha}function ya(t){return t.store(Ps.store)}function ga(t){return t.store(Gs.store)}var va=function(){function t(t,e){this.db=t,this.garbageCollector=new ua(this,e)}return t.prototype.getSequenceNumberCount=function(t){var e=this.orphanedDocmentCount(t);return this.db.getQueryCache().getQueryCount(t).next(function(t){return e.next(function(e){return t+e})})},t.prototype.orphanedDocmentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,function(t){e++}).next(function(){return e})},t.prototype.forEachTarget=function(t,e){return this.db.getQueryCache().forEachTarget(t,e)},t.prototype.forEachOrphanedDocumentSequenceNumber=function(t,e){return this.forEachOrphanedDocument(t,function(t,n){return e(n)})},t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.addReference=function(t,e){return ba(t,e)},t.prototype.removeReference=function(t,e){return ba(t,e)},t.prototype.removeTargets=function(t,e,n){return this.db.getQueryCache().removeTargets(t,e,n)},t.prototype.removeMutationReference=function(t,e){return ba(t,e)},t.prototype.isPinned=function(t,e){return this.inMemoryPins.containsKey(e)?hs.resolve(!0):function(t,e){var n=!1;return ea(t).iterateSerial(function(r){return Ys(t,r,e).next(function(t){return t&&(n=!0),hs.resolve(!t)})}).next(function(){return n})}(t,e)},t.prototype.removeOrphanedDocuments=function(t,e){var n=this,r=0,i=0,o=[];return this.forEachOrphanedDocument(t,function(s,a){if(a<=e){var u=n.isPinned(t,s).next(function(e){if(!e)return r++,n.removeOrphanedDocument(t,s).next(function(t){i+=t})});o.push(u)}}).next(function(){return hs.waitFor(o)}).next(function(){return n.db.getRemoteDocumentCache().updateSize(t,-i)}).next(function(){return r})},t.prototype.removeOrphanedDocument=function(t,e){var n,r=0,i=this.db.getRemoteDocumentCache();return hs.waitFor([ws(t).delete((n=e,[0,ts(n.path)])),i.removeEntry(t,e).next(function(t){r+=t})]).next(function(){return r})},t.prototype.removeTarget=function(t,e){var n=e.copy({sequenceNumber:t.currentSequenceNumber});return this.db.getQueryCache().updateQueryData(t,n)},t.prototype.updateLimboDocument=function(t,e){return ba(t,e)},t.prototype.forEachOrphanedDocument=function(t,e){var n,r=ws(t),i=zo.INVALID;return r.iterate({index:Ks.documentTargetsIndex},function(t,r){var o=t[0],s=(t[1],r.path),a=r.sequenceNumber;0===o?(i!==zo.INVALID&&e(new Wr(rs(n)),i),i=a,n=s):i=zo.INVALID}).next(function(){i!==zo.INVALID&&e(new Wr(rs(n)),i)})},t.prototype.getCacheSize=function(t){return this.db.getRemoteDocumentCache().getSize(t)},t}();function ba(t,e){return ws(t).put(function(t,e){return new Ks(0,ts(t.path),e)}(e,t.currentSequenceNumber))}var wa=function(){function t(t,e){this.remoteDocumentCache=t,this.mutationQueue=e}return t.prototype.getDocument=function(t,e){var n=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(t,e).next(function(r){return n.getDocumentInternal(t,e,r)})},t.prototype.getDocumentInternal=function(t,e,n){return this.remoteDocumentCache.getEntry(t,e).next(function(t){for(var r=0,i=n;r0){var h=u;u=u.copy({resumeToken:c,snapshotVersion:e.snapshotVersion}),n.queryDataByTarget[r]=u,t.shouldPersistQueryData(h,u,a)&&o.push(n.queryCache.updateQueryData(i,u))}}});var a=ao();e.documentUpdates.forEach(function(t,u){a=a.add(t),o.push(r.getEntry(i,t).next(function(e){null==e||u.version.isEqual(_i.MIN)||s.has(u.key)&&!e.hasPendingWrites||u.version.compareTo(e.version)>=0?r.addEntry(u):Hn("LocalStore","Ignoring outdated watch update for ",t,". Current version:",e.version," Watch version:",u.version)})),e.resolvedLimboDocuments.has(t)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(i,t))});var u=e.snapshotVersion;if(!u.isEqual(_i.MIN)){var c=n.queryCache.getLastRemoteSnapshotVersion(i).next(function(t){return Zn(u.compareTo(t)>=0,"Watch stream reverted to previous snapshot?? "+u+" < "+t),n.queryCache.setTargetsMetadata(i,i.currentSequenceNumber,u)});o.push(c)}return hs.waitFor(o).next(function(){return r.apply(i)}).next(function(){return n.localDocuments.getDocuments(i,a)})})},t.shouldPersistQueryData=function(t,e,n){return 0!==e.resumeToken.length&&(0===t.resumeToken.length||(e.snapshotVersion.toMicroseconds()-t.snapshotVersion.toMicroseconds()>=this.RESUME_TOKEN_MAX_AGE_MICROS||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0))},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("notifyLocalViewChanges","readwrite",function(n){return hs.forEach(t,function(t){return e.localViewReferences.addReferences(t.addedKeys,t.targetId),e.localViewReferences.removeReferences(t.removedKeys,t.targetId),hs.forEach(t.removedKeys,function(t){return e.persistence.referenceDelegate.removeReference(n,t)})})})},t.prototype.nextMutationBatch=function(t){var e=this;return this.persistence.runTransaction("Get next mutation batch","readonly",function(n){return void 0===t&&(t=os),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)})},t.prototype.readDocument=function(t){var e=this;return this.persistence.runTransaction("read document","readonly",function(n){return e.localDocuments.getDocument(n,t)})},t.prototype.allocateQuery=function(t){var e=this;return this.persistence.runTransaction("Allocate query","readwrite",function(n){var r;return e.queryCache.getQueryData(n,t).next(function(i){return i?(r=i,hs.resolve()):e.queryCache.allocateTargetId(n).next(function(i){return r=new Li(t,i,Ei.Listen,n.currentSequenceNumber),e.queryCache.addQueryData(n,r)})}).next(function(){return Zn(!e.queryDataByTarget[r.targetId],"Tried to allocate an already allocated query: "+t),e.queryDataByTarget[r.targetId]=r,r})})},t.prototype.releaseQuery=function(t,e){var n=this,r=e?"readwrite":"readwrite-primary";return this.persistence.runTransaction("Release query",r,function(r){return n.queryCache.getQueryData(r,t).next(function(i){Zn(null!=i,"Tried to release nonexistent query: "+t);var o=i.targetId,s=n.queryDataByTarget[o],a=n.localViewReferences.removeReferencesForId(o);return delete n.queryDataByTarget[o],e?hs.resolve():hs.forEach(a,function(t){return n.persistence.referenceDelegate.removeReference(r,t)}).next(function(){return n.persistence.referenceDelegate.removeTarget(r,s)})})})},t.prototype.executeQuery=function(t){var e=this;return this.persistence.runTransaction("Execute query","readonly",function(n){return e.localDocuments.getDocumentsMatchingQuery(n,t)})},t.prototype.remoteDocumentKeys=function(t){var e=this;return this.persistence.runTransaction("Remote document keys","readonly",function(n){return e.queryCache.getMatchingKeysForTargetId(n,t)})},t.prototype.getActiveClients=function(){return this.persistence.getActiveClients()},t.prototype.removeCachedMutationBatchMetadata=function(t){this.mutationQueue.removeCachedMutationKeys(t)},t.prototype.setNetworkEnabled=function(t){this.persistence.setNetworkEnabled(t)},t.prototype.applyWriteToRemoteDocuments=function(t,e,n){var r=this,i=e.batch,o=i.keys(),s=hs.resolve();return o.forEach(function(r){s=s.next(function(){return n.getEntry(t,r)}).next(function(t){var o=t,s=e.docVersions.get(r);Zn(null!==s,"ackVersions should contain every doc in the write."),(!o||o.version.compareTo(s)<0)&&((o=i.applyToRemoteDocument(r,o,e))?n.addEntry(o):Zn(!t,"Mutation batch "+i+" applied to document "+t+" resulted in null"))})}),s.next(function(){return r.mutationQueue.removeMutationBatch(t,i)})},t.prototype.collectGarbage=function(t){var e=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary",function(n){return t.collect(n,e.queryDataByTarget)})},t.prototype.getQueryForTarget=function(t){var e=this;return this.queryDataByTarget[t]?Promise.resolve(this.queryDataByTarget[t].query):this.persistence.runTransaction("Get query data","readonly",function(n){return e.queryCache.getQueryDataForTarget(n,t).next(function(t){return t?t.query:null})})},t.prototype.getNewDocumentChanges=function(){var t=this;return this.persistence.runTransaction("Get new document changes","readonly",function(e){return t.remoteDocuments.getNewDocumentChanges(e)})},t.RESUME_TOKEN_MAX_AGE_MICROS=3e8,t}(),Ia=function(){function t(t){this.referenceDelegate=t,this.mutationQueue=[],this.nextBatchId=1,this.highestAcknowledgedBatchId=os,this.lastStreamToken=tr(),this.batchesByDocumentKey=new qi(Sa.compareByKey)}return t.prototype.checkEmpty=function(t){return hs.resolve(0===this.mutationQueue.length)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;Zn(r>this.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var i=this.indexOfExistingBatchId(r,"acknowledged");Zn(0===i,"Can only acknowledge the first batch in the mutation queue");var o=this.mutationQueue[i];return Zn(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,hs.resolve()},t.prototype.getLastStreamToken=function(t){return hs.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,hs.resolve()},t.prototype.addMutationBatch=function(t,e,n){Zn(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;(this.nextBatchId++,this.mutationQueue.length>0)&&Zn(this.mutationQueue[this.mutationQueue.length-1].batchIdi?this.mutationQueue[i]:null)},t.prototype.getAllMutationBatches=function(t){return hs.resolve(this.mutationQueue.slice())},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new Sa(e,0),i=new Sa(e,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([r,i],function(t){Zn(e.isEqual(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);Zn(null!==r,"Batches in the index must exist in the main table"),o.push(r)}),hs.resolve(o)},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new qi(Nr);return e.forEach(function(t){var e=new Sa(t,0),i=new Sa(t,Number.POSITIVE_INFINITY);n.batchesByDocumentKey.forEachInRange([e,i],function(e){Zn(t.isEqual(e.key),"For each key, should only iterate over a single key's batches"),r=r.add(e.targetOrBatchId)})}),hs.resolve(this.findMutationBatches(r))},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=e.path,r=n.length+1,i=n;Wr.isDocumentKey(i)||(i=i.child(""));var o=new Sa(new Wr(i),0),s=new qi(Nr);return this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(s=s.add(t.targetOrBatchId)),!0)},o),hs.resolve(this.findMutationBatches(s))},t.prototype.findMutationBatches=function(t){var e=this,n=[];return t.forEach(function(t){var r=e.findMutationBatch(t);null!==r&&n.push(r)}),n},t.prototype.removeMutationBatch=function(t,e){var n=this;Zn(0===this.indexOfExistingBatchId(e.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.mutationQueue.shift();var r=this.batchesByDocumentKey;return hs.forEach(e.mutations,function(i){var o=new Sa(i.key,e.batchId);return r=r.delete(o),n.referenceDelegate.removeMutationReference(t,i.key)}).next(function(){n.batchesByDocumentKey=r})},t.prototype.removeCachedMutationKeys=function(t){},t.prototype.containsKey=function(t,e){var n=new Sa(e,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return hs.resolve(e.isEqual(r&&r.key))},t.prototype.performConsistencyCheck=function(t){return 0===this.mutationQueue.length&&Zn(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),hs.resolve()},t.prototype.indexOfExistingBatchId=function(t,e){var n=this.indexOfBatchId(t);return Zn(n>=0&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return Zn(n.batchId===t,"If found batch must match"),n},t}(),Ca=function(){function t(t){this.persistence=t,this.queries=new Es(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=_i.MIN,this.highestTargetId=0,this.highestSequenceNumber=0,this.references=new Ea,this.targetCount=0,this.targetIdGenerator=cs.forQueryCache()}return t.prototype.getTargetCount=function(t){return hs.resolve(this.targetCount)},t.prototype.forEachTarget=function(t,e){return this.queries.forEach(function(t,n){return e(n)}),hs.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(t){return hs.resolve(this.lastRemoteSnapshotVersion)},t.prototype.getHighestSequenceNumber=function(t){return hs.resolve(this.highestSequenceNumber)},t.prototype.allocateTargetId=function(t){var e=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=e,hs.resolve(e)},t.prototype.setTargetsMetadata=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.highestSequenceNumber&&(this.highestSequenceNumber=e),hs.resolve()},t.prototype.saveQueryData=function(t){this.queries.set(t.query,t);var e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e),t.sequenceNumber>this.highestSequenceNumber&&(this.highestSequenceNumber=t.sequenceNumber)},t.prototype.addQueryData=function(t,e){return Zn(!this.queries.has(e.query),"Adding a query that already exists"),this.saveQueryData(e),this.targetCount+=1,hs.resolve()},t.prototype.updateQueryData=function(t,e){return Zn(this.queries.has(e.query),"Updating a non-existent query"),this.saveQueryData(e),hs.resolve()},t.prototype.removeQueryData=function(t,e){return Zn(this.targetCount>0,"Removing a target from an empty cache"),Zn(this.queries.has(e.query),"Removing a non-existent target from the cache"),this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),this.targetCount-=1,hs.resolve()},t.prototype.removeTargets=function(t,e,n){var r=this,i=0,o=[];return this.queries.forEach(function(s,a){a.sequenceNumber<=e&&!n[a.targetId]&&(r.queries.delete(s),o.push(r.removeMatchingKeysForTargetId(t,a.targetId)),i++)}),hs.waitFor(o).next(function(){return i})},t.prototype.getQueryCount=function(t){return hs.resolve(this.targetCount)},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return hs.resolve(n)},t.prototype.getQueryDataForTarget=function(t,e){return Jn("Not yet implemented.")},t.prototype.addMatchingKeys=function(t,e,n){this.references.addReferences(e,n);var r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(function(e){i.push(r.addReference(t,e))}),hs.waitFor(i)},t.prototype.removeMatchingKeys=function(t,e,n){this.references.removeReferences(e,n);var r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(function(e){i.push(r.removeReference(t,e))}),hs.waitFor(i)},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),hs.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return hs.resolve(n)},t.prototype.containsKey=function(t,e){return hs.resolve(this.references.containsKey(e))},t}();var Da,Na=function(){function t(t){this.sizer=t,this.docs=new Xr(Wr.comparator),this.newDocumentChanges=ao(),this.size=0}return t.prototype.addEntries=function(t,e,n){for(var r=0,i=e;rn)}])},t.prototype.getCacheSize=function(t){return this.persistence.getRemoteDocumentCache().getSize(t)},t}(),_a=function(){function t(t,e,n,r,i){this.queue=t,this.timerId=e,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=i,this.timerPromise=null,this.lastAttemptTime=Date.now(),this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndRun=function(t){var e=this;this.cancel();var n=Math.floor(this.currentBaseMs+this.jitterDelayMs()),r=Math.max(0,Date.now()-this.lastAttemptTime),i=Math.max(0,n-r);this.currentBaseMs>0&&Hn("ExponentialBackoff","Backing off for "+i+" ms (base delay: "+this.currentBaseMs+" ms, delay with jitter: "+n+" ms, last attempt: "+r+" ms ago)"),this.timerPromise=this.queue.enqueueAfterDelay(this.timerId,i,function(){return e.lastAttemptTime=Date.now(),t()}),this.currentBaseMs*=this.backoffFactor,this.currentBaseMsthis.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},t.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}();!function(t){t[t.Initial=0]="Initial",t[t.Starting=1]="Starting",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff"}(Da||(Da={}));var Pa,La,qa=1e3,xa=6e4,Fa=1.5,Ba=function(){function t(t,e,n,r,i,o){this.queue=t,this.idleTimerId=n,this.connection=r,this.credentialsProvider=i,this.listener=o,this.state=Da.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new _a(t,e,qa,Fa,xa)}return t.prototype.isStarted=function(){return this.state===Da.Starting||this.state===Da.Open||this.state===Da.Backoff},t.prototype.isOpen=function(){return this.state===Da.Open},t.prototype.start=function(){this.state!==Da.Error?(Zn(this.state===Da.Initial,"Already started"),this.auth()):this.performBackoff()},t.prototype.stop=function(){return a(this,void 0,void 0,function(){return u(this,function(t){switch(t.label){case 0:return this.isStarted()?[4,this.close(Da.Initial)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},t.prototype.inhibitBackoff=function(){Zn(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=Da.Initial,this.backoff.reset()},t.prototype.markIdle=function(){var t=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,function(){return t.handleIdleCloseTimer()}))},t.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},t.prototype.handleIdleCloseTimer=function(){return a(this,void 0,void 0,function(){return u(this,function(t){return this.isOpen()?[2,this.close(Da.Initial)]:[2]})})},t.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},t.prototype.close=function(t,e){return a(this,void 0,void 0,function(){return u(this,function(n){switch(n.label){case 0:return Zn(this.isStarted(),"Only started streams should be closed."),Zn(t===Da.Error||bi(e),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,t!==Da.Error?this.backoff.reset():e&&e.code===er.RESOURCE_EXHAUSTED?(Xn(e.toString()),Xn("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):e&&e.code===er.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=t,[4,this.listener.onClose(e)];case 1:return n.sent(),[2]}})})},t.prototype.tearDown=function(){},t.prototype.auth=function(){var t=this;Zn(this.state===Da.Initial,"Must be in initial state to auth"),this.state=Da.Starting;var e=this.getCloseGuardedDispatcher(this.closeCount),n=this.closeCount;this.credentialsProvider.getToken().then(function(e){t.closeCount===n&&t.startStream(e)},function(n){e(function(){var e=new nr(er.UNKNOWN,"Fetching auth token failed: "+n.message);return t.handleStreamClose(e)})})},t.prototype.startStream=function(t){var e=this;Zn(this.state===Da.Starting,"Trying to start stream in a non-starting state");var n=this.getCloseGuardedDispatcher(this.closeCount);this.stream=this.startRpc(t),this.stream.onOpen(function(){n(function(){return Zn(e.state===Da.Starting,"Expected stream to be in state Starting, but was "+e.state),e.state=Da.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t)})})},t.prototype.performBackoff=function(){var t=this;Zn(this.state===Da.Error,"Should only perform backoff when in Error state"),this.state=Da.Backoff,this.backoff.backoffAndRun(function(){return a(t,void 0,void 0,function(){return u(this,function(t){return Zn(this.state===Da.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=Da.Initial,this.start(),Zn(this.isStarted(),"PersistentStream should have started"),[2]})})})},t.prototype.handleStreamClose=function(t){return Zn(this.isStarted(),"Can't handle server close on non-started stream"),Hn("PersistentStream","close with error: "+t),this.stream=null,this.close(Da.Error,t)},t.prototype.getCloseGuardedDispatcher=function(t){var e=this;return function(n){e.queue.enqueueAndForget(function(){return e.closeCount===t?n():(Hn("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}},t}(),Ua=function(t){function e(e,n,r,i,o){var s=t.call(this,e,jo.ListenStreamConnectionBackoff,jo.ListenStreamIdle,n,r,o)||this;return s.serializer=i,s}return s(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.sendRequest(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},e}(Ba),Va=function(t){function e(e,n,r,i,o){var s=t.call(this,e,jo.WriteStreamConnectionBackoff,jo.WriteStreamIdle,n,r,o)||this;return s.serializer=i,s.handshakeComplete_=!1,s}return s(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.handshakeComplete_},enumerable:!0,configurable:!0}),e.prototype.start=function(){this.handshakeComplete_=!1,t.prototype.start.call(this)},e.prototype.tearDown=function(){this.handshakeComplete_&&this.writeMutations([])},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(Zn(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.handshakeComplete_){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults,t.commitTime),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return Zn(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){Zn(this.isOpen(),"Writing handshake requires an opened stream"),Zn(!this.handshakeComplete_,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},e.prototype.writeMutations=function(t){var e=this;Zn(this.isOpen(),"Writing mutations requires an opened stream"),Zn(this.handshakeComplete_,"Handshake must be complete before writing mutations"),Zn(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map(function(t){return e.serializer.toMutation(t)})};this.sendRequest(n)},e}(Ba),Qa=function(){function t(t,e,n,r){this.queue=t,this.connection=e,this.credentials=n,this.serializer=r}return t.prototype.newPersistentWriteStream=function(t){return new Va(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.newPersistentWatchStream=function(t){return new Ua(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.commit=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,writes:t.map(function(t){return e.serializer.toMutation(t)})};return this.invokeRPC("Commit",n).then(function(t){return e.serializer.fromWriteResults(t.writeResults,t.commitTime)})},t.prototype.lookup=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,documents:t.map(function(t){return e.serializer.toName(t)})};return this.invokeStreamingRPC("BatchGetDocuments",n).then(function(n){var r=eo();n.forEach(function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)});var i=[];return t.forEach(function(t){var e=r.get(t);Zn(!!e,"Missing entity in write response for "+t),i.push(e)}),i})},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken().then(function(r){return n.connection.invokeRPC(t,e,r)}).catch(function(t){throw t.code===er.UNAUTHENTICATED&&n.credentials.invalidateToken(),t})},t.prototype.invokeStreamingRPC=function(t,e){var n=this;return this.credentials.getToken().then(function(r){return n.connection.invokeStreamingRPC(t,e,r)}).catch(function(t){throw t.code===er.UNAUTHENTICATED&&n.credentials.invalidateToken(),t})},t}(),Ka=function(){function t(t){this.datastore=t,this.readVersions=oo(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e;if(t instanceof zr)e=t.version;else{if(!(t instanceof Gr))throw Jn("Document in a transaction was a "+t.constructor.name);e=_i.forDeletedDoc()}var n=this.readVersions.get(t.key);if(null!==n){if(!e.isEqual(n))throw new nr(er.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.lookup=function(t){var e=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(t).then(function(t){return t.forEach(function(t){t instanceof Gr||t instanceof zr?e.recordVersion(t):Jn("Document in a transaction was a "+t.constructor.name)}),t})},t.prototype.write=function(t){if(this.committed)throw new nr(er.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(t)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return e?Ui.updateTime(e):Ui.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.isEqual(_i.forDeletedDoc()))throw new nr(er.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?Ui.updateTime(e):Ui.exists(!0)},t.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,e){this.write(e.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new ji(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,_i.forDeletedDoc())},t.prototype.commit=function(){var t=this,e=this.readVersions;return this.mutations.forEach(function(t){e=e.remove(t.key)}),e.isEmpty()?this.datastore.commit(this.mutations).then(function(){t.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},t}();!function(t){t[t.Unknown=0]="Unknown",t[t.Online=1]="Online",t[t.Offline=2]="Offline"}(Pa||(Pa={})),function(t){t[t.RemoteStore=0]="RemoteStore",t[t.SharedClientState=1]="SharedClientState"}(La||(La={}));var Wa=function(){function t(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state=Pa.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}return t.prototype.handleWatchStreamStart=function(){var t=this;0===this.watchStreamFailures&&(this.setAndBroadcast(Pa.Unknown),Zn(null===this.onlineStateTimer,"onlineStateTimer shouldn't be started yet"),this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(jo.OnlineStateTimeout,1e4,function(){return t.onlineStateTimer=null,Zn(t.state===Pa.Unknown,"Timer should be canceled if we transitioned to a different state."),t.logClientOfflineWarningIfNecessary("Backend didn't respond within 10 seconds."),t.setAndBroadcast(Pa.Offline),Promise.resolve()}))},t.prototype.handleWatchStreamFailure=function(t){this.state===Pa.Online?(this.setAndBroadcast(Pa.Unknown),Zn(0===this.watchStreamFailures,"watchStreamFailures must be 0"),Zn(null===this.onlineStateTimer,"onlineStateTimer must be null")):(this.watchStreamFailures++,this.watchStreamFailures>=1&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary("Connection failed 1 times. Most recent error: "+t.toString()),this.setAndBroadcast(Pa.Offline)))},t.prototype.set=function(t){this.clearOnlineStateTimer(),this.watchStreamFailures=0,t===Pa.Online&&(this.shouldWarnClientIsOffline=!1),this.setAndBroadcast(t)},t.prototype.setAndBroadcast=function(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))},t.prototype.logClientOfflineWarningIfNecessary=function(t){var e="Could not reach Cloud Firestore backend. "+t+"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.";this.shouldWarnClientIsOffline?(Xn(e),this.shouldWarnClientIsOffline=!1):Hn("OnlineStateTracker",e)},t.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},t}(),ja=function(){function t(t,e,n,r){this.localStore=t,this.datastore=e,this.writePipeline=[],this.listenTargets={},this.watchChangeAggregator=null,this.networkEnabled=!1,this.isPrimary=!1,this.onlineStateTracker=new Wa(n,r),this.watchStream=this.datastore.newPersistentWatchStream({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)}),this.writeStream=this.datastore.newPersistentWriteStream({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.enableNetwork=function(){return a(this,void 0,void 0,function(){var t;return u(this,function(e){switch(e.label){case 0:return this.networkEnabled=!0,this.canUseNetwork()?(t=this.writeStream,[4,this.localStore.getLastStreamToken()]):[3,3];case 1:return t.lastStreamToken=e.sent(),this.shouldStartWatchStream()?this.startWatchStream():this.onlineStateTracker.set(Pa.Unknown),[4,this.fillWritePipeline()];case 2:e.sent(),e.label=3;case 3:return[2]}})})},t.prototype.disableNetwork=function(){return a(this,void 0,void 0,function(){return u(this,function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Pa.Offline),[2]}})})},t.prototype.disableNetworkInternal=function(){return a(this,void 0,void 0,function(){return u(this,function(t){switch(t.label){case 0:return[4,this.writeStream.stop()];case 1:return t.sent(),[4,this.watchStream.stop()];case 2:return t.sent(),this.writePipeline.length>0&&(Hn("RemoteStore","Stopping write stream with "+this.writePipeline.length+" pending writes"),this.writePipeline=[]),this.cleanUpWatchStreamState(),[2]}})})},t.prototype.shutdown=function(){return a(this,void 0,void 0,function(){return u(this,function(t){switch(t.label){case 0:return Hn("RemoteStore","RemoteStore shutting down."),this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Pa.Unknown),[2]}})})},t.prototype.listen=function(t){Zn(!ir(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){Zn(ir(this.listenTargets,t),"unlisten called without assigned target ID!"),delete this.listenTargets[t],this.watchStream.isOpen()&&this.sendUnwatchRequest(t),ur(this.listenTargets)&&(this.watchStream.isOpen()?this.watchStream.markIdle():this.canUseNetwork()&&this.onlineStateTracker.set(Pa.Unknown))},t.prototype.getQueryDataForTarget=function(t){return this.listenTargets[t]||null},t.prototype.getRemoteKeysForTarget=function(t){return this.syncEngine.getRemoteKeysForTarget(t)},t.prototype.sendWatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.startWatchStream=function(){Zn(this.shouldStartWatchStream(),"startWatchStream() called when shouldStartWatchStream() is false."),this.watchChangeAggregator=new To(this),this.watchStream.start(),this.onlineStateTracker.handleWatchStreamStart()},t.prototype.shouldStartWatchStream=function(){return this.canUseNetwork()&&!this.watchStream.isStarted()&&!ur(this.listenTargets)},t.prototype.canUseNetwork=function(){return this.isPrimary&&this.networkEnabled},t.prototype.cleanUpWatchStreamState=function(){this.watchChangeAggregator=null},t.prototype.onWatchStreamOpen=function(){return a(this,void 0,void 0,function(){var t=this;return u(this,function(e){return sr(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),[2]})})},t.prototype.onWatchStreamClose=function(t){return a(this,void 0,void 0,function(){return u(this,function(e){return void 0===t&&Zn(!this.shouldStartWatchStream(),"Watch stream was stopped gracefully while still needed."),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.onlineStateTracker.handleWatchStreamFailure(t),this.startWatchStream()):this.onlineStateTracker.set(Pa.Unknown),[2]})})},t.prototype.onWatchStreamChange=function(t,e){return a(this,void 0,void 0,function(){var n;return u(this,function(r){switch(r.label){case 0:return this.onlineStateTracker.set(Pa.Online),t instanceof Eo&&t.state===po.Removed&&t.cause?[2,this.handleTargetError(t)]:(t instanceof bo?this.watchChangeAggregator.handleDocumentChange(t):t instanceof wo?this.watchChangeAggregator.handleExistenceFilter(t):(Zn(t instanceof Eo,"Expected watchChange to be an instance of WatchTargetChange"),this.watchChangeAggregator.handleTargetChange(t)),e.isEqual(_i.MIN)?[3,3]:[4,this.localStore.getLastRemoteSnapshotVersion()]);case 1:return n=r.sent(),e.compareTo(n)>=0?[4,this.raiseWatchSnapshot(e)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[2]}})})},t.prototype.raiseWatchSnapshot=function(t){var e=this;Zn(!t.isEqual(_i.MIN),"Can't raise event for unknown SnapshotVersion");var n=this.watchChangeAggregator.createRemoteEvent(t);return sr(n.targetChanges,function(n,r){if(r.resumeToken.length>0){var i=e.listenTargets[n];i&&(e.listenTargets[n]=i.copy({resumeToken:r.resumeToken,snapshotVersion:t}))}}),n.targetMismatches.forEach(function(t){var n=e.listenTargets[t];if(n){e.listenTargets[t]=n.copy({resumeToken:tr()}),e.sendUnwatchRequest(t);var r=new Li(n.query,t,Ei.ExistenceFilterMismatch,n.sequenceNumber);e.sendWatchRequest(r)}}),this.syncEngine.applyRemoteEvent(n)},t.prototype.handleTargetError=function(t){var e=this;Zn(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach(function(t){r=r.then(function(){return a(e,void 0,void 0,function(){return u(this,function(e){return ir(this.listenTargets,t)?(delete this.listenTargets[t],this.watchChangeAggregator.removeTarget(t),[2,this.syncEngine.rejectListen(t,n)]):[2]})})})}),r},t.prototype.fillWritePipeline=function(){return a(this,void 0,void 0,function(){var t,e;return u(this,function(n){switch(n.label){case 0:return this.canAddToWritePipeline()?(t=this.writePipeline.length>0?this.writePipeline[this.writePipeline.length-1].batchId:os,[4,this.localStore.nextMutationBatch(t)]):[3,4];case 1:return null!==(e=n.sent())?[3,2]:(0===this.writePipeline.length&&this.writeStream.markIdle(),[3,4]);case 2:return this.addToWritePipeline(e),[4,this.fillWritePipeline()];case 3:n.sent(),n.label=4;case 4:return this.shouldStartWriteStream()&&this.startWriteStream(),[2]}})})},t.prototype.canAddToWritePipeline=function(){return this.canUseNetwork()&&this.writePipeline.length<10},t.prototype.outstandingWrites=function(){return this.writePipeline.length},t.prototype.addToWritePipeline=function(t){Zn(this.canAddToWritePipeline(),"addToWritePipeline called when pipeline is full"),this.writePipeline.push(t),this.writeStream.isOpen()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.canUseNetwork()&&!this.writeStream.isStarted()&&this.writePipeline.length>0},t.prototype.startWriteStream=function(){Zn(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},t.prototype.onWriteStreamOpen=function(){return a(this,void 0,void 0,function(){return u(this,function(t){return this.writeStream.writeHandshake(),[2]})})},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.writePipeline;e0,"Got result for empty write pipeline");var r=this.writePipeline.shift(),i=as.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){return a(this,void 0,void 0,function(){var e=this;return u(this,function(n){return void 0===t&&Zn(!this.shouldStartWriteStream(),"Write stream was stopped gracefully while still needed."),t&&this.writePipeline.length>0?(void 0,[2,(this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t)).then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})]):[2]})})},t.prototype.handleHandshakeError=function(t){return a(this,void 0,void 0,function(){var e=this;return u(this,function(n){return Zi(t.code)||t.code===er.ABORTED?(Hn("RemoteStore","RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=tr(),[2,this.localStore.setLastStreamToken(tr()).catch(function(t){return e.ignoreIfPrimaryLeaseLoss(t)})]):[2]})})},t.prototype.handleWriteError=function(t){return a(this,void 0,void 0,function(){var e,n=this;return u(this,function(r){return Zi(t.code)?(e=this.writePipeline.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(e.batchId,t).then(function(){return n.fillWritePipeline()})]):[2]})})},t.prototype.createTransaction=function(){return new Ka(this.datastore)},t.prototype.handleCredentialChange=function(){return a(this,void 0,void 0,function(){return u(this,function(t){switch(t.label){case 0:return this.canUseNetwork()?(Hn("RemoteStore","RemoteStore restarting streams for new credential"),this.networkEnabled=!1,[4,this.disableNetworkInternal()]):[3,3];case 1:return t.sent(),this.onlineStateTracker.set(Pa.Unknown),[4,this.enableNetwork()];case 2:t.sent(),t.label=3;case 3:return[2]}})})},t.prototype.applyPrimaryState=function(t){return a(this,void 0,void 0,function(){return u(this,function(e){switch(e.label){case 0:return this.isPrimary=t,t&&this.networkEnabled?[4,this.enableNetwork()]:[3,2];case 1:return e.sent(),[3,4];case 2:return t?[3,4]:[4,this.disableNetworkInternal()];case 3:e.sent(),this.onlineStateTracker.set(Pa.Unknown),e.label=4;case 4:return[2]}})})},t}(),za=function(){return function(){this.listeners=[]}}(),Ga=function(){function t(t){this.syncEngine=t,this.queries=new Es(function(t){return t.canonicalId()}),this.onlineState=Pa.Unknown,this.syncEngine.subscribe(this)}return t.prototype.listen=function(t){var e=t.query,n=!1,r=this.queries.get(e);return r||(n=!0,r=new za,this.queries.set(e,r)),r.listeners.push(t),t.applyOnlineStateChange(this.onlineState),r.viewSnap&&t.onViewSnapshot(r.viewSnap),n?this.syncEngine.listen(e).then(function(t){return r.targetId=t,t}):Promise.resolve(r.targetId)},t.prototype.unlisten=function(t){return a(this,void 0,void 0,function(){var e,n,r,i;return u(this,function(o){return e=t.query,n=!1,(r=this.queries.get(e))&&(i=r.listeners.indexOf(t))>=0&&(r.listeners.splice(i,1),n=0===r.listeners.length),n?(this.queries.delete(e),[2,this.syncEngine.unlisten(e)]):[2]})})},t.prototype.onWatchChange=function(t){for(var e=0,n=t;e0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeMetadataChanges){for(var e=[],n=0,r=t.docChanges;n0)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeMetadataChanges},t.prototype.raiseInitialEvent=function(t){Zn(!this.raisedInitialEvent,"Trying to raise initial events for second time"),t=yo.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache),this.raisedInitialEvent=!0,this.queryObserver.next(t)},t}(),Xa=function(){function t(t,e,n){this.targetId=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e,n){for(var r=ao(),i=ao(),o=0,s=n.docChanges;o=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!bi(e)&&e.catch&&e.then?e.catch(function(t){return Promise.reject(n.wrapUpdateFunctionError(t))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(t){return Promise.reject(n.wrapUpdateFunctionError(t))}}().then(function(i){return r.commit().then(function(){return i}).catch(function(r){return 0===e?Promise.reject(r):n.runTransaction(t,e-1)})})},t.prototype.applyRemoteEvent=function(t){var e=this;return this.assertSubscribed("applyRemoteEvent()"),this.localStore.applyRemoteEvent(t).then(function(n){return ar(t.targetChanges,function(t,n){var r=e.limboResolutionsByTarget[t];r&&(Zn(n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size<=1,"Limbo resolution for single document contains multiple changes."),n.addedDocuments.size>0?r.receivedDocument=!0:n.modifiedDocuments.size>0?Zn(r.receivedDocument,"Received change for limbo target document without add."):n.removedDocuments.size>0&&(Zn(r.receivedDocument,"Received remove for limbo target document without add."),r.receivedDocument=!1))}),e.emitNewSnapsAndNotifyLocalStore(n,t)}).catch(function(t){return e.ignoreIfPrimaryLeaseLoss(t)})},t.prototype.applyOnlineStateChange=function(t,e){if(this.isPrimary&&e===La.RemoteStore||!this.isPrimary&&e===La.SharedClientState){var n=[];this.queryViewsByQuery.forEach(function(e,r){var i=r.view.applyOnlineStateChange(t);Zn(0===i.limboChanges.length,"OnlineState should not affect limbo documents."),i.snapshot&&n.push(i.snapshot)}),this.syncEngineListener.onOnlineStateChange(t),this.syncEngineListener.onWatchChange(n),this.onlineState=t,this.isPrimary&&this.sharedClientState.setOnlineState(t)}},t.prototype.rejectListen=function(t,e){return a(this,void 0,void 0,function(){var n,r,i,o,s,a,c=this;return u(this,function(u){switch(u.label){case 0:return this.assertSubscribed("rejectListens()"),this.sharedClientState.updateQueryState(t,"rejected",e),n=this.limboResolutionsByTarget[t],(r=n&&n.key)?(this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboResolutionsByTarget[t],i=(i=new Xr(Wr.comparator)).insert(r,new Gr(r,_i.forDeletedDoc())),o=ao().add(r),s=new go(_i.MIN,{},new qi(Nr),i,o),[2,this.applyRemoteEvent(s)]):[3,1];case 1:return Zn(!!(a=this.queryViewsByTarget[t]),"Unknown targetId: "+t),[4,this.localStore.releaseQuery(a.query,!1).then(function(){return c.removeAndCleanupQuery(a)}).catch(function(t){return c.ignoreIfPrimaryLeaseLoss(t)})];case 2:u.sent(),this.syncEngineListener.onWatchError(a.query,e),u.label=3;case 3:return[2]}})})},t.prototype.applyBatchState=function(t,e,n){return a(this,void 0,void 0,function(){var r;return u(this,function(i){switch(i.label){case 0:return this.assertSubscribed("applyBatchState()"),[4,this.localStore.lookupMutationDocuments(t)];case 1:return null===(r=i.sent())?(Hn("SyncEngine","Cannot apply mutation batch with id: "+t),[2]):"pending"!==e?[3,3]:[4,this.remoteStore.fillWritePipeline()];case 2:return i.sent(),[3,4];case 3:"acknowledged"===e||"rejected"===e?(this.processUserCallback(t,n||null),this.localStore.removeCachedMutationBatchMetadata(t)):Jn("Unknown batchState: "+e),i.label=4;case 4:return[4,this.emitNewSnapsAndNotifyLocalStore(r)];case 5:return i.sent(),[2]}})})},t.prototype.applySuccessfulWrite=function(t){var e=this;this.assertSubscribed("applySuccessfulWrite()");var n=t.batch.batchId;return this.processUserCallback(n,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.sharedClientState.updateMutationState(n,"acknowledged"),e.emitNewSnapsAndNotifyLocalStore(t)}).catch(function(t){return e.ignoreIfPrimaryLeaseLoss(t)})},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(r){return n.sharedClientState.updateMutationState(t,"rejected",e),n.emitNewSnapsAndNotifyLocalStore(r)}).catch(function(t){return n.ignoreIfPrimaryLeaseLoss(t)})},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new Xr(Nr)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(Zn(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){var e=this;if(this.sharedClientState.removeLocalQueryTarget(t.targetId),this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.isPrimary){var n=this.limboDocumentRefs.referencesForId(t.targetId);this.limboDocumentRefs.removeReferencesForId(t.targetId),n.forEach(function(t){e.limboDocumentRefs.containsKey(t)||e.removeLimboTarget(t)})}},t.prototype.removeLimboTarget=function(t){var e=this.limboTargetsByKey.get(t);null!==e&&(this.remoteStore.unlisten(e),this.limboTargetsByKey=this.limboTargetsByKey.remove(t),delete this.limboResolutionsByTarget[e])},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n() instead."),Lu=/^__.*__$/,qu=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new Ki(t,this.data,this.fieldMask,e)):n.push(new Qi(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new Wi(t,this.fieldTransforms)),n},t}(),xu=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[new Ki(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new Wi(t,this.fieldTransforms)),n},t}();function Fu(t){switch(t){case Au.Set:case Au.MergeSet:case Au.Update:return!0;case Au.Argument:return!1;default:throw Jn("Unexpected case for UserDataSource: "+t)}}!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.Argument=3]="Argument"}(Au||(Au={}));var Bu=function(){function t(t,e,n,r,i,o){this.dataSource=t,this.methodName=e,this.path=n,this.arrayElement=r,void 0===i&&this.validatePath(),this.arrayElement=void 0!==r&&r,this.fieldTransforms=i||[],this.fieldMask=o||[]}return t.prototype.childContextForField=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(e),r},t.prototype.childContextForFieldPath=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},t.prototype.childContextForArray=function(e){return new t(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path.toString()+")";return new nr(er.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.contains=function(t){return void 0!==this.fieldMask.find(function(e){return t.isPrefixOf(e)})||void 0!==this.fieldTransforms.find(function(e){return t.isPrefixOf(e.field)})},t.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t0&&e.fieldMask.push(e.path):ar(t,function(t,i){var o=n.parseData(i,e.childContextForField(t));null!=o&&(r=r.insert(t,o))}),new di(r)},t.prototype.parseArray=function(t,e){for(var n=[],r=0,i=0,o=t;i0,"FieldValue.delete() at the top level should have already been handled."),e.createError("FieldValue.delete() can only appear at the top level of your update data")):e.createError("FieldValue.delete() cannot be used with set() unless you pass {merge:true}");e.fieldMask.push(e.path)}else if(t instanceof Mu)e.fieldTransforms.push(new Fi(e.path,zi.instance));else if(t instanceof Ou){var n=this.parseArrayTransformElements(t._methodName,t._elements),r=new Gi(n);e.fieldTransforms.push(new Fi(e.path,r))}else if(t instanceof _u){n=this.parseArrayTransformElements(t._methodName,t._elements);var i=new Hi(n);e.fieldTransforms.push(new Fi(e.path,i))}else Jn("Unknown FieldValue type: "+t)},t.prototype.parseScalarValue=function(t,e){if(null===t)return ei.INSTANCE;if("number"==typeof t)return wi(t)?new oi(t):new si(t);if("boolean"==typeof t)return ni.of(t);if("string"==typeof t)return new ai(t);if(t instanceof Date)return new ui(qr.fromDate(t));if(t instanceof qr)return new ui(new qr(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)));if(t instanceof Lr)return new fi(t);if(t instanceof _r)return new hi(t);if(t instanceof Uu)return new li(t.databaseId,t.key);throw e.createError("Unsupported field value: "+wr(t))},t.prototype.parseArrayTransformElements=function(t,e){var n=this;return e.map(function(e,r){var i=new Bu(Au.Argument,t,Kr.EMPTY_PATH);return n.parseData(e,i.childContextForArray(r))})},t}();function Qu(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof qr||t instanceof Lr||t instanceof _r||t instanceof Uu||t instanceof ku)}function Ku(t,e,n){if(!Qu(n)||!br(n)){var r=wr(n);throw"an object"===r?e.createError(t+" a custom object"):e.createError(t+" "+r)}}function Wu(t,e){if(e instanceof wu)return e._internalPath;if("string"==typeof e)return ju(t,e);throw new nr(er.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function ju(t,e){try{return function(t){if(t.search(Eu)>=0)throw new nr(er.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(wu.bind.apply(wu,[void 0].concat(t.split("."))))}catch(e){throw new nr(er.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}(e)._internalPath}catch(e){var n=zu(e);throw new nr(er.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. "+n)}}function zu(t){return t instanceof Error?t.message:t.toString()}var Gu="firestore.googleapis.com",Hu=!0,Xu=!1,Yu=sa.COLLECTION_DISABLED,Ju=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new nr(er.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Gu,this.ssl=Hu}else pr("settings","non-empty string","host",t.host),this.host=t.host,mr("settings","boolean","ssl",t.ssl),this.ssl=or(t.ssl,Hu);if(Sr("settings",t,["host","ssl","credentials","timestampsInSnapshots","cacheSizeBytes"]),mr("settings","object","credentials",t.credentials),this.credentials=t.credentials,mr("settings","boolean","timestampsInSnapshots",t.timestampsInSnapshots),this.timestampsInSnapshots=or(t.timestampsInSnapshots,Xu),mr("settings","number","cacheSizeBytes",t.cacheSizeBytes),void 0===t.cacheSizeBytes)this.cacheSizeBytes=sa.DEFAULT_CACHE_SIZE_BYTES;else{if(t.cacheSizeBytes!==Yu&&t.cacheSizeBytes0?[2,this._firestore.ensureClientConfigured().write(this._mutations)]:[2]})})},t.prototype.verifyNotCommitted=function(){if(this._committed)throw new nr(er.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),nc=function(){function t(t,e){this._key=t,this.firestore=e,this._firestoreClient=this.firestore.ensureClientConfigured()}return t.forPath=function(e,n){if(e.length%2!=0)throw new nr(er.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new t(new Wr(e),n)},Object.defineProperty(t.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new uc(this._key.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this._key.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(cr("DocumentReference.collection",arguments,1),fr("DocumentReference.collection","non-empty string",1,t),!t)throw new nr(er.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=Vr.fromString(t);return new uc(this._key.path.child(e),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Tr("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this._key.isEqual(e._key)},t.prototype.set=function(t,e){lr("DocumentReference.set",arguments,1,2);var n=(e=cc("DocumentReference.set",e)).merge||e.mergeFields?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t,e.mergeFields):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this._firestoreClient.write(n.toMutations(this._key,Ui.NONE))},t.prototype.update=function(t,e){for(var n,r=[],i=2;i0)throw new nr(er.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var i=e;if(!i.exists)throw new nr(er.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,i._document,r)}var o=[e].concat(n);return this.boundFromFields(t,o,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],i=0,o=this._query.orderBy;ir.length)throw new nr(er.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");for(var i=[],o=0;o, or >=) must be on the same field. But you have inequality filters on '"+e.toString()+"' and '"+t.field.toString()+"'");var n=this._query.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(t.field,n)}else if(t.op===Ii.ARRAY_CONTAINS&&this._query.hasArrayContainsFilter())throw new nr(er.INVALID_ARGUMENT,"Invalid query. Queries only support a single array-contains filter.")},t.prototype.validateNewOrderBy=function(t){if(null===this._query.getFirstOrderByField()){var e=this._query.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.isEqual(t))throw new nr(er.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.")},t}(),ac=function(){function t(t,e,n){this._firestore=t,this._originalQuery=e,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new rc(n.hasPendingWrites,n.fromCache)}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach(function(e){return t.push(e)}),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this._snapshot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this._snapshot.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;lr("QuerySnapshot.forEach",arguments,1,2),fr("QuerySnapshot.forEach","function",1,t),this._snapshot.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new sc(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),t.prototype.docChanges=function(t){t&&(Sr("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),mr("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));var e=!(!t||!t.includeMetadataChanges);if(e&&this._snapshot.excludesMetadataChanges)throw new nr(er.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(t,e,n){if(n.oldDocs.isEmpty()){var r,i=0;return n.docChanges.map(function(e){var o=new oc(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key));return Zn(e.type===ho.Added,"Invalid event type for first snapshot"),Zn(!r||n.query.docComparator(r,e.doc)<0,"Got added events in wrong order"),r=e.doc,{type:"added",doc:o,oldIndex:-1,newIndex:i++}})}var o=n.oldDocs;return n.docChanges.filter(function(t){return e||t.type!==ho.Metadata}).map(function(e){var r=new oc(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key)),i=-1,s=-1;return e.type!==ho.Added&&(Zn((i=o.indexOf(e.doc.key))>=0,"Index for document not found"),o=o.delete(e.doc.key)),e.type!==ho.Removed&&(o=o.add(e.doc),s=o.indexOf(e.doc.key)),{type:function(t){switch(t){case ho.Added:return"added";case ho.Modified:case ho.Metadata:return"modified";case ho.Removed:return"removed";default:return Jn("Unknown change type: "+t)}}(e.type),doc:r,oldIndex:i,newIndex:s}})}(this._firestore,e,this._snapshot),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Tr("isEqual","QuerySnapshot",1,e);return this._firestore===e._firestore&&this._originalQuery.isEqual(e._originalQuery)&&this._snapshot.isEqual(e._snapshot)},t.prototype.convertToDocumentImpl=function(t){return new oc(this._firestore,t.key,t,this.metadata.fromCache,this._snapshot.mutatedKeys.has(t.key))},t}();["length","forEach","map"].concat("undefined"!=typeof Symbol?[Symbol.iterator]:[]).forEach(function(t){try{Object.defineProperty(ac.prototype.docChanges,t,{get:function(){return function(){throw new nr(er.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}()}})}catch(t){}});var uc=function(t){function e(e,n){var r=t.call(this,Si.atPath(e),n)||this;if(e.length%2!=1)throw new nr(er.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.canonicalString()+" has "+e.length);return r}return s(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this._query.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this._query.path.popLast();return t.isEmpty()?null:new nc(new Wr(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this._query.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(lr("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=Dr.newId()),fr("CollectionReference.doc","non-empty string",1,t),""===t)throw new nr(er.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=Vr.fromString(t);return nc.forPath(this._query.path.child(e),this.firestore)},e.prototype.add=function(t){cr("CollectionReference.add",arguments,1),fr("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(sc);function cc(t,e){if(void 0===e)return{merge:!1};if(Sr(t,e,["merge","mergeFields"]),mr(t,"boolean","merge",e.merge),yr(t,"mergeFields","a string or a FieldPath",e.mergeFields,function(t){return"string"==typeof t||t instanceof wu}),void 0!==e.mergeFields&&void 0!==e.merge)throw new nr(er.INVALID_ARGUMENT,"Invalid options passed to function "+t+'(): You cannot specify both "merge" and "mergeFields".');return e}function hc(t,e){return void 0===e?{}:(Sr(t,e,["serverTimestamps"]),gr(t,0,"serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function lc(t,e){dr(t,"object",1,e),e&&(Sr(t,e,["source"]),gr(t,0,"source",e.source,["default","server","cache"]))}function fc(t,e,n){if(e instanceof nc){if(e.firestore!==n)throw new nr(er.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw Tr(t,"DocumentReference",1,e)}var dc=rr($u,"Use firebase.firestore() instead."),pc=rr(tc,"Use firebase.firestore().runTransaction() instead."),mc=rr(ec,"Use firebase.firestore().batch() instead."),yc=rr(nc,"Use firebase.firestore().doc() instead."),gc=rr(ic),vc=rr(oc),bc=rr(sc),wc=rr(ac),Ec=rr(uc,"Use firebase.firestore().collection() instead."),Sc={Firestore:dc,GeoPoint:Lr,Timestamp:qr,Blob:Pr,Transaction:pc,WriteBatch:mc,DocumentReference:yc,DocumentSnapshot:gc,Query:bc,QueryDocumentSnapshot:vc,QuerySnapshot:wc,CollectionReference:Ec,FieldPath:wu,FieldValue:Pu,setLogLevel:$u.setLogLevel,CACHE_SIZE_UNLIMITED:Yu};function Tc(t){t.INTERNAL.registerService("firestore",function(t){return new $u(t)},function(t){Zn(t&&"object"==typeof t,"shallowCopy() expects object parameter.");var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}(Sc))}Tc(t)}).apply(this,arguments)}catch(t){throw console.error(t),new Error("Cannot instantiate firebase-firestore - be sure to load firebase-app.js first.")}}); //# sourceMappingURL=firebase-firestore.js.map