mirror of
https://github.com/musix-org/musix-oss
synced 2024-11-13 02:20:18 +00:00
3 lines
356 KiB
JavaScript
3 lines
356 KiB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app"],e):e((t=t||self).firebase)}(this,function(Od){"use strict";try{(function(){var o,t;Od=Od&&Od.hasOwnProperty("default")?Od.default:Od,(t=o=o||{})[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";function e(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(e<t.logLevel)){var i=(new Date).toISOString();switch(e){case o.DEBUG:case o.VERBOSE:console.log.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case o.INFO:console.info.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case o.WARN:console.warn.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case o.ERROR:console.error.apply(console,["["+i+"] "+t.name+":"].concat(n));break;default:throw new Error("Attempted to log a message with an invalid logType (value: "+e+")")}}}var n=o.INFO,r=(Object.defineProperty(i.prototype,"logLevel",{get:function(){return this._logLevel},set:function(t){if(!(t in o))throw new TypeError("Invalid value assigned to `logLevel`");this._logLevel=t},enumerable:!0,configurable:!0}),Object.defineProperty(i.prototype,"logHandler",{get:function(){return this._logHandler},set:function(t){if("function"!=typeof t)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t},enumerable:!0,configurable:!0}),i.prototype.debug=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,o.DEBUG].concat(t))},i.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,o.VERBOSE].concat(t))},i.prototype.info=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,o.INFO].concat(t))},i.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,o.WARN].concat(t))},i.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,o.ERROR].concat(t))},i);function i(t){this.name=t,this._logLevel=n,this._logHandler=e}var a=function(t,e){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function s(t,e){function n(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function p(o,a,s,u){return new(s=s||Promise)(function(t,e){function n(t){try{i(u.next(t))}catch(t){e(t)}}function r(t){try{i(u.throw(t))}catch(t){e(t)}}function i(e){e.done?t(e.value):new s(function(t){t(e.value)}).then(n,r)}i((u=u.apply(o,a||[])).next())})}function d(n,r){var i,o,a,t,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return t={next:e(0),throw:e(1),return:e(2)},"function"==typeof Symbol&&(t[Symbol.iterator]=function(){return this}),t;function e(e){return function(t){return function(e){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,o&&(a=2&e[0]?o.return:e[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,e[1])).done)return a;switch(o=0,a&&(e=[2&e[0],a.value]),e[0]){case 0:case 1:a=e;break;case 4:return s.label++,{value:e[1],done:!1};case 5:s.label++,o=e[1],e=[0];continue;case 7:e=s.ops.pop(),s.trys.pop();continue;default:if(!(a=0<(a=s.trys).length&&a[a.length-1])&&(6===e[0]||2===e[0])){s=0;continue}if(3===e[0]&&(!a||e[1]>a[0]&&e[1]<a[3])){s.label=e[1];break}if(6===e[0]&&s.label<a[1]){s.label=a[1],a=e;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(e);break}a[2]&&s.ops.pop(),s.trys.pop();continue}e=r.call(n,s)}catch(t){e=[6,t],o=0}finally{i=a=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([e,t])}}}function u(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}var c,f=(s(h,c=Error),h);function h(t,e){var n=c.call(this,e)||this;return n.code=t,n.name="FirebaseError",Object.setPrototypeOf(n,h.prototype),Error.captureStackTrace&&Error.captureStackTrace(n,l.prototype.create),n}var l=(m.prototype.create=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];for(var r=e[0]||{},i=this.service+"/"+t,o=this.errors[t],a=o?function(t,r){return t.replace(g,function(t,e){var n=r[e];return null!=n?n.toString():"<"+e+"?>"})}(o,r):"Error",s=this.serviceName+": "+a+" ("+i+").",u=new f(i,s),c=0,h=Object.keys(r);c<h.length;c++){var l=h[c];"_"!==l.slice(-1)&&(l in u&&console.warn('Overwriting FirebaseError base field "'+l+'" can cause unexpected behavior.'),u[l]=r[l])}return u},m);function m(t,e,n){this.service=t,this.serviceName=e,this.errors=n}var y,g=/\{\$([^}]+)}/g,v="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},b=b||{},w=v;function E(t){return"string"==typeof t}function S(t){return"number"==typeof t}function T(t,e){t=t.split("."),e=e||w;for(var n=0;n<t.length;n++)if(null==(e=e[t[n]]))return null;return e}function I(){}function C(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function D(t){return"array"==C(t)}function N(t){var e=C(t);return"array"==e||"object"==e&&"number"==typeof t.length}function A(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var k="closure_uid_"+(1e9*Math.random()>>>0),R=0;function M(t,e,n){return t.call.apply(t.bind,arguments)}function _(e,n,t){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var t=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(t,r),e.apply(n,t)}}return function(){return e.apply(n,arguments)}}function O(t,e,n){return(O=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?M:_).apply(null,arguments)}function P(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}var L=Date.now||function(){return+new Date};function x(t,o){function e(){}e.prototype=o.prototype,t.N=o.prototype,t.prototype=new e,(t.prototype.constructor=t).yb=function(t,e,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return o.prototype[e].apply(t,r)}}function q(){this.j=this.j,this.i=this.i}q.prototype.j=!1,q.prototype.la=function(){if(!this.j&&(this.j=!0,this.G(),0))this[k]||(this[k]=++R)},q.prototype.G=function(){if(this.i)for(;this.i.length;)this.i.shift()()};var F=Array.prototype.indexOf?function(t,e){return Array.prototype.indexOf.call(t,e,void 0)}:function(t,e){if(E(t))return E(e)&&1==e.length?t.indexOf(e,0):-1;for(var n=0;n<t.length;n++)if(n in t&&t[n]===e)return n;return-1},V=Array.prototype.forEach?function(t,e,n){Array.prototype.forEach.call(t,e,n)}:function(t,e,n){for(var r=t.length,i=E(t)?t.split(""):t,o=0;o<r;o++)o in i&&e.call(n,i[o],o,t)};function B(t){return Array.prototype.concat.apply([],arguments)}function U(t){var e=t.length;if(0<e){for(var n=Array(e),r=0;r<e;r++)n[r]=t[r];return n}return[]}function Q(t){return/^[\s\xa0]*$/.test(t)}var K,j=String.prototype.trim?function(t){return t.trim()}:function(t){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(t)[1]};function W(t,e){return-1!=t.indexOf(e)}function G(t,e){return t<e?-1:e<t?1:0}t:{var z=w.navigator;if(z){var H=z.userAgent;if(H){K=H;break t}}K=""}function Y(t,e,n){for(var r in t)e.call(n,t[r],r,t)}function X(t){var e,n={};for(e in t)n[e]=t[e];return n}var J="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function $(t,e){for(var n,r,i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(var o=0;o<J.length;o++)n=J[o],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function Z(t){return Z[" "](t),t}Z[" "]=I;var tt,et,nt=W(K,"Opera"),rt=W(K,"Trident")||W(K,"MSIE"),it=W(K,"Edge"),ot=it||rt,at=W(K,"Gecko")&&!(W(K.toLowerCase(),"webkit")&&!W(K,"Edge"))&&!(W(K,"Trident")||W(K,"MSIE"))&&!W(K,"Edge"),st=W(K.toLowerCase(),"webkit")&&!W(K,"Edge");function ut(){var t=w.document;return t?t.documentMode:void 0}t:{var ct="",ht=(et=K,at?/rv:([^\);]+)(\)|;)/.exec(et):it?/Edge\/([\d\.]+)/.exec(et):rt?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(et):st?/WebKit\/(\S+)/.exec(et):nt?/(?:Version)[ \/]?(\S+)/.exec(et):void 0);if(ht&&(ct=ht?ht[1]:""),rt){var lt=ut();if(null!=lt&<>parseFloat(ct)){tt=String(lt);break t}}tt=ct}var ft,pt={};function dt(s){return function(t,e){var n=pt;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=e(t)}(s,function(){for(var t=0,e=j(String(tt)).split("."),n=j(String(s)).split("."),r=Math.max(e.length,n.length),i=0;0==t&&i<r;i++){var o=e[i]||"",a=n[i]||"";do{if(o=/(\d*)(\D*)(.*)/.exec(o)||["","","",""],a=/(\d*)(\D*)(.*)/.exec(a)||["","","",""],0==o[0].length&&0==a[0].length)break;t=G(0==o[1].length?0:parseInt(o[1],10),0==a[1].length?0:parseInt(a[1],10))||G(0==o[2].length,0==a[2].length)||G(o[2],a[2]),o=o[3],a=a[3]}while(0==t)}return 0<=t})}var mt=w.document;ft=mt&&rt?ut()||("CSS1Compat"==mt.compatMode?parseInt(tt,10):5):void 0;var yt=!rt||9<=Number(ft),gt=rt&&!dt("9"),vt=function(){if(!w.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});try{w.addEventListener("test",I,e),w.removeEventListener("test",I,e)}catch(t){}return t}();function bt(t,e){this.type=t,this.a=this.target=e,this.Ja=!0}function wt(t,e){if(bt.call(this,t?t.type:""),this.relatedTarget=this.a=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.pointerId=0,this.pointerType="",this.c=null,t){var n=this.type=t.type,r=t.changedTouches&&t.changedTouches.length?t.changedTouches[0]:null;if(this.target=t.target||t.srcElement,this.a=e,e=t.relatedTarget){if(at){t:{try{Z(e.nodeName);var i=!0;break t}catch(t){}i=!1}i||(e=null)}}else"mouseover"==n?e=t.fromElement:"mouseout"==n&&(e=t.toElement);this.relatedTarget=e,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==t.clientX?t.clientX:t.pageX,this.clientY=void 0!==t.clientY?t.clientY:t.pageY,this.screenX=t.screenX||0,this.screenY=t.screenY||0),this.button=t.button,this.key=t.key||"",this.ctrlKey=t.ctrlKey,this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.metaKey=t.metaKey,this.pointerId=t.pointerId||0,this.pointerType=E(t.pointerType)?t.pointerType:Et[t.pointerType]||"",(this.c=t).defaultPrevented&&this.b()}}bt.prototype.b=function(){this.Ja=!1},x(wt,bt);var Et={2:"touch",3:"pen",4:"mouse"};wt.prototype.b=function(){wt.N.b.call(this);var t=this.c;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,gt)try{(t.ctrlKey||112<=t.keyCode&&t.keyCode<=123)&&(t.keyCode=-1)}catch(t){}};var St="closure_listenable_"+(1e6*Math.random()|0),Tt=0;function It(t,e,n,r,i){this.listener=t,this.proxy=null,this.src=e,this.type=n,this.capture=!!r,this.da=i,this.key=++Tt,this.X=this.Z=!1}function Ct(t){t.X=!0,t.listener=null,t.proxy=null,t.src=null,t.da=null}function Dt(t){this.src=t,this.a={},this.b=0}function Nt(t,e){var n=e.type;if(n in t.a){var r,i=t.a[n],o=F(i,e);(r=0<=o)&&Array.prototype.splice.call(i,o,1),r&&(Ct(e),0==t.a[n].length&&(delete t.a[n],t.b--))}}function At(t,e,n,r){for(var i=0;i<t.length;++i){var o=t[i];if(!o.X&&o.listener==e&&o.capture==!!n&&o.da==r)return i}return-1}Dt.prototype.add=function(t,e,n,r,i){var o=t.toString();(t=this.a[o])||(t=this.a[o]=[],this.b++);var a=At(t,e,r,i);return-1<a?(e=t[a],n||(e.Z=!1)):((e=new It(e,this.src,o,!!r,i)).Z=n,t.push(e)),e};var kt="closure_lm_"+(1e6*Math.random()|0),Rt={};function Mt(t,e,n,r,i){if(r&&r.once)return function t(e,n,r,i,o){if(D(n)){for(var a=0;a<n.length;a++)t(e,n[a],r,i,o);return null}r=Vt(r);return e&&e[St]?e.Ba(n,r,A(i)?!!i.capture:!!i,o):_t(e,n,r,!0,i,o)}(t,e,n,r,i);if(D(e)){for(var o=0;o<e.length;o++)Mt(t,e[o],n,r,i);return null}return n=Vt(n),t&&t[St]?t.Aa(e,n,A(r)?!!r.capture:!!r,i):_t(t,e,n,!1,r,i)}function _t(t,e,n,r,i,o){if(!e)throw Error("Invalid event type");var a=A(i)?!!i.capture:!!i;if(a&&!yt)return null;var s=qt(t);if(s||(t[kt]=s=new Dt(t)),(n=s.add(e,n,r,a,o)).proxy)return n;if(r=function(){var e=xt,n=yt?function(t){return e.call(n.src,n.listener,t)}:function(t){if(!(t=e.call(n.src,n.listener,t)))return t};return n}(),(n.proxy=r).src=t,r.listener=n,t.addEventListener)vt||(i=a),void 0===i&&(i=!1),t.addEventListener(e.toString(),r,i);else if(t.attachEvent)t.attachEvent(Pt(e.toString()),r);else{if(!t.addListener||!t.removeListener)throw Error("addEventListener and attachEvent are unavailable.");t.addListener(r)}return n}function Ot(t){if(!S(t)&&t&&!t.X){var e=t.src;if(e&&e[St])Nt(e.c,t);else{var n=t.type,r=t.proxy;e.removeEventListener?e.removeEventListener(n,r,t.capture):e.detachEvent?e.detachEvent(Pt(n),r):e.addListener&&e.removeListener&&e.removeListener(r),(n=qt(e))?(Nt(n,t),0==n.b&&(n.src=null,e[kt]=null)):Ct(t)}}}function Pt(t){return t in Rt?Rt[t]:Rt[t]="on"+t}function Lt(t,e){var n=t.listener,r=t.da||t.src;return t.Z&&Ot(t),n.call(r,e)}function xt(t,e){return!!t.X||(yt?Lt(t,new wt(e,this)):Lt(t,e=new wt(e||T("window.event"),this)))}function qt(t){return(t=t[kt])instanceof Dt?t:null}var Ft="__closure_events_fn_"+(1e9*Math.random()>>>0);function Vt(e){return"function"==C(e)?e:(e[Ft]||(e[Ft]=function(t){return e.handleEvent(t)}),e[Ft])}function Bt(){q.call(this),this.c=new Dt(this),(this.J=this).B=null}function Ut(t,e,n,r){if(!(e=t.c.a[String(e)]))return!0;e=e.concat();for(var i=!0,o=0;o<e.length;++o){var a=e[o];if(a&&!a.X&&a.capture==n){var s=a.listener,u=a.da||a.src;a.Z&&Nt(t.c,a),i=!1!==s.call(u,r)&&i}}return i&&0!=r.Ja}x(Bt,q),Bt.prototype[St]=!0,(y=Bt.prototype).addEventListener=function(t,e,n,r){Mt(this,t,e,n,r)},y.removeEventListener=function(t,e,n,r){!function t(e,n,r,i,o){if(D(n))for(var a=0;a<n.length;a++)t(e,n[a],r,i,o);else i=A(i)?!!i.capture:!!i,r=Vt(r),e&&e[St]?(e=e.c,(n=String(n).toString())in e.a&&-1<(r=At(a=e.a[n],r,i,o))&&(Ct(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete e.a[n],e.b--))):(e=e&&qt(e))&&(n=e.a[n.toString()],e=-1,n&&(e=At(n,r,i,o)),(r=-1<e?n[e]:null)&&Ot(r))}(this,t,e,n,r)},y.dispatchEvent=function(t){var e,n=this.B;if(n)for(e=[];n;n=n.B)e.push(n);n=this.J;var r=t.type||t;if(E(t))t=new bt(t,n);else if(t instanceof bt)t.target=t.target||n;else{var i=t;$(t=new bt(r,n),i)}if(i=!0,e)for(var o=e.length-1;0<=o;o--){var a=t.a=e[o];i=Ut(a,r,!0,t)&&i}if(i=Ut(a=t.a=n,r,!0,t)&&i,i=Ut(a,r,!1,t)&&i,e)for(o=0;o<e.length;o++)i=Ut(a=t.a=e[o],r,!1,t)&&i;return i},y.G=function(){if(Bt.N.G.call(this),this.c){var t,e=this.c;for(t in e.a){for(var n=e.a[t],r=0;r<n.length;r++)Ct(n[r]);delete e.a[t],e.b--}}this.B=null},y.Aa=function(t,e,n,r){return this.c.add(String(t),e,!1,n,r)},y.Ba=function(t,e,n,r){return this.c.add(String(t),e,!0,n,r)};var Qt=w.JSON.stringify;function Kt(t,e){this.c=t,this.f=e,this.b=0,this.a=null}function jt(){this.b=this.a=null}Kt.prototype.get=function(){if(0<this.b){this.b--;var t=this.a;this.a=t.next,t.next=null}else t=this.c();return t};var Wt,Gt=new Kt(function(){return new zt},function(t){t.reset()});function zt(){this.next=this.b=this.a=null}function Ht(t){w.setTimeout(function(){throw t},0)}function Yt(t,e){Wt||function(){var t=w.Promise.resolve(void 0);Wt=function(){t.then($t)}}(),Xt||(Wt(),Xt=!0),Jt.add(t,e)}jt.prototype.add=function(t,e){var n=Gt.get();n.set(t,e),this.b?this.b.next=n:this.a=n,this.b=n},zt.prototype.set=function(t,e){this.a=t,this.b=e,this.next=null};var Xt=!(zt.prototype.reset=function(){this.next=this.b=this.a=null}),Jt=new jt;function $t(){for(var t;r=n=void 0,r=null,(n=Jt).a&&(r=n.a,n.a=n.a.next,n.a||(n.b=null),r.next=null),t=r;){try{t.a.call(t.b)}catch(t){Ht(t)}var e=Gt;e.f(t),e.b<100&&(e.b++,t.next=e.a,e.a=t)}var n,r;Xt=!1}function Zt(t,e){Bt.call(this),this.b=t||1,this.a=e||w,this.f=O(this.gb,this),this.g=L()}function te(t){t.ba=!1,t.L&&(t.a.clearTimeout(t.L),t.L=null)}function ee(t,e,n){if("function"==C(t))n&&(t=O(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=O(t.handleEvent,t)}return 2147483647<Number(e)?-1:w.setTimeout(t,e||0)}function ne(t,e,n){q.call(this),this.f=null!=n?O(t,n):t,this.c=e,this.b=O(this.ab,this),this.a=[]}function re(t){t.U=ee(t.b,t.c),t.f.apply(null,t.a)}function ie(t){q.call(this),this.b=t,this.a={}}x(Zt,Bt),(y=Zt.prototype).ba=!1,y.L=null,y.gb=function(){if(this.ba){var t=L()-this.g;0<t&&t<.8*this.b?this.L=this.a.setTimeout(this.f,this.b-t):(this.L&&(this.a.clearTimeout(this.L),this.L=null),this.dispatchEvent("tick"),this.ba&&(te(this),this.start()))}},y.start=function(){this.ba=!0,this.L||(this.L=this.a.setTimeout(this.f,this.b),this.g=L())},y.G=function(){Zt.N.G.call(this),te(this),delete this.a},x(ne,q),(y=ne.prototype).ea=!1,y.U=null,y.Ua=function(t){this.a=arguments,this.U?this.ea=!0:re(this)},y.G=function(){ne.N.G.call(this),this.U&&(w.clearTimeout(this.U),this.U=null,this.ea=!1,this.a=[])},y.ab=function(){this.U=null,this.ea&&(this.ea=!1,re(this))},x(ie,q);var oe=[];function ae(t,e,n,r){D(n)||(n&&(oe[0]=n.toString()),n=oe);for(var i=0;i<n.length;i++){var o=Mt(e,n[i],r||t.handleEvent,!1,t.b||t);if(!o)break;t.a[o.key]=o}}function se(t){Y(t.a,function(t,e){this.a.hasOwnProperty(e)&&Ot(t)},t),t.a={}}function ue(){}ie.prototype.G=function(){ie.N.G.call(this),se(this)},ie.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var ce=new Bt;function he(t){bt.call(this,"serverreachability",t)}function le(t){ce.dispatchEvent(new he(ce,t))}function fe(t){bt.call(this,"statevent",t)}function pe(t){ce.dispatchEvent(new fe(ce,t))}function de(t){bt.call(this,"timingevent",t)}function me(t,e){if("function"!=C(t))throw Error("Fn must not be null and must be a function");return w.setTimeout(function(){t()},e)}x(he,bt),x(fe,bt),x(de,bt);var ye={NO_ERROR:0,hb:1,ob:2,nb:3,kb:4,mb:5,pb:6,Ma:7,TIMEOUT:8,sb:9},ge={jb:"complete",wb:"success",Na:"error",Ma:"abort",ub:"ready",vb:"readystatechange",TIMEOUT:"timeout",qb:"incrementaldata",tb:"progress",lb:"downloadprogress",xb:"uploadprogress"};function ve(){}function be(t){var e;return(e=t.a)||(e=t.a={}),e}function we(){}ve.prototype.a=null;var Ee,Se={OPEN:"a",ib:"b",Na:"c",rb:"d"};function Te(){bt.call(this,"d")}function Ie(){bt.call(this,"c")}function Ce(){}function De(t,e,n){this.g=t,this.W=e,this.V=n||1,this.I=new ie(this),this.O=Ne,t=ot?125:void 0,this.P=new Zt(t),this.h=null,this.b=!1,this.l=this.D=this.f=this.F=this.v=this.R=this.i=null,this.j=[],this.a=null,this.A=0,this.c=this.w=null,this.o=-1,this.m=!1,this.J=0,this.B=null,this.s=this.S=this.H=!1}x(Te,bt),x(Ie,bt),x(Ce,ve),Ee=new Ce;var Ne=45e3,Ae={},ke={};function Re(t,e,n){t.F=1,t.f=en(He(e)),t.l=n,t.H=!0,_e(t,null)}function Me(t,e,n,r){t.F=1,t.f=en(He(e)),t.l=null,t.H=n,_e(t,r)}function _e(t,e){t.v=L(),Le(t),t.D=He(t.f),tn(t.D,"t",t.V),t.A=0,t.a=t.g.$(t.g.Y()?e:null),0<t.J&&(t.B=new ne(O(t.Ka,t,t.a),t.J)),ae(t.I,t.a,"readystatechange",t.eb),e=t.h?X(t.h):{},t.l?(t.w||(t.w="POST"),e["Content-Type"]="application/x-www-form-urlencoded",t.a.ca(t.D,t.w,t.l,e)):(t.w="GET",t.a.ca(t.D,t.w,null,e)),le(1)}function Oe(t,e,n){for(var r=!0;!t.m&&t.A<n.length;){var i=Pe(t,n);if(i==ke){4==e&&(t.c=4,pe(14),r=!1);break}if(i==Ae){t.c=4,pe(15),r=!1;break}Be(t,i)}4==e&&0==n.length&&(t.c=1,pe(16),r=!1),t.b=t.b&&r,r||(Ve(t),Fe(t))}function Pe(t,e){var n=t.A,r=e.indexOf("\n",n);return-1==r?ke:(n=Number(e.substring(n,r)),isNaN(n)?Ae:(r+=1)+n>e.length?ke:(e=e.substr(r,n),t.A=r+n,e))}function Le(t){t.R=L()+t.O,xe(t,t.O)}function xe(t,e){if(null!=t.i)throw Error("WatchDog timer not null");t.i=me(O(t.bb,t),e)}function qe(t){t.i&&(w.clearTimeout(t.i),t.i=null)}function Fe(t){t.g.Da()||t.m||t.g.na(t)}function Ve(t){qe(t);var e=t.B;e&&"function"==typeof e.la&&e.la(),t.B=null,te(t.P),se(t.I),t.a&&(e=t.a,t.a=null,e.abort(),e.la())}function Be(t,e){try{t.g.Ga(t,e),le(4)}catch(t){}}function Ue(t,e){if(t.forEach&&"function"==typeof t.forEach)t.forEach(e,void 0);else if(N(t)||E(t))V(t,e,void 0);else{if(t.K&&"function"==typeof t.K)var n=t.K();else if(t.C&&"function"==typeof t.C)n=void 0;else if(N(t)||E(t)){n=[];for(var r=t.length,i=0;i<r;i++)n.push(i)}else for(i in n=[],r=0,t)n[r++]=i;i=(r=function(t){if(t.C&&"function"==typeof t.C)return t.C();if(E(t))return t.split("");if(N(t)){for(var e=[],n=t.length,r=0;r<n;r++)e.push(t[r]);return e}for(r in e=[],n=0,t)e[n++]=t[r];return e}(t)).length;for(var o=0;o<i;o++)e.call(void 0,r[o],n&&n[o],t)}}function Qe(t,e){this.b={},this.a=[],this.c=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(t)if(t instanceof Qe)for(n=t.K(),r=0;r<n.length;r++)this.set(n[r],t.get(n[r]));else for(r in t)this.set(r,t[r])}function Ke(t,e){We(t.b,e)&&(delete t.b[e],t.c--,t.a.length>2*t.c&&je(t))}function je(t){if(t.c!=t.a.length){for(var e=0,n=0;e<t.a.length;){var r=t.a[e];We(t.b,r)&&(t.a[n++]=r),e++}t.a.length=n}if(t.c!=t.a.length){var i={};for(n=e=0;e<t.a.length;)We(i,r=t.a[e])||(i[t.a[n++]=r]=1),e++;t.a.length=n}}function We(t,e){return Object.prototype.hasOwnProperty.call(t,e)}(y=De.prototype).setTimeout=function(t){this.O=t},y.eb=function(t){t=t.target;var e=this.B;e&&3==Hn(t)?e.Ua():this.Ka(t)},y.Ka=function(t){try{if(t==this.a)t:{var e=Hn(this.a),n=this.a.ya(),r=this.a.T();if(!(e<3||3==e&&!ot&&!this.a.aa())){this.m||4!=e||7==n||le(8==n||r<=0?3:2),qe(this);var i=this.a.T();this.o=i;var o=this.a.aa();if(this.b=200==i){if(this.S&&!this.s){e:{if(this.a){var a=Yn(this.a,"X-HTTP-Initial-Response");if(a&&!Q(a)){var s=a;break e}}s=null}if(!s){this.b=!1,this.c=3,pe(12),Ve(this),Fe(this);break t}this.s=!0,Be(this,s)}this.H?(Oe(this,e,o),ot&&this.b&&3==e&&(ae(this.I,this.P,"tick",this.cb),this.P.start())):Be(this,o),4==e&&Ve(this),this.b&&!this.m&&(4==e?this.g.na(this):(this.b=!1,Le(this)))}else 400==i&&0<o.indexOf("Unknown SID")?(this.c=3,pe(12)):(this.c=0,pe(13)),Ve(this),Fe(this)}}}catch(t){}},y.cb=function(){if(this.a){var t=Hn(this.a),e=this.a.aa();this.A<e.length&&(qe(this),Oe(this,t,e),this.b&&4!=t&&Le(this))}},y.cancel=function(){this.m=!0,Ve(this)},y.bb=function(){this.i=null;var t=L();0<=t-this.R?(2!=this.F&&(le(3),pe(17)),Ve(this),this.c=2,Fe(this)):xe(this,this.R-t)},(y=Qe.prototype).C=function(){je(this);for(var t=[],e=0;e<this.a.length;e++)t.push(this.b[this.a[e]]);return t},y.K=function(){return je(this),this.a.concat()},y.get=function(t,e){return We(this.b,t)?this.b[t]:e},y.set=function(t,e){We(this.b,t)||(this.c++,this.a.push(t)),this.b[t]=e},y.forEach=function(t,e){for(var n=this.K(),r=0;r<n.length;r++){var i=n[r],o=this.get(i);t.call(e,o,i,this)}};var Ge=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function ze(t,e){var n;this.b=this.j=this.f="",this.i=null,this.g=this.a="",this.h=!1,t instanceof ze?(this.h=void 0!==e?e:t.h,Ye(this,t.f),this.j=t.j,Xe(this,t.b),Je(this,t.i),this.a=t.a,$e(this,yn(t.c)),this.g=t.g):t&&(n=String(t).match(Ge))?(this.h=!!e,Ye(this,n[1]||"",!0),this.j=nn(n[2]||""),Xe(this,n[3]||"",!0),Je(this,n[4]),this.a=nn(n[5]||"",!0),$e(this,n[6]||"",!0),this.g=nn(n[7]||"")):(this.h=!!e,this.c=new ln(null,this.h))}function He(t){return new ze(t)}function Ye(t,e,n){t.f=n?nn(e,!0):e,t.f&&(t.f=t.f.replace(/:$/,""))}function Xe(t,e,n){t.b=n?nn(e,!0):e}function Je(t,e){if(e){if(e=Number(e),isNaN(e)||e<0)throw Error("Bad port number "+e);t.i=e}else t.i=null}function $e(t,e,n){e instanceof ln?(t.c=e,function(t,e){e&&!t.f&&(fn(t),t.c=null,t.a.forEach(function(t,e){var n=e.toLowerCase();e!=n&&(pn(this,e),mn(this,n,t))},t)),t.f=e}(t.c,t.h)):(n||(e=rn(e,cn)),t.c=new ln(e,t.h))}function Ze(t,e,n){t.c.set(e,n)}function tn(t,e,n){D(n)||(n=[String(n)]),mn(t.c,e,n)}function en(t){return Ze(t,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^L()).toString(36)),t}function nn(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function rn(t,e,n){return E(t)?(t=encodeURI(t).replace(e,on),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function on(t){return"%"+((t=t.charCodeAt(0))>>4&15).toString(16)+(15&t).toString(16)}ze.prototype.toString=function(){var t=[],e=this.f;e&&t.push(rn(e,an,!0),":");var n=this.b;return!n&&"file"!=e||(t.push("//"),(e=this.j)&&t.push(rn(e,an,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.i)&&t.push(":",String(n))),(n=this.a)&&(this.b&&"/"!=n.charAt(0)&&t.push("/"),t.push(rn(n,"/"==n.charAt(0)?un:sn,!0))),(n=this.c.toString())&&t.push("?",n),(n=this.g)&&t.push("#",rn(n,hn)),t.join("")},ze.prototype.resolve=function(t){var e=He(this),n=!!t.f;n?Ye(e,t.f):n=!!t.j,n?e.j=t.j:n=!!t.b,n?Xe(e,t.b):n=null!=t.i;var r=t.a;if(n)Je(e,t.i);else if(n=!!t.a){if("/"!=r.charAt(0))if(this.b&&!this.a)r="/"+r;else{var i=e.a.lastIndexOf("/");-1!=i&&(r=e.a.substr(0,i+1)+r)}if(".."==(i=r)||"."==i)r="";else if(W(i,"./")||W(i,"/.")){r=0==i.lastIndexOf("/",0),i=i.split("/");for(var o=[],a=0;a<i.length;){var s=i[a++];"."==s?r&&a==i.length&&o.push(""):".."==s?((1<o.length||1==o.length&&""!=o[0])&&o.pop(),r&&a==i.length&&o.push("")):(o.push(s),r=!0)}r=o.join("/")}else r=i}return n?e.a=r:n=""!==t.c.toString(),n?$e(e,yn(t.c)):n=!!t.g,n&&(e.g=t.g),e};var an=/[#\/\?@]/g,sn=/[#\?:]/g,un=/[#\?]/g,cn=/[#\?@]/g,hn=/#/g;function ln(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function fn(n){n.a||(n.a=new Qe,n.b=0,n.c&&function(t,e){if(t){t=t.split("&");for(var n=0;n<t.length;n++){var r=t[n].indexOf("="),i=null;if(0<=r){var o=t[n].substring(0,r);i=t[n].substring(r+1)}else o=t[n];e(o,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(n.c,function(t,e){n.add(decodeURIComponent(t.replace(/\+/g," ")),e)}))}function pn(t,e){fn(t),e=gn(t,e),We(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,Ke(t.a,e))}function dn(t,e){return fn(t),e=gn(t,e),We(t.a.b,e)}function mn(t,e,n){pn(t,e),0<n.length&&(t.c=null,t.a.set(gn(t,e),U(n)),t.b+=n.length)}function yn(t){var e=new ln;return e.c=t.c,t.a&&(e.a=new Qe(t.a),e.b=t.b),e}function gn(t,e){return e=String(e),t.f&&(e=e.toLowerCase()),e}function vn(t){this.a=t,this.b=this.h=null,this.g=!1,this.i=null,this.c=-1,this.l=this.f=null}function bn(t){var e=t.a.F.a;if(null!=e)pe(4),e?(pe(10),sr(t.a,t,!1)):(pe(11),sr(t.a,t,!0));else{t.b=new De(t,void 0,void 0),t.b.h=t.h,e=fr(e=t.a,e.Y()?t.f:null,t.i),pe(4),tn(e,"TYPE","xmlhttp");var n=t.a.j,r=t.a.I;n&&r&&Ze(e,n,r),Me(t.b,e,!1,t.f)}}function wn(){this.a=this.b=null}function En(){this.a=new Qe}function Sn(t){var e=typeof t;return"object"==e&&t||"function"==e?"o"+(t[k]||(t[k]=++R)):e.charAt(0)+t}function Tn(t,e){this.b=t,this.a=e}function In(t){this.g=t||Cn,t=w.PerformanceNavigationTiming?0<(t=w.performance.getEntriesByType("navigation")).length&&("hq"==t[0].nextHopProtocol||"h2"==t[0].nextHopProtocol):!!(w.ka&&w.ka.Ea&&w.ka.Ea()&&w.ka.Ea().zb),this.f=t?this.g:1,this.a=null,1<this.f&&(this.a=new En),this.b=null,this.c=[]}(y=ln.prototype).add=function(t,e){fn(this),this.c=null,t=gn(this,t);var n=this.a.get(t);return n||this.a.set(t,n=[]),n.push(e),this.b+=1,this},y.forEach=function(n,r){fn(this),this.a.forEach(function(t,e){V(t,function(t){n.call(r,t,e,this)},this)},this)},y.K=function(){fn(this);for(var t=this.a.C(),e=this.a.K(),n=[],r=0;r<e.length;r++)for(var i=t[r],o=0;o<i.length;o++)n.push(e[r]);return n},y.C=function(t){fn(this);var e=[];if(E(t))dn(this,t)&&(e=B(e,this.a.get(gn(this,t))));else{t=this.a.C();for(var n=0;n<t.length;n++)e=B(e,t[n])}return e},y.set=function(t,e){return fn(this),this.c=null,dn(this,t=gn(this,t))&&(this.b-=this.a.get(t).length),this.a.set(t,[e]),this.b+=1,this},y.get=function(t,e){return t&&0<(t=this.C(t)).length?String(t[0]):e},y.toString=function(){if(this.c)return this.c;if(!this.a)return"";for(var t=[],e=this.a.K(),n=0;n<e.length;n++){var r=e[n],i=encodeURIComponent(String(r));r=this.C(r);for(var o=0;o<r.length;o++){var a=i;""!==r[o]&&(a+="="+encodeURIComponent(String(r[o]))),t.push(a)}}return this.c=t.join("&")},x(function(){},function(){}),(y=vn.prototype).M=null,y.$=function(t){return this.a.$(t)},y.abort=function(){this.b&&(this.b.cancel(),this.b=null),this.c=-1},y.Da=function(){return!1},y.Ga=function(t,e){if(this.c=t.o,0==this.M){if(!this.a.o&&(t=t.a)){var n=Yn(t,"X-Client-Wire-Protocol");this.l=n||null,this.a.j&&(t=Yn(t,"X-HTTP-Session-Id"))&&(this.a.I=t)}if(e){try{var r=this.a.ja.a.parse(e)}catch(t){return(e=this.a).m=this.c,void hr(e,2)}this.f=r[0]}else(e=this.a).m=this.c,hr(e,2)}else 1==this.M&&(this.g?pe(6):"11111"==e?(pe(5),this.g=!0,(!rt||10<=Number(ft))&&(this.c=200,this.b.cancel(),pe(11),sr(this.a,this,!0))):(pe(7),this.g=!1))},y.na=function(){if(this.c=this.b.o,this.b.b)0==this.M?(this.M=1,bn(this)):1==this.M&&(this.g?(pe(11),sr(this.a,this,!0)):(pe(10),sr(this.a,this,!1)));else{0==this.M?pe(8):1==this.M&&pe(9);var t=this.a;t.m=this.c,hr(t,2)}},y.Y=function(){return this.a.Y()},y.ma=function(){return this.a.ma()},En.prototype.add=function(t){this.a.set(Sn(t),t)},En.prototype.C=function(){return this.a.C()};var Cn=10;function Dn(t,e){!t.a&&(W(e,"spdy")||W(e,"quic")||W(e,"h2"))&&(t.f=t.g,t.a=new En,t.b&&(Rn(t,t.b),t.b=null))}function Nn(t){return!!t.b||!!t.a&&t.a.a.c>=t.f}function An(t){return t.b?1:t.a?t.a.a.c:0}function kn(t,e){return t=t.b?t.b==e:!!t.a&&(e=Sn(e),We(t.a.a.b,e))}function Rn(t,e){t.a?t.a.add(e):t.b=e}function Mn(t,e){var n;t.b&&t.b==e?t.b=null:((n=t.a)&&(n=Sn(e),n=We(t.a.a.b,n)),n&&Ke(t.a.a,Sn(e)))}function _n(t){if(null!=t.b)return t.c.concat(t.b.j);if(null==t.a||0==t.a.a.c)return U(t.c);var e=t.c;return V(t.a.C(),function(t){e=e.concat(t.j)}),e}function On(){}function Pn(){this.a=new On}function Ln(t,r,e){var i=e||"";try{Ue(t,function(t,e){var n=t;A(t)&&(n=Qt(t)),r.push(i+e+"="+encodeURIComponent(n))})}catch(t){throw r.push(i+"type="+encodeURIComponent("_badmap")),t}}function xn(t,e,n,r,i){try{e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,i(r)}catch(t){}}In.prototype.cancel=function(){this.c=_n(this),this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(V(this.a.C(),function(t){t.cancel()}),function(t){t.b={},t.a.length=0,t.c=0}(this.a.a))},On.prototype.stringify=function(t){return w.JSON.stringify(t,void 0)},On.prototype.parse=function(t){return w.JSON.parse(t,void 0)};var qn=w.JSON.parse;function Fn(t){Bt.call(this),this.headers=new Qe,this.H=t||null,this.b=!1,this.s=this.a=null,this.A="",this.h=0,this.f="",this.g=this.w=this.l=this.v=!1,this.o=0,this.m=null,this.I=Vn,this.D=this.F=!1}x(Fn,Bt);var Vn="",Bn=/^https?$/i,Un=["POST","PUT"];function Qn(t){return"content-type"==t.toLowerCase()}function Kn(t,e){t.b=!1,t.a&&(t.g=!0,t.a.abort(),t.g=!1),t.f=e,t.h=5,jn(t),Gn(t)}function jn(t){t.v||(t.v=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function Wn(t){if(t.b&&void 0!==b&&(!t.s[1]||4!=Hn(t)||2!=t.T()))if(t.l&&4==Hn(t))ee(t.Fa,0,t);else if(t.dispatchEvent("readystatechange"),4==Hn(t)){t.b=!1;try{var e,n=t.T();t:switch(n){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var r=!0;break t;default:r=!1}if(!(e=r)){var i;if(i=0===n){var o=String(t.A).match(Ge)[1]||null;if(!o&&w.self&&w.self.location){var a=w.self.location.protocol;o=a.substr(0,a.length-1)}i=!Bn.test(o?o.toLowerCase():"")}e=i}e?(t.dispatchEvent("complete"),t.dispatchEvent("success")):(t.h=6,t.f=t.za()+" ["+t.T()+"]",jn(t))}finally{Gn(t)}}}function Gn(t,e){if(t.a){zn(t);var n=t.a,r=t.s[0]?I:null;t.a=null,t.s=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(t){}}}function zn(t){t.a&&t.D&&(t.a.ontimeout=null),t.m&&(w.clearTimeout(t.m),t.m=null)}function Hn(t){return t.a?t.a.readyState:0}function Yn(t,e){return t.a?t.a.getResponseHeader(e):null}function Xn(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=function(t){var n="";return Y(t,function(t,e){n+=e,n+=":",n+=t,n+="\r\n"}),n}(n),E(t)){if(e=encodeURIComponent(String(e)),e+=n=null!=n?"="+encodeURIComponent(String(n)):""){if((n=t.indexOf("#"))<0&&(n=t.length),(r=t.indexOf("?"))<0||n<r){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 Ze(t,e,n),t}function Jn(t){this.f=[],this.F=new wn,this.ga=this.pa=this.B=this.ha=this.a=this.I=this.j=this.V=this.g=this.J=this.i=null,this.Ra=this.P=0,this.Pa=!!T("internalChannelParams.failFast",t),this.ia=this.w=this.s=this.l=this.h=this.c=null,this.oa=!0,this.m=this.ra=this.O=-1,this.S=this.v=this.A=0,this.Oa=T("internalChannelParams.baseRetryDelayMs",t)||5e3,this.Sa=T("internalChannelParams.retryDelaySeedMs",t)||1e4,this.Qa=T("internalChannelParams.forwardChannelMaxRetries",t)||2,this.qa=T("internalChannelParams.forwardChannelRequestTimeoutMs",t)||2e4,this.La=t&&t.Ab||void 0,this.D=void 0,this.R=t&&t.supportsCrossDomainXhr||!1,this.H="",this.b=new In(t&&t.concurrentRequestLimit),this.ja=new Pn,this.o=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,(this.W=t&&t.fastHandshake||!1)&&!this.o&&(this.o=!0),t&&t.forceLongPolling&&(this.oa=!1),this.fa=void 0}function $n(t){if(Zn(t),3==t.u){var e=t.P++,n=He(t.B);Ze(n,"SID",t.H),Ze(n,"RID",e),Ze(n,"TYPE","terminate"),rr(t,n),(e=new De(t,e,void 0)).F=2,e.f=en(He(n)),n=!1,w.navigator&&w.navigator.sendBeacon&&(n=w.navigator.sendBeacon(e.f.toString(),"")),!n&&w.Image&&((new Image).src=e.f,n=!0),n||(e.a=e.g.$(null),e.a.ca(e.f)),e.v=L(),Le(e)}lr(t)}function Zn(t){t.w&&(t.w.abort(),t.w=null),t.a&&(t.a.cancel(),t.a=null),t.l&&(w.clearTimeout(t.l),t.l=null),ur(t),t.b.cancel(),t.h&&(S(t.h)&&w.clearTimeout(t.h),t.h=null)}function tr(t,e){t.f.push(new Tn(t.Ra++,e)),3==t.u&&er(t)}function er(t){Nn(t.b)||t.h||(t.h=!0,Yt(t.Ia,t),t.A=0)}function nr(t,e){var n;n=e?e.W:t.P++;var r=He(t.B);Ze(r,"SID",t.H),Ze(r,"RID",n),Ze(r,"AID",t.O),rr(t,r),t.g&&t.i&&Xn(r,t.g,t.i),n=new De(t,n,t.A+1),null===t.g&&(n.h=t.i),e&&(t.f=e.j.concat(t.f)),e=ir(t,n,1e3),n.setTimeout(Math.round(.5*t.qa)+Math.round(.5*t.qa*Math.random())),Rn(t.b,n),Re(n,r,e)}function rr(t,n){t.c&&Ue({},function(t,e){Ze(n,e,t)})}function ir(t,e,n){n=Math.min(t.f.length,n);var r=t.c?O(t.c.Ta,t.c,t):null;t:for(var i=t.f,o=-1;;){var a=["count="+n];-1==o?0<n?(o=i[0].b,a.push("ofs="+o)):o=0:a.push("ofs="+o);for(var s=!0,u=0;u<n;u++){var c=i[u].b,h=i[u].a;if((c-=o)<0)o=Math.max(0,i[u].b-100),s=!1;else try{Ln(h,a,"req"+c+"_")}catch(t){r&&r(h)}}if(s){r=a.join("&");break t}}return t=t.f.splice(0,n),e.j=t,r}function or(t){t.a||t.l||(t.S=1,Yt(t.Ha,t),t.v=0)}function ar(t){return!(t.a||t.l||3<=t.v)&&(t.S++,t.l=me(O(t.Ha,t),cr(t,t.v)),t.v++,!0)}function sr(t,e,n){var r=e.l;r&&Dn(t.b,r),t.ia=t.oa&&n,t.m=e.c,t.B=fr(t,null,t.ha),er(t)}function ur(t){null!=t.s&&(w.clearTimeout(t.s),t.s=null)}function cr(t,e){var n=t.Oa+Math.floor(Math.random()*t.Sa);return t.ma()||(n*=2),n*e}function hr(t,e){if(2==e){var n=null;t.c&&(n=null);var r=O(t.fb,t);n||(n=new ze("//www.google.com/images/cleardot.gif"),w.location&&"http"==w.location.protocol||Ye(n,"https"),en(n)),function(t,e){var n=new ue;if(w.Image){var r=new Image;r.onload=P(xn,n,r,"TestLoadImage: loaded",!0,e),r.onerror=P(xn,n,r,"TestLoadImage: error",!1,e),r.onabort=P(xn,n,r,"TestLoadImage: abort",!1,e),r.ontimeout=P(xn,n,r,"TestLoadImage: timeout",!1,e),w.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=t}else e(!1)}(n.toString(),r)}else pe(2);t.u=0,t.c&&t.c.ta(e),lr(t),Zn(t)}function lr(t){t.u=0,t.m=-1,t.c&&(0==_n(t.b).length&&0==t.f.length||(t.b.c.length=0,U(t.f),t.f.length=0),t.c.sa())}function fr(t,e,n){var r=function(t){return t instanceof ze?He(t):new ze(t,void 0)}(n);if(""!=r.b)e&&Xe(r,e+"."+r.b),Je(r,r.i);else{var i,o=w.location;i=e?e+"."+o.hostname:o.hostname,r=function(t,e,n,r){var i=new ze(null,void 0);return t&&Ye(i,t),e&&Xe(i,e),n&&Je(i,n),r&&(i.a=r),i}(o.protocol,i,+o.port,n)}return t.V&&Y(t.V,function(t,e){Ze(r,e,t)}),e=t.j,n=t.I,e&&n&&Ze(r,e,n),Ze(r,"VER",t.wa),rr(t,r),r}function pr(){}function dr(){if(rt&&!(10<=Number(ft)))throw Error("Environmental error: no available transport.")}function mr(t,e){Bt.call(this),this.a=new Jn(e),this.g=t,this.m=e&&e.testUrl?e.testUrl:function(t){for(var e=t,n=1;n<arguments.length;n++){var r,i=arguments[n];if(0==i.lastIndexOf("/",0))e=i;else(r=""==e)||(r=0<=(r=e.length-1)&&e.indexOf("/",r)==r),e+=r?i:"/"+i}return e}(this.g,"test"),this.b=e&&e.messageUrlParams||null,t=e&&e.messageHeaders||null,e&&e.clientProtocolHeaderRequired&&(t?t["X-Client-Protocol"]="webchannel":t={"X-Client-Protocol":"webchannel"}),this.a.i=t,t=e&&e.initMessageHeaders||null,e&&e.messageContentType&&(t?t["X-WebChannel-Content-Type"]=e.messageContentType:t={"X-WebChannel-Content-Type":e.messageContentType}),e&&e.xa&&(t?t["X-WebChannel-Client-Profile"]=e.xa:t={"X-WebChannel-Client-Profile":e.xa}),this.a.J=t,(t=e&&e.httpHeadersOverwriteParam)&&!Q(t)&&(this.a.g=t),this.l=e&&e.supportsCrossDomainXhr||!1,this.h=e&&e.sendRawJson||!1,(e=e&&e.httpSessionIdParam)&&!Q(e)&&(this.a.j=e,null!==(t=this.b)&&e in t&&(e in(t=this.b)&&delete t[e])),this.f=new vr(this)}function yr(t){Te.call(this);var e=t.__sm__;if(e){t:{for(var n in e){t=n;break t}t=void 0}(this.c=t)?(t=this.c,this.data=null!==e&&t in e?e[t]:void 0):this.data=e}else this.data=t}function gr(){Ie.call(this),this.status=1}function vr(t){this.a=t}(y=Fn.prototype).ca=function(t,e,n,r){if(this.a)throw Error("[goog.net.XhrIo] Object is active with another request="+this.A+"; newUri="+t);e=e?e.toUpperCase():"GET",this.A=t,this.f="",this.h=0,this.v=!1,this.b=!0,this.a=new XMLHttpRequest,this.s=this.H?be(this.H):be(Ee),this.a.onreadystatechange=O(this.Fa,this);try{this.w=!0,this.a.open(e,String(t),!0),this.w=!1}catch(t){return void Kn(this,t)}t=n||"";var i=new Qe(this.headers);r&&Ue(r,function(t,e){i.set(e,t)}),r=function(t){t:{for(var e=Qn,n=t.length,r=E(t)?t.split(""):t,i=0;i<n;i++)if(i in r&&e.call(void 0,r[i],i,t)){e=i;break t}e=-1}return e<0?null:E(t)?t.charAt(e):t[e]}(i.K()),n=w.FormData&&t instanceof w.FormData,0<=F(Un,e)&&!r&&!n&&i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach(function(t,e){this.a.setRequestHeader(e,t)},this),this.I&&(this.a.responseType=this.I),"withCredentials"in this.a&&this.a.withCredentials!==this.F&&(this.a.withCredentials=this.F);try{zn(this),0<this.o&&((this.D=function(t){return rt&&dt(9)&&S(t.timeout)&&void 0!==t.ontimeout}(this.a))?(this.a.timeout=this.o,this.a.ontimeout=O(this.Ca,this)):this.m=ee(this.Ca,this.o,this)),this.l=!0,this.a.send(t),this.l=!1}catch(t){Kn(this,t)}},y.Ca=function(){void 0!==b&&this.a&&(this.f="Timed out after "+this.o+"ms, aborting",this.h=8,this.dispatchEvent("timeout"),this.abort(8))},y.abort=function(t){this.a&&this.b&&(this.b=!1,this.g=!0,this.a.abort(),this.g=!1,this.h=t||7,this.dispatchEvent("complete"),this.dispatchEvent("abort"),Gn(this))},y.G=function(){this.a&&(this.b&&(this.b=!1,this.g=!0,this.a.abort(),this.g=!1),Gn(this,!0)),Fn.N.G.call(this)},y.Fa=function(){this.j||(this.w||this.l||this.g?Wn(this):this.$a())},y.$a=function(){Wn(this)},y.T=function(){try{return 2<Hn(this)?this.a.status:-1}catch(t){return-1}},y.za=function(){try{return 2<Hn(this)?this.a.statusText:""}catch(t){return""}},y.aa=function(){try{return this.a?this.a.responseText:""}catch(t){return""}},y.Va=function(t){if(this.a){var e=this.a.responseText;return t&&0==e.indexOf(t)&&(e=e.substring(t.length)),qn(e)}},y.ya=function(){return this.h},y.Ya=function(){return E(this.f)?this.f:String(this.f)},(y=Jn.prototype).wa=8,y.u=1,y.Da=function(){return 0==this.u},y.Ia=function(t){if(this.h)if(this.h=null,1==this.u){if(!t){this.P=Math.floor(1e5*Math.random()),t=this.P++;var e,n=new De(this,t,void 0),r=this.i;if(this.J&&(r?$(r=X(r),this.J):r=this.J),null===this.g&&(n.h=r),this.W)t:{for(var i=e=0;i<this.f.length;i++){var o=this.f[i];if(void 0===(o="__data__"in o.a&&E(o=o.a.__data__)?o.length:void 0))break;if(4096<(e+=o)){e=i;break t}if(4096===e||i===this.f.length-1){e=i+1;break t}}e=1e3}else e=1e3;e=ir(this,n,e),Ze(i=He(this.B),"RID",t),Ze(i,"CVER",22),this.o&&this.j&&Ze(i,"X-HTTP-Session-Id",this.j),rr(this,i),this.g&&r&&Xn(i,this.g,r),Rn(this.b,n),this.W?(Ze(i,"$req",e),Ze(i,"SID","null"),n.S=!0,Re(n,i,null)):Re(n,i,e),this.u=2}}else 3==this.u&&(t?nr(this,t):0==this.f.length||Nn(this.b)||nr(this))},y.Ha=function(){this.l=null,this.a=new De(this,"rpc",this.S),null===this.g&&(this.a.h=this.i),this.a.J=0;var t=He(this.pa);Ze(t,"RID","rpc"),Ze(t,"SID",this.H),Ze(t,"CI",this.ia?"0":"1"),Ze(t,"AID",this.O),rr(this,t),Ze(t,"TYPE","xmlhttp"),this.g&&this.i&&Xn(t,this.g,this.i),this.D&&this.a.setTimeout(this.D),Me(this.a,t,!0,this.ga)},y.Ga=function(t,e){if(0!=this.u&&(this.a==t||kn(this.b,t)))if(this.m=t.o,!t.s&&kn(this.b,t)&&3==this.u){try{var n=this.ja.a.parse(e)}catch(t){n=null}if(D(n)&&3==n.length){if(0==(e=n)[0]){t:if(!this.l){if(this.a){if(!(this.a.v+3e3<t.v))break t;ur(this),this.a.cancel(),this.a=null}ar(this),pe(18)}}else this.ra=e[1],0<this.ra-this.O&&e[2]<37500&&this.ia&&0==this.v&&!this.s&&(this.s=me(O(this.Za,this),6e3));if(An(this.b)<=1&&this.fa){try{this.fa()}catch(t){}this.fa=void 0}}else hr(this,11)}else if(!t.s&&this.a!=t||ur(this),!Q(e))for(e=n=this.ja.a.parse(e),n=0;n<e.length;n++){var r=e[n];if(this.O=r[0],r=r[1],2==this.u)if("c"==r[0]){this.H=r[1],this.ga=r[2];var i=r[3];null!=i&&(this.wa=i),null!=(r=r[5])&&S(r)&&0<r&&(this.D=1.5*r),this.o&&(r=t.a)&&((i=Yn(r,"X-Client-Wire-Protocol"))&&Dn(this.b,i),this.j&&(r=Yn(r,"X-HTTP-Session-Id")))&&(this.I=r,Ze(this.B,this.j,r)),this.u=3,this.c&&this.c.va(),r=t,this.pa=fr(this,this.Y()?this.ga:null,this.ha),r.s?(Mn(this.b,r),(i=this.D)&&r.setTimeout(i),r.i&&(qe(r),Le(r)),this.a=r):or(this),0<this.f.length&&er(this)}else"stop"!=r[0]&&"close"!=r[0]||hr(this,7);else 3==this.u&&("stop"==r[0]||"close"==r[0]?"stop"==r[0]?hr(this,7):$n(this):"noop"!=r[0]&&this.c&&this.c.ua(r),this.v=0)}},y.Za=function(){null!=this.s&&(this.s=null,this.a.cancel(),this.a=null,ar(this),pe(19))},y.na=function(t){var e=null;if(this.a==t){ur(this),this.a=null;var n=2}else{if(!kn(this.b,t))return;e=t.j,Mn(this.b,t),n=1}if(this.m=t.o,0!=this.u)if(t.b)1==n?(e=L()-t.v,ce.dispatchEvent(new de(ce,t.l?t.l.length:0,e,this.A)),er(this)):or(this);else{var r=t.c;if(3==r||0==r&&0<this.m||!(1==n&&function(t,e){return!(An(t.b)>=t.b.f-(t.h?1:0))&&(t.h?(t.f=e.j.concat(t.f),!0):!(1==t.u||2==t.u||t.A>=(t.Pa?0:t.Qa))&&(t.h=me(O(t.Ia,t,e),cr(t,t.A)),t.A++,!0))}(this,t)||2==n&&ar(this)))switch(e&&0<e.length&&(t=this.b,t.c=t.c.concat(e)),r){case 1:hr(this,5);break;case 4:hr(this,10);break;case 3:hr(this,6);break;default:hr(this,2)}}},y.fb=function(t){pe(t?2:1)},y.$=function(t){if(t&&!this.R)throw Error("Can't create secondary domain capable XhrIo object.");return(t=new Fn(this.La)).F=this.R,t},y.ma=function(){return!!this.c&&!0},y.Y=function(){return this.R},(y=pr.prototype).va=function(){},y.ua=function(){},y.ta=function(){},y.sa=function(){},y.Ta=function(){},dr.prototype.a=function(t,e){return new mr(t,e)},x(mr,Bt),(y=mr.prototype).addEventListener=function(t,e,n,r){mr.N.addEventListener.call(this,t,e,n,r)},y.removeEventListener=function(t,e,n,r){mr.N.removeEventListener.call(this,t,e,n,r)},y.Wa=function(){this.a.c=this.f,this.l&&(this.a.R=!0);var t=this.a,e=this.m,n=this.g,r=this.b||void 0;pe(0),t.ha=n,t.V=r||{},t.o&&(t.F.b=[],t.F.a=!1),t.w=new vn(t),null===t.g&&(t.w.h=t.i),n=e,t.g&&t.i&&(n=Xn(e,t.g,t.i)),(t=t.w).i=n,e=fr(t.a,null,t.i),pe(3),null!=(n=t.a.F.b)?(t.f=n[0],t.M=1,bn(t)):(tn(e,"MODE","init"),!t.a.o&&t.a.j&&tn(e,"X-HTTP-Session-Id",t.a.j),t.b=new De(t,void 0,void 0),t.b.h=t.h,Me(t.b,e,!1,null),t.M=0)},y.close=function(){$n(this.a)},y.Xa=function(t){if(E(t)){var e={};e.__data__=t,tr(this.a,e)}else this.h?((e={}).__data__=Qt(t),tr(this.a,e)):tr(this.a,t)},y.G=function(){this.a.c=null,delete this.f,$n(this.a),delete this.a,mr.N.G.call(this)},x(yr,Te),x(gr,Ie),x(vr,pr),vr.prototype.va=function(){this.a.dispatchEvent("a")},vr.prototype.ua=function(t){this.a.dispatchEvent(new yr(t))},vr.prototype.ta=function(t){this.a.dispatchEvent(new gr(t))},vr.prototype.sa=function(){this.a.dispatchEvent("b")};var br=P(function(t,e){function n(){}n.prototype=t.prototype;var r=new n;return t.apply(r,Array.prototype.slice.call(arguments,1)),r},dr);dr.prototype.createWebChannel=dr.prototype.a,mr.prototype.send=mr.prototype.Xa,mr.prototype.open=mr.prototype.Wa,mr.prototype.close=mr.prototype.close,ye.NO_ERROR=0,ye.TIMEOUT=8,ye.HTTP_ERROR=6,ge.COMPLETE="complete",(we.EventType=Se).OPEN="a",Se.CLOSE="b",Se.ERROR="c",Se.MESSAGE="d",Bt.prototype.listen=Bt.prototype.Aa,Fn.prototype.listenOnce=Fn.prototype.Ba,Fn.prototype.getLastError=Fn.prototype.Ya,Fn.prototype.getLastErrorCode=Fn.prototype.ya,Fn.prototype.getStatus=Fn.prototype.T,Fn.prototype.getStatusText=Fn.prototype.za,Fn.prototype.getResponseJson=Fn.prototype.Va,Fn.prototype.getResponseText=Fn.prototype.aa,Fn.prototype.send=Fn.prototype.ca;var wr,Er,Sr={createWebChannelTransport:br,ErrorCode:ye,EventType:ge,WebChannel:we,XhrIo:Fn},Tr=Sr.createWebChannelTransport,Ir=Sr.ErrorCode,Cr=Sr.EventType,Dr=Sr.WebChannel,Nr=Sr.XhrIo,Ar=Od.SDK_VERSION,kr=new r("@firebase/firestore");function Rr(){return kr.logLevel===o.DEBUG?wr.DEBUG:kr.logLevel===o.SILENT?wr.SILENT:wr.ERROR}function Mr(t){switch(t){case wr.DEBUG:kr.logLevel=o.DEBUG;break;case wr.ERROR:kr.logLevel=o.ERROR;break;case wr.SILENT:kr.logLevel=o.SILENT;break;default:kr.error("Firestore ("+Ar+"): Invalid value passed to `setLogLevel`")}}function _r(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(kr.logLevel<=o.DEBUG){var i=n.map(Pr);kr.debug.apply(kr,["Firestore ("+Ar+") ["+t+"]: "+e].concat(i))}}function Or(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(kr.logLevel<=o.ERROR){var r=e.map(Pr);kr.error.apply(kr,["Firestore ("+Ar+"): "+t].concat(r))}}function Pr(e){if("string"==typeof e)return e;var t=qr.getPlatform();try{return t.formatJSON(e)}catch(t){return e}}function Lr(t){var e="FIRESTORE ("+Ar+") INTERNAL ASSERTION FAILED: "+t;throw Or(e),new Error(e)}function xr(t,e){t||Lr(e)}(Er=wr=wr||{})[Er.DEBUG=0]="DEBUG",Er[Er.ERROR=1]="ERROR",Er[Er.SILENT=2]="SILENT";var qr=(Fr.setPlatform=function(t){Fr.platform&&Lr("Platform already defined"),Fr.platform=t},Fr.getPlatform=function(){return Fr.platform||Lr("Platform not set"),Fr.platform},Fr);function Fr(){}function Vr(){return qr.getPlatform().emptyByteString}var Br,Ur={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},Qr=(s(Kr,Br=Error),Kr);function Kr(t,e){var n=Br.call(this,e)||this;return n.code=t,n.message=e,n.name="FirebaseError",n.toString=function(){return n.name+": [code="+n.code+"]: "+n.message},n}function jr(t,e){function n(){var t="This constructor is private.";throw e&&(t+=" ",t+=e),new Qr(Ur.INVALID_ARGUMENT,t)}for(var r in n.prototype=t.prototype,t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}function Wr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Gr(t,e){return void 0!==t?t:e}function zr(t,e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var r=Number(n);isNaN(r)||e(r,t[n])}}function Hr(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])}function Yr(t){for(var e in xr(null!=t&&"object"==typeof t,"isEmpty() expects object parameter."),t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function Xr(t,e){if(0!==e.length)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() does not support arguments, but was called with "+pi(e.length,"argument")+".")}function Jr(t,e,n){if(e.length!==n)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires "+pi(n,"argument")+", but was called with "+pi(e.length,"argument")+".")}function $r(t,e,n){if(e.length<n)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires at least "+pi(n,"argument")+", but was called with "+pi(e.length,"argument")+".")}function Zr(t,e,n,r){if(e.length<n||e.length>r)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+pi(e.length,"argument")+".")}function ti(t,e,n,r){ai(t,e,fi(n)+" argument",r)}function ei(t,e,n,r){void 0!==r&&ti(t,e,n,r)}function ni(t,e,n,r){ai(t,e,n+" option",r)}function ri(t,e,n,r){void 0!==r&&ni(t,e,n,r)}function ii(t,e,n,r,i){void 0!==r&&function(t,e,n,r,i){if(!(r instanceof Array))throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires its "+e+" option to be an array, but it was: "+ui(r));for(var o=0;o<r.length;++o)if(!i(r[o]))throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires all "+e+" elements to be "+n+", but the value at index "+o+" was: "+ui(r[o]))}(t,e,n,r,i)}function oi(t,e,n,r,i){void 0!==r&&function(t,e,n,r,i){for(var o=[],a=0,s=i;a<s.length;a++){var u=s[a];if(u===r)return;o.push(ui(u))}var c=ui(r);throw new Qr(Ur.INVALID_ARGUMENT,"Invalid value "+c+" provided to function "+t+'() for option "'+n+'". Acceptable values: '+o.join(", "))}(t,0,n,r,i)}function ai(t,e,n,r){if(!("object"===e?si(r):"non-empty string"===e?"string"==typeof r&&""!==r:typeof r===e)){var i=ui(r);throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires its "+n+" to be of type "+e+", but it was: "+i)}}function si(t){return"object"==typeof t&&null!==t&&(Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))}function ui(t){if(void 0===t)return"undefined";if(null===t)return"null";if("string"==typeof t)return 20<t.length&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"!=typeof t)return"function"==typeof t?"a function":Lr("Unknown wrong type: "+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&&1<e.length)return e[1]}return null}(t);return e?"a custom "+e+" object":"an object"}function ci(t,e,n){if(void 0===n)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+fi(e)+" argument, but it was undefined.")}function hi(n,t,r){Hr(t,function(t,e){if(r.indexOf(t)<0)throw new Qr(Ur.INVALID_ARGUMENT,"Unknown option '"+t+"' passed to function "+n+"(). Available options: "+r.join(", "))})}function li(t,e,n,r){var i=ui(r);return new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires its "+fi(n)+" argument to be a "+e+", but it was: "+i)}function fi(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function pi(t,e){return t+" "+e+(1===t?"":"s")}var di=(mi.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return xr(20===e.length,"Invalid auto ID: "+e),e},mi);function mi(){}function yi(t,e){return t<e?-1:e<t?1:0}function gi(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(!t[n].isEqual(e[n]))return!1;return!0}function vi(t){return t+"\0"}function bi(){if("undefined"==typeof Uint8Array)throw new Qr(Ur.UNIMPLEMENTED,"Uint8Arrays are not available in this environment.")}function wi(){if(!qr.getPlatform().base64Available)throw new Qr(Ur.UNIMPLEMENTED,"Blobs are unavailable in Firestore in this environment.")}var Ei=(Si.fromBase64String=function(t){Jr("Blob.fromBase64String",arguments,1),ti("Blob.fromBase64String","string",1,t),wi();try{return new Si(qr.getPlatform().atob(t))}catch(t){throw new Qr(Ur.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},Si.fromUint8Array=function(t){if(Jr("Blob.fromUint8Array",arguments,1),bi(),!(t instanceof Uint8Array))throw li("Blob.fromUint8Array","Uint8Array",1,t);return new Si(Array.prototype.map.call(t,function(t){return String.fromCharCode(t)}).join(""))},Si.prototype.toBase64=function(){return Jr("Blob.toBase64",arguments,0),wi(),qr.getPlatform().btoa(this._binaryString)},Si.prototype.toUint8Array=function(){Jr("Blob.toUint8Array",arguments,0),bi();for(var t=new Uint8Array(this._binaryString.length),e=0;e<this._binaryString.length;e++)t[e]=this._binaryString.charCodeAt(e);return t},Si.prototype.toString=function(){return"Blob(base64: "+this.toBase64()+")"},Si.prototype.isEqual=function(t){return this._binaryString===t._binaryString},Si.prototype._compareTo=function(t){return yi(this._binaryString,t._binaryString)},Si);function Si(t){wi(),this._binaryString=t}var Ti=jr(Ei,"Use Blob.fromUint8Array() or Blob.fromBase64String() instead."),Ii=function(t,e,n,r,i){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r,this.forceLongPolling=i},Ci="(default)",Di=(Object.defineProperty(Ni.prototype,"isDefaultDatabase",{get:function(){return this.database===Ci},enumerable:!0,configurable:!0}),Ni.prototype.isEqual=function(t){return t instanceof Ni&&t.projectId===this.projectId&&t.database===this.database},Ni.prototype.compareTo=function(t){return yi(this.projectId,t.projectId)||yi(this.database,t.database)},Ni);function Ni(t,e){this.projectId=t,this.database=e||Ci}var Ai=(ki.prototype.setPreviousValue=function(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue},ki.prototype.next=function(){var t=++this.previousValue;return this.writeNewSequenceNumber&&this.writeNewSequenceNumber(t),t},ki.INVALID=-1,ki);function ki(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)})}var Ri="__name__",Mi=(Object.defineProperty(_i.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),_i.prototype.isEqual=function(t){return 0===_i.comparator(this,t)},_i.prototype.child=function(t){var e=this.segments.slice(this.offset,this.limit());return t instanceof _i?t.forEach(function(t){e.push(t)}):e.push(t),this.construct(e)},_i.prototype.limit=function(){return this.offset+this.length},_i.prototype.popFirst=function(t){return t=void 0===t?1:t,xr(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},_i.prototype.popLast=function(){return xr(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},_i.prototype.firstSegment=function(){return xr(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},_i.prototype.lastSegment=function(){return this.get(this.length-1)},_i.prototype.get=function(t){return xr(t<this.length,"Index out of range"),this.segments[this.offset+t]},_i.prototype.isEmpty=function(){return 0===this.length},_i.prototype.isPrefixOf=function(t){if(t.length<this.length)return!1;for(var e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0},_i.prototype.isImmediateParentOf=function(t){if(this.length+1!==t.length)return!1;for(var e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0},_i.prototype.forEach=function(t){for(var e=this.offset,n=this.limit();e<n;e++)t(this.segments[e])},_i.prototype.toArray=function(){return this.segments.slice(this.offset,this.limit())},_i.comparator=function(t,e){for(var n=Math.min(t.length,e.length),r=0;r<n;r++){var i=t.get(r),o=e.get(r);if(i<o)return-1;if(o<i)return 1}return t.length<e.length?-1:t.length>e.length?1:0},_i);function _i(t,e,n){void 0===e?e=0:e>t.length&&Lr("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&Lr("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n}var Oi,Pi=(s(Li,Oi=Mi),Li.prototype.construct=function(t,e,n){return new Li(t,e,n)},Li.prototype.canonicalString=function(){return this.toArray().join("/")},Li.prototype.toString=function(){return this.canonicalString()},Li.fromString=function(t){if(0<=t.indexOf("//"))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new Li(t.split("/").filter(function(t){return 0<t.length}))},Li.EMPTY_PATH=new Li([]),Li);function Li(){return null!==Oi&&Oi.apply(this,arguments)||this}var xi,qi=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Fi=(s(Vi,xi=Mi),Vi.prototype.construct=function(t,e,n){return new Vi(t,e,n)},Vi.isValidIdentifier=function(t){return qi.test(t)},Vi.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),Vi.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},Vi.prototype.toString=function(){return this.canonicalString()},Vi.prototype.isKeyField=function(){return 1===this.length&&this.get(0)===Ri},Vi.keyField=function(){return new Vi([Ri])},Vi.fromServerFormat=function(t){for(var e=[],n="",r=0,i=function(){if(0===n.length)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");e.push(n),n=""},o=!1;r<t.length;){var a=t[r];if("\\"===a){if(r+1===t.length)throw new Qr(Ur.INVALID_ARGUMENT,"Path has trailing escape character: "+t);var s=t[r+1];if("\\"!==s&&"."!==s&&"`"!==s)throw new Qr(Ur.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);n+=s,r+=2}else"`"===a?o=!o:"."!==a||o?n+=a:i(),r++}if(i(),o)throw new Qr(Ur.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new Vi(e)},Vi.EMPTY_PATH=new Vi([]),Vi);function Vi(){return null!==xi&&xi.apply(this,arguments)||this}var Bi=(Ui.prototype.hasCollectionId=function(t){return 2<=this.path.length&&this.path.get(this.path.length-2)===t},Ui.prototype.isEqual=function(t){return null!==t&&0===Pi.comparator(this.path,t.path)},Ui.prototype.toString=function(){return this.path.toString()},Ui.comparator=function(t,e){return Pi.comparator(t.path,e.path)},Ui.isDocumentKey=function(t){return t.length%2==0},Ui.fromSegments=function(t){return new Ui(new Pi(t.slice()))},Ui.fromPathString=function(t){return new Ui(Pi.fromString(t))},Ui.EMPTY=new Ui(new Pi([])),Ui);function Ui(t){this.path=t,xr(Ui.isDocumentKey(t),"Invalid DocumentKey with an odd number of segments: "+t.toArray().join("/"))}var Qi,Ki,ji=function(){var n=this;this.promise=new Promise(function(t,e){n.resolve=t,n.reject=e})};(Ki=Qi=Qi||{}).All="all",Ki.ListenStreamIdle="listen_stream_idle",Ki.ListenStreamConnectionBackoff="listen_stream_connection_backoff",Ki.WriteStreamIdle="write_stream_idle",Ki.WriteStreamConnectionBackoff="write_stream_connection_backoff",Ki.OnlineStateTimeout="online_state_timeout",Ki.ClientMetadataRefresh="client_metadata_refresh",Ki.LruGarbageCollection="lru_garbage_collection",Ki.RetryTransaction="retry_transaction";var Wi=(Gi.createAndSchedule=function(t,e,n,r,i){var o=new Gi(t,e,Date.now()+n,r,i);return o.start(n),o},Gi.prototype.start=function(t){var e=this;this.timerHandle=setTimeout(function(){return e.handleDelayElapsed()},t)},Gi.prototype.skipDelay=function(){return this.handleDelayElapsed()},Gi.prototype.cancel=function(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new Qr(Ur.CANCELLED,"Operation cancelled"+(t?": "+t:""))))},Gi.prototype.handleDelayElapsed=function(){var e=this;this.asyncQueue.enqueueAndForget(function(){return null!==e.timerHandle?(e.clearTimeout(),e.op().then(function(t){return e.deferred.resolve(t)})):Promise.resolve()})},Gi.prototype.clearTimeout=function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)},Gi);function Gi(t,e,n,r,i){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new ji,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){})}var zi=(Object.defineProperty(Hi.prototype,"isShuttingDown",{get:function(){return this._isShuttingDown},enumerable:!0,configurable:!0}),Hi.prototype.enqueueAndForget=function(t){this.enqueue(t)},Hi.prototype.enqueueAndForgetEvenAfterShutdown=function(t){this.verifyNotFailed(),this.enqueueInternal(t)},Hi.prototype.enqueueEvenAfterShutdown=function(t){return this.verifyNotFailed(),this.enqueueInternal(t)},Hi.prototype.enqueueAndInitiateShutdown=function(e){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.verifyNotFailed(),this._isShuttingDown?[3,2]:(this._isShuttingDown=!0,[4,this.enqueueEvenAfterShutdown(e)]);case 1:t.sent(),t.label=2;case 2:return[2]}})})},Hi.prototype.enqueue=function(t){return this.verifyNotFailed(),this._isShuttingDown?new Promise(function(t){}):this.enqueueInternal(t)},Hi.prototype.enqueueInternal=function(t){var n=this,e=this.tail.then(function(){return n.operationInProgress=!0,t().catch(function(t){n.failure=t,n.operationInProgress=!1;var e=t.stack||t.message||"";throw Or("INTERNAL UNHANDLED ERROR: ",e),e.indexOf("Firestore Test Simulated Error")<0&&setTimeout(function(){throw t},0),t}).then(function(t){return n.operationInProgress=!1,t})});return this.tail=e},Hi.prototype.enqueueAfterDelay=function(t,e,n){var r=this;this.verifyNotFailed(),xr(0<=e,"Attempted to schedule an operation with a negative delay of "+e),-1<this.timerIdsToSkip.indexOf(t)&&(e=0);var i=Wi.createAndSchedule(this,t,e,n,function(t){return r.removeDelayedOperation(t)});return this.delayedOperations.push(i),i},Hi.prototype.verifyNotFailed=function(){this.failure&&Lr("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},Hi.prototype.verifyOperationInProgress=function(){xr(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},Hi.prototype.drain=function(){return this.enqueueEvenAfterShutdown(function(){return Promise.resolve()})},Hi.prototype.containsDelayedOperation=function(t){for(var e=0,n=this.delayedOperations;e<n.length;e++)if(n[e].timerId===t)return!0;return!1},Hi.prototype.runDelayedOperationsEarly=function(r){var i=this;return this.drain().then(function(){xr(r===Qi.All||i.containsDelayedOperation(r),"Attempted to drain to missing operation "+r),i.delayedOperations.sort(function(t,e){return t.targetTimeMs-e.targetTimeMs});for(var t=0,e=i.delayedOperations;t<e.length;t++){var n=e[t];if(n.skipDelay(),r!==Qi.All&&n.timerId===r)break}return i.drain()})},Hi.prototype.skipDelaysForTimerId=function(t){this.timerIdsToSkip.push(t)},Hi.prototype.removeDelayedOperation=function(t){var e=this.delayedOperations.indexOf(t);xr(0<=e,"Delayed operation not found."),this.delayedOperations.splice(e,1)},Hi);function Hi(){this.tail=Promise.resolve(),this._isShuttingDown=!1,this.delayedOperations=[],this.failure=null,this.operationInProgress=!1,this.timerIdsToSkip=[]}var Yi="",Xi="",Ji="",$i="";function Zi(t){for(var e="",n=0;n<t.length;n++)0<e.length&&(e=eo(e)),e=to(t.get(n),e);return eo(e)}function to(t,e){for(var n=e,r=t.length,i=0;i<r;i++){var o=t.charAt(i);switch(o){case"\0":n+=Yi+Ji;break;case Yi:n+=Yi+$i;break;default:n+=o}}return n}function eo(t){return t+Yi+Xi}function no(t){var e=t.length;if(xr(2<=e,"Invalid path "+t),2===e)return xr(t.charAt(0)===Yi&&t.charAt(1)===Xi,"Non-empty path "+t+" had length 2"),Pi.EMPTY_PATH;for(var n=e-2,r=[],i="",o=0;o<e;){var a=t.indexOf(Yi,o);switch((a<0||n<a)&&Lr('Invalid encoded resource path: "'+t+'"'),t.charAt(a+1)){case Xi:var s=t.substring(o,a),u=void 0;0===i.length?u=s:(u=i+=s,i=""),r.push(u);break;case Ji:i+=t.substring(o,a),i+="\0";break;case $i:i+=t.substring(o,a+1);break;default:Lr('Invalid encoded resource path: "'+t+'"')}o=a+2}return new Pi(r)}var ro=(io.now=function(){return io.fromMillis(Date.now())},io.fromDate=function(t){return io.fromMillis(t.getTime())},io.fromMillis=function(t){var e=Math.floor(t/1e3);return new io(e,1e6*(t-1e3*e))},io.prototype.toDate=function(){return new Date(this.toMillis())},io.prototype.toMillis=function(){return 1e3*this.seconds+this.nanoseconds/1e6},io.prototype._compareTo=function(t){return this.seconds===t.seconds?yi(this.nanoseconds,t.nanoseconds):yi(this.seconds,t.seconds)},io.prototype.isEqual=function(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds},io.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"},io);function io(t,e){if(this.seconds=t,(this.nanoseconds=e)<0)throw new Qr(Ur.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(1e9<=e)throw new Qr(Ur.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new Qr(Ur.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(253402300800<=t)throw new Qr(Ur.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}var oo=(ao.fromMicroseconds=function(t){var e=Math.floor(t/1e6);return new ao(new ro(e,t%1e6*1e3))},ao.fromTimestamp=function(t){return new ao(t)},ao.forDeletedDoc=function(){return ao.MIN},ao.prototype.compareTo=function(t){return this.timestamp._compareTo(t.timestamp)},ao.prototype.isEqual=function(t){return this.timestamp.isEqual(t.timestamp)},ao.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3},ao.prototype.toString=function(){return"SnapshotVersion("+this.timestamp.toString()+")"},ao.prototype.toTimestamp=function(){return this.timestamp},ao.MIN=new ao(new ro(0,0)),ao);function ao(t){this.timestamp=t}var so=(uo.prototype.insert=function(t,e){return new uo(this.comparator,this.root.insert(t,e,this.comparator).copy(null,null,lo.BLACK,null,null))},uo.prototype.remove=function(t){return new uo(this.comparator,this.root.remove(t,this.comparator).copy(null,null,lo.BLACK,null,null))},uo.prototype.get=function(t){for(var e=this.root;!e.isEmpty();){var n=this.comparator(t,e.key);if(0===n)return e.value;n<0?e=e.left:0<n&&(e=e.right)}return null},uo.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;n=r<0?n.left:(e+=n.left.size+1,n.right)}return-1},uo.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(uo.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),uo.prototype.minKey=function(){return this.root.minKey()},uo.prototype.maxKey=function(){return this.root.maxKey()},uo.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},uo.prototype.forEach=function(n){this.inorderTraversal(function(t,e){return n(t,e),!1})},uo.prototype.toString=function(){var n=[];return this.inorderTraversal(function(t,e){return n.push(t+":"+e),!1}),"{"+n.join(", ")+"}"},uo.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},uo.prototype.getIterator=function(){return new co(this.root,null,this.comparator,!1)},uo.prototype.getIteratorFrom=function(t){return new co(this.root,t,this.comparator,!1)},uo.prototype.getReverseIterator=function(){return new co(this.root,null,this.comparator,!0)},uo.prototype.getReverseIteratorFrom=function(t){return new co(this.root,t,this.comparator,!0)},uo);function uo(t,e){this.comparator=t,this.root=e||lo.EMPTY}var co=(ho.prototype.getNext=function(){xr(0<this.nodeStack.length,"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},ho.prototype.hasNext=function(){return 0<this.nodeStack.length},ho.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}},ho);function ho(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}}var lo=(fo.prototype.copy=function(t,e,n,r,i){return new fo(null!=t?t:this.key,null!=e?e:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)},fo.prototype.isEmpty=function(){return!1},fo.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},fo.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},fo.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},fo.prototype.minKey=function(){return this.min().key},fo.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},fo.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()},fo.prototype.removeMin=function(){if(this.left.isEmpty())return fo.EMPTY;var t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),(t=t.copy(null,null,null,t.left.removeMin(),null)).fixUp()},fo.prototype.remove=function(t,e){var n,r=this;if(e(t,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(t,e),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===e(t,r.key)){if(r.right.isEmpty())return fo.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(t,e))}return r.fixUp()},fo.prototype.isRed=function(){return this.color},fo.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},fo.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},fo.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=(t=t.rotateRight()).colorFlip()),t},fo.prototype.rotateLeft=function(){var t=this.copy(null,null,fo.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)},fo.prototype.rotateRight=function(){var t=this.copy(null,null,fo.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)},fo.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)},fo.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},fo.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw Lr("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw Lr("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw Lr("Black depths differ");return t+(this.isRed()?0:1)},fo.EMPTY=null,fo.RED=!0,fo.BLACK=!1,fo);function fo(t,e,n,r,i){this.key=t,this.value=e,this.color=null!=n?n:fo.RED,this.left=null!=r?r:fo.EMPTY,this.right=null!=i?i:fo.EMPTY,this.size=this.left.size+1+this.right.size}var po=(Object.defineProperty(mo.prototype,"key",{get:function(){throw Lr("LLRBEmptyNode has no key.")},enumerable:!0,configurable:!0}),Object.defineProperty(mo.prototype,"value",{get:function(){throw Lr("LLRBEmptyNode has no value.")},enumerable:!0,configurable:!0}),Object.defineProperty(mo.prototype,"color",{get:function(){throw Lr("LLRBEmptyNode has no color.")},enumerable:!0,configurable:!0}),Object.defineProperty(mo.prototype,"left",{get:function(){throw Lr("LLRBEmptyNode has no left child.")},enumerable:!0,configurable:!0}),Object.defineProperty(mo.prototype,"right",{get:function(){throw Lr("LLRBEmptyNode has no right child.")},enumerable:!0,configurable:!0}),mo.prototype.copy=function(t,e,n,r,i){return this},mo.prototype.insert=function(t,e,n){return new lo(t,e)},mo.prototype.remove=function(t,e){return this},mo.prototype.isEmpty=function(){return!0},mo.prototype.inorderTraversal=function(t){return!1},mo.prototype.reverseTraversal=function(t){return!1},mo.prototype.minKey=function(){return null},mo.prototype.maxKey=function(){return null},mo.prototype.isRed=function(){return!1},mo.prototype.checkMaxDepth=function(){return!0},mo.prototype.check=function(){return 0},mo);function mo(){this.size=0}lo.EMPTY=new po;var yo=(go.fromMapKeys=function(t){var e=new go(t.comparator);return t.forEach(function(t){e=e.add(t)}),e},go.prototype.has=function(t){return null!==this.data.get(t)},go.prototype.first=function(){return this.data.minKey()},go.prototype.last=function(){return this.data.maxKey()},Object.defineProperty(go.prototype,"size",{get:function(){return this.data.size},enumerable:!0,configurable:!0}),go.prototype.indexOf=function(t){return this.data.indexOf(t)},go.prototype.forEach=function(n){this.data.inorderTraversal(function(t,e){return n(t),!1})},go.prototype.forEachInRange=function(t,e){for(var n=this.data.getIteratorFrom(t[0]);n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,t[1]))return;e(r.key)}},go.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},go.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},go.prototype.getIterator=function(){return new vo(this.data.getIterator())},go.prototype.getIteratorFrom=function(t){return new vo(this.data.getIteratorFrom(t))},go.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},go.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},go.prototype.isEmpty=function(){return this.data.isEmpty()},go.prototype.unionWith=function(t){var e=this;return t.forEach(function(t){e=e.add(t)}),e},go.prototype.isEqual=function(t){if(!(t instanceof go))return!1;if(this.size!==t.size)return!1;for(var e=this.data.getIterator(),n=t.data.getIterator();e.hasNext();){var r=e.getNext().key,i=n.getNext().key;if(0!==this.comparator(r,i))return!1}return!0},go.prototype.toArray=function(){var e=[];return this.forEach(function(t){e.push(t)}),e},go.prototype.toString=function(){var e=[];return this.forEach(function(t){return e.push(t)}),"SortedSet("+e.toString()+")"},go.prototype.copy=function(t){var e=new go(this.comparator);return e.data=t,e},go);function go(t){this.comparator=t,this.data=new so(this.comparator)}var vo=(bo.prototype.getNext=function(){return this.iter.getNext().key},bo.prototype.hasNext=function(){return this.iter.hasNext()},bo);function bo(t){this.iter=t}var wo=new so(Bi.comparator);function Eo(){return wo}function So(){return Eo()}var To=new so(Bi.comparator);function Io(){return To}var Co=new so(Bi.comparator);function Do(){return Co}var No=new yo(Bi.comparator);function Ao(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];for(var n=No,r=0,i=t;r<i.length;r++){var o=i[r];n=n.add(o)}return n}var ko=new yo(yi);function Ro(){return ko}var Mo=(_o.prototype.applyToRemoteDocument=function(t,e,n){e&&xr(e.key.isEqual(t),"applyToRemoteDocument: key "+t+" should match maybeDoc key\n "+e.key);var r=n.mutationResults;xr(r.length===this.mutations.length,"Mismatch between mutations length\n ("+this.mutations.length+") and mutation results length\n ("+r.length+").");for(var i=0;i<this.mutations.length;i++){var o=this.mutations[i];if(o.key.isEqual(t)){var a=r[i];e=o.applyToRemoteDocument(e,a)}}return e},_o.prototype.applyToLocalView=function(t,e){e&&xr(e.key.isEqual(t),"applyToLocalDocument: key "+t+" should match maybeDoc key\n "+e.key);for(var n=0,r=this.baseMutations;n<r.length;n++)(s=r[n]).key.isEqual(t)&&(e=s.applyToLocalView(e,e,this.localWriteTime));for(var i=e,o=0,a=this.mutations;o<a.length;o++){var s;(s=a[o]).key.isEqual(t)&&(e=s.applyToLocalView(e,i,this.localWriteTime))}return e},_o.prototype.applyToLocalDocumentSet=function(n){var r=this,i=n;return this.mutations.forEach(function(t){var e=r.applyToLocalView(t.key,n.get(t.key));e&&(i=i.insert(t.key,e))}),i},_o.prototype.keys=function(){return this.mutations.reduce(function(t,e){return t.add(e.key)},Ao())},_o.prototype.isEqual=function(t){return this.batchId===t.batchId&&gi(this.mutations,t.mutations)&&gi(this.baseMutations,t.baseMutations)},_o);function _o(t,e,n,r){this.batchId=t,this.localWriteTime=e,this.baseMutations=n,xr(0<(this.mutations=r).length,"Cannot create an empty mutation batch")}var Oo=(Po.from=function(t,e,n,r){xr(t.mutations.length===n.length,"Mutations sent "+t.mutations.length+" must equal results received "+n.length);for(var i=Do(),o=t.mutations,a=0;a<o.length;a++)i=i.insert(o[a].key,n[a].version);return new Po(t,e,n,r,i)},Po);function Po(t,e,n,r,i){this.batch=t,this.commitVersion=e,this.mutationResults=n,this.streamToken=r,this.docVersions=i}var Lo=(xo.prototype.catch=function(t){return this.next(void 0,t)},xo.prototype.next=function(r,i){var o=this;return this.callbackAttached&&Lr("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new xo(function(e,n){o.nextCallback=function(t){o.wrapSuccess(r,t).next(e,n)},o.catchCallback=function(t){o.wrapFailure(i,t).next(e,n)}})},xo.prototype.toPromise=function(){var n=this;return new Promise(function(t,e){n.next(t,e)})},xo.prototype.wrapUserFunction=function(t){try{var e=t();return e instanceof xo?e:xo.resolve(e)}catch(t){return xo.reject(t)}},xo.prototype.wrapSuccess=function(t,e){return t?this.wrapUserFunction(function(){return t(e)}):xo.resolve(e)},xo.prototype.wrapFailure=function(t,e){return t?this.wrapUserFunction(function(){return t(e)}):xo.reject(e)},xo.resolve=function(n){return new xo(function(t,e){t(n)})},xo.reject=function(n){return new xo(function(t,e){e(n)})},xo.waitFor=function(t){return new xo(function(e,n){var r=0,i=0,o=!1;t.forEach(function(t){++r,t.next(function(){++i,o&&i===r&&e()},function(t){return n(t)})}),o=!0,i===r&&e()})},xo.or=function(t){for(var n=xo.resolve(!1),e=function(e){n=n.next(function(t){return t?xo.resolve(t):e()})},r=0,i=t;r<i.length;r++)e(i[r]);return n},xo.forEach=function(t,n){var r=this,i=[];return t.forEach(function(t,e){i.push(n.call(r,t,e))}),this.waitFor(i)},xo);function xo(t){var e=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t(function(t){e.isDone=!0,e.result=t,e.nextCallback&&e.nextCallback(t)},function(t){e.isDone=!0,e.error=t,e.catchCallback&&e.catchCallback(t)})}var qo=(Fo.forUser=function(t,e,n,r){return xr(""!==t.uid,"UserID must not be an empty string."),new Fo(t.isAuthenticated()?t.uid:"",e,n,r)},Fo.prototype.checkEmpty=function(t){var r=!0,e=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Qo(t).iterate({index:pu.userMutationsIndex,range:e},function(t,e,n){r=!1,n.done()}).next(function(){return r})},Fo.prototype.acknowledgeBatch=function(e,t,n){return this.getMutationQueueMetadata(e).next(function(t){return t.lastStreamToken=Uo(n),jo(e).put(t)})},Fo.prototype.getLastStreamToken=function(t){return this.getMutationQueueMetadata(t).next(function(t){return t.lastStreamToken})},Fo.prototype.setLastStreamToken=function(e,n){return this.getMutationQueueMetadata(e).next(function(t){return t.lastStreamToken=Uo(n),jo(e).put(t)})},Fo.prototype.addMutationBatch=function(u,c,h,l){var f=this,p=Ko(u),d=Qo(u);return d.add({}).next(function(t){xr("number"==typeof t,"Auto-generated key is not a number");var e=new Mo(t,c,h,l),n=f.serializer.toDbMutationBatch(f.userId,e);f.documentKeysByBatchId[t]=e.keys();for(var r=[],i=0,o=l;i<o.length;i++){var a=o[i],s=mu.key(f.userId,a.key.path,t);r.push(d.put(n)),r.push(p.put(s,mu.PLACEHOLDER)),r.push(f.indexManager.addToCollectionParentIndex(u,a.key.path.popLast()))}return Lo.waitFor(r).next(function(){return e})})},Fo.prototype.lookupMutationBatch=function(t,e){var n=this;return Qo(t).get(e).next(function(t){return t?(xr(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),n.serializer.fromDbMutationBatch(t)):null})},Fo.prototype.lookupMutationKeys=function(t,n){var r=this;return this.documentKeysByBatchId[n]?Lo.resolve(this.documentKeysByBatchId[n]):this.lookupMutationBatch(t,n).next(function(t){if(t){var e=t.keys();return r.documentKeysByBatchId[n]=e}return null})},Fo.prototype.getNextMutationBatchAfterBatchId=function(t,e){var r=this,i=e+1,n=IDBKeyRange.lowerBound([this.userId,i]),o=null;return Qo(t).iterate({index:pu.userMutationsIndex,range:n},function(t,e,n){e.userId===r.userId&&(xr(e.batchId>=i,"Should have found mutation after "+i),o=r.serializer.fromDbMutationBatch(e)),n.done()}).next(function(){return o})},Fo.prototype.getHighestUnacknowledgedBatchId=function(t){var e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),r=-1;return Qo(t).iterate({index:pu.userMutationsIndex,range:e,reverse:!0},function(t,e,n){r=e.batchId,n.done()}).next(function(){return r})},Fo.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Qo(t).loadAll(pu.userMutationsIndex,n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},Fo.prototype.getAllMutationBatchesAffectingDocumentKey=function(s,u){var c=this,t=mu.prefixForPath(this.userId,u.path),e=IDBKeyRange.lowerBound(t),h=[];return Ko(s).iterate({range:e},function(e,t,n){var r=e[0],i=e[1],o=e[2],a=no(i);if(r===c.userId&&u.path.isEqual(a))return Qo(s).get(o).next(function(t){if(!t)throw Lr("Dangling document-mutation reference found: "+e+" which points to "+o);xr(t.userId===c.userId,"Unexpected user '"+t.userId+"' for mutation batch "+o),h.push(c.serializer.fromDbMutationBatch(t))});n.done()}).next(function(){return h})},Fo.prototype.getAllMutationBatchesAffectingDocumentKeys=function(r,t){var u=this,c=new yo(yi),i=[];return t.forEach(function(s){var t=mu.prefixForPath(u.userId,s.path),e=IDBKeyRange.lowerBound(t),n=Ko(r).iterate({range:e},function(t,e,n){var r=t[0],i=t[1],o=t[2],a=no(i);r===u.userId&&s.path.isEqual(a)?c=c.add(o):n.done()});i.push(n)}),Lo.waitFor(i).next(function(){return u.lookupMutationBatches(r,c)})},Fo.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var s=this;xr(!e.isDocumentQuery(),"Document queries shouldn't go down this path"),xr(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var u=e.path,c=u.length+1,n=mu.prefixForPath(this.userId,u),r=IDBKeyRange.lowerBound(n),h=new yo(yi);return Ko(t).iterate({range:r},function(t,e,n){var r=t[0],i=t[1],o=t[2],a=no(i);r===s.userId&&u.isPrefixOf(a)?a.length===c&&(h=h.add(o)):n.done()}).next(function(){return s.lookupMutationBatches(t,h)})},Fo.prototype.lookupMutationBatches=function(t,e){var n=this,r=[],i=[];return e.forEach(function(e){i.push(Qo(t).get(e).next(function(t){if(null===t)throw Lr("Dangling document-mutation reference found, which points to "+e);xr(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),r.push(n.serializer.fromDbMutationBatch(t))}))}),Lo.waitFor(i).next(function(){return r})},Fo.prototype.removeMutationBatch=function(e,n){var r=this;return Bo(e.simpleDbTransaction,this.userId,n).next(function(t){return r.removeCachedMutationKeys(n.batchId),Lo.forEach(t,function(t){return r.referenceDelegate.removeMutationReference(e,t)})})},Fo.prototype.removeCachedMutationKeys=function(t){delete this.documentKeysByBatchId[t]},Fo.prototype.performConsistencyCheck=function(n){var o=this;return this.checkEmpty(n).next(function(t){if(!t)return Lo.resolve();var e=IDBKeyRange.lowerBound(mu.prefixForUser(o.userId)),i=[];return Ko(n).iterate({range:e},function(t,e,n){if(t[0]===o.userId){var r=no(t[1]);i.push(r)}else n.done()}).next(function(){xr(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map(function(t){return t.canonicalString()}))})})},Fo.prototype.containsKey=function(t,e){return Vo(t,this.userId,e)},Fo.prototype.getMutationQueueMetadata=function(t){var e=this;return jo(t).get(this.userId).next(function(t){return t||new lu(e.userId,-1,"")})},Fo);function Fo(t,e,n,r){this.userId=t,this.serializer=e,this.indexManager=n,this.referenceDelegate=r,this.documentKeysByBatchId={}}function Vo(t,o,e){var n=mu.prefixForPath(o,e.path),a=n[1],r=IDBKeyRange.lowerBound(n),s=!1;return Ko(t).iterate({range:r,keysOnly:!0},function(t,e,n){var r=t[0],i=t[1];t[2];r===o&&i===a&&(s=!0),n.done()}).next(function(){return s})}function Bo(t,e,n){var r=t.store(pu.store),i=t.store(mu.store),o=[],a=IDBKeyRange.only(n.batchId),s=0,u=r.iterate({range:a},function(t,e,n){return s++,n.delete()});o.push(u.next(function(){xr(1===s,"Dangling document-mutation reference found: Missing batch "+n.batchId)}));for(var c=[],h=0,l=n.mutations;h<l.length;h++){var f=l[h],p=mu.key(e,f.key.path,n.batchId);o.push(i.delete(p)),c.push(f.key)}return Lo.waitFor(o).next(function(){return c})}function Uo(t){return t instanceof Uint8Array?(xr("YES"===process.env.USE_MOCK_PERSISTENCE,"Persisting non-string stream tokens is only supported with mock persistence."),t.toString()):t}function Qo(t){return uc.getStore(t,pu.store)}function Ko(t){return uc.getStore(t,mu.store)}function jo(t){return uc.getStore(t,lu.store)}var Wo,Go;(Go=Wo=Wo||{})[Go.QueryCache=0]="QueryCache",Go[Go.SyncEngine=1]="SyncEngine";var zo=(Ho.prototype.next=function(){var t=this.nextId;return this.nextId+=2,t},Ho.prototype.after=function(t){return this.seek(t+2),this.next()},Ho.prototype.seek=function(t){xr((1&t)===this.generatorId,"Cannot supply target ID from different generator ID"),this.nextId=t},Ho.forQueryCache=function(){return new Ho(Wo.QueryCache,2)},Ho.forSyncEngine=function(){return new Ho(Wo.SyncEngine)},Ho);function Ho(t,e){xr((1&(this.generatorId=t))===t,"Generator ID "+t+" contains more than 1 reserved bits"),this.seek(void 0!==e?e:this.generatorId)}var Yo="SimpleDb",Xo=(Jo.openOrCreate=function(o,t,a){return xr(Jo.isAvailable(),"IndexedDB not supported in current environment."),_r(Yo,"Opening database:",o),new Lo(function(n,r){var i=window.indexedDB.open(o,t);i.onsuccess=function(t){var e=t.target.result;n(new Jo(e))},i.onblocked=function(){r(new Qr(Ur.FAILED_PRECONDITION,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=function(t){var e=t.target.error;"VersionError"===e.name?r(new Qr(Ur.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):r(e)},i.onupgradeneeded=function(t){_r(Yo,'Database "'+o+'" requires upgrade from version:',t.oldVersion);var e=t.target.result,n=new ta(i.transaction);a.createOrUpgrade(e,n,t.oldVersion,ou).next(function(){_r(Yo,"Database upgrade to version "+ou+" complete")})}}).toPromise()},Jo.delete=function(t){return _r(Yo,"Removing database:",t),ia(window.indexedDB.deleteDatabase(t)).toPromise()},Jo.isAvailable=function(){if("undefined"==typeof window||null==window.indexedDB)return!1;if(void 0===window.navigator)return"YES"===process.env.USE_MOCK_PERSISTENCE;var t=u(),e=Jo.getIOSVersion(t),n=0<e&&e<10,r=Jo.getAndroidVersion(t),i=0<r&&r<4.5;return!(0<t.indexOf("MSIE ")||0<t.indexOf("Trident/")||0<t.indexOf("Edge/")||n||i)},Jo.getStore=function(t,e){return t.store(e)},Jo.getIOSVersion=function(t){var e=t.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=e?e[1].split("_").slice(0,2).join("."):"-1";return Number(n)},Jo.getAndroidVersion=function(t){var e=t.match(/Android ([\d.]+)/i),n=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(n)},Jo.prototype.setVersionChangeListener=function(e){this.db.onversionchange=function(t){return e(t)}},Jo.prototype.runTransaction=function(t,e,n){var r=ta.open(this.db,t,e),i=n(r).catch(function(t){return r.abort(t),Lo.reject(t)}).toPromise();return i.catch(function(){}),r.completionPromise.then(function(){return i})},Jo.prototype.close=function(){this.db.close()},Jo);function Jo(t){this.db=t,12.2===Jo.getIOSVersion(u())&&Or("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}var $o=(Object.defineProperty(Zo.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(Zo.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(Zo.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),Zo.prototype.done=function(){this.shouldStop=!0},Zo.prototype.skip=function(t){this.nextKey=t},Zo.prototype.delete=function(){return ia(this.dbCursor.delete())},Zo);function Zo(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}var ta=(ea.open=function(t,e,n){return new ea(t.transaction(n,e))},Object.defineProperty(ea.prototype,"completionPromise",{get:function(){return this.completionDeferred.promise},enumerable:!0,configurable:!0}),ea.prototype.abort=function(t){t&&this.completionDeferred.reject(t),this.aborted||(_r(Yo,"Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())},ea.prototype.store=function(t){var e=this.transaction.objectStore(t);return xr(!!e,"Object store not part of transaction: "+t),new na(e)},ea);function ea(t){var n=this;this.transaction=t,this.aborted=!1,this.completionDeferred=new ji,this.transaction.oncomplete=function(){n.completionDeferred.resolve()},this.transaction.onabort=function(){t.error?n.completionDeferred.reject(t.error):n.completionDeferred.resolve()},this.transaction.onerror=function(t){var e=aa(t.target.error);n.completionDeferred.reject(e)}}var na=(ra.prototype.put=function(t,e){return ia(void 0!==e?(_r(Yo,"PUT",this.store.name,t,e),this.store.put(e,t)):(_r(Yo,"PUT",this.store.name,"<auto-key>",t),this.store.put(t)))},ra.prototype.add=function(t){return _r(Yo,"ADD",this.store.name,t,t),ia(this.store.add(t))},ra.prototype.get=function(e){var n=this;return ia(this.store.get(e)).next(function(t){return void 0===t&&(t=null),_r(Yo,"GET",n.store.name,e,t),t})},ra.prototype.delete=function(t){return _r(Yo,"DELETE",this.store.name,t),ia(this.store.delete(t))},ra.prototype.count=function(){return _r(Yo,"COUNT",this.store.name),ia(this.store.count())},ra.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})},ra.prototype.deleteAll=function(t,e){_r(Yo,"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()})},ra.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},ra.prototype.iterateSerial=function(i){var t=this.cursor({});return new Lo(function(n,r){t.onerror=function(t){var e=aa(t.target.error);r(e)},t.onsuccess=function(t){var e=t.target.result;e?i(e.primaryKey,e.value).next(function(t){t?e.continue():n()}):n()}})},ra.prototype.iterateCursor=function(t,a){var s=[];return new Lo(function(o,e){t.onerror=function(t){e(t.target.error)},t.onsuccess=function(t){var e=t.target.result;if(e){var n=new $o(e),r=a(e.primaryKey,e.value,n);if(r instanceof Lo){var i=r.catch(function(t){return n.done(),Lo.reject(t)});s.push(i)}n.isDone?o():null===n.skipToKey?e.continue():e.continue(n.skipToKey)}else o()}}).next(function(){return Lo.waitFor(s)})},ra.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(xr(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},ra.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)},ra);function ra(t){this.store=t}function ia(t){return new Lo(function(n,r){t.onsuccess=function(t){var e=t.target.result;n(e)},t.onerror=function(t){var e=aa(t.target.error);r(e)}})}var oa=!1;function aa(t){var e=Xo.getIOSVersion(u());if(12.2<=e&&e<13){var n="An internal error was encountered in the Indexed Database server";if(0<=t.message.indexOf(n)){var r=new Qr("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '"+n+"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");return oa||(oa=!0,setTimeout(function(){throw r},0)),r}}return t}var sa=(ua.prototype.allocateTargetId=function(e){var n=this;return this.retrieveMetadata(e).next(function(t){return t.highestTargetId=n.targetIdGenerator.after(t.highestTargetId),n.saveMetadata(e,t).next(function(){return t.highestTargetId})})},ua.prototype.getLastRemoteSnapshotVersion=function(t){return this.retrieveMetadata(t).next(function(t){return oo.fromTimestamp(new ro(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds))})},ua.prototype.getHighestSequenceNumber=function(t){return la(t.simpleDbTransaction)},ua.prototype.setTargetsMetadata=function(e,n,r){var i=this;return this.retrieveMetadata(e).next(function(t){return t.highestListenSequenceNumber=n,r&&(t.lastRemoteSnapshotVersion=r.toTimestamp()),n>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=n),i.saveMetadata(e,t)})},ua.prototype.addQueryData=function(e,n){var r=this;return this.saveQueryData(e,n).next(function(){return r.retrieveMetadata(e).next(function(t){return t.targetCount+=1,r.updateMetadataFromQueryData(n,t),r.saveMetadata(e,t)})})},ua.prototype.updateQueryData=function(t,e){return this.saveQueryData(t,e)},ua.prototype.removeQueryData=function(e,t){var n=this;return this.removeMatchingKeysForTargetId(e,t.targetId).next(function(){return ca(e).delete(t.targetId)}).next(function(){return n.retrieveMetadata(e)}).next(function(t){return xr(0<t.targetCount,"Removing from an empty query cache"),t.targetCount-=1,n.saveMetadata(e,t)})},ua.prototype.removeTargets=function(r,i,o){var a=this,s=0,u=[];return ca(r).iterate(function(t,e){var n=a.serializer.fromDbTarget(e);n.sequenceNumber<=i&&void 0===o[n.targetId]&&(s++,u.push(a.removeQueryData(r,n)))}).next(function(){return Lo.waitFor(u)}).next(function(){return s})},ua.prototype.forEachTarget=function(t,r){var i=this;return ca(t).iterate(function(t,e){var n=i.serializer.fromDbTarget(e);r(n)})},ua.prototype.retrieveMetadata=function(t){return ha(t.simpleDbTransaction)},ua.prototype.saveMetadata=function(t,e){return function(t){return uc.getStore(t,Nu.store)}(t).put(Nu.key,e)},ua.prototype.saveQueryData=function(t,e){return ca(t).put(this.serializer.toDbTarget(e))},ua.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},ua.prototype.getQueryCount=function(t){return this.retrieveMetadata(t).next(function(t){return t.targetCount})},ua.prototype.getQueryData=function(t,i){var o=this,e=i.canonicalId(),n=IDBKeyRange.bound([e,Number.NEGATIVE_INFINITY],[e,Number.POSITIVE_INFINITY]),a=null;return ca(t).iterate({range:n,index:Tu.queryTargetsIndexName},function(t,e,n){var r=o.serializer.fromDbTarget(e);i.isEqual(r.query)&&(a=r,n.done())}).next(function(){return a})},ua.prototype.addMatchingKeys=function(n,t,r){var i=this,o=[],a=fa(n);return t.forEach(function(t){var e=Zi(t.path);o.push(a.put(new Cu(r,e))),o.push(i.referenceDelegate.addReference(n,t))}),Lo.waitFor(o)},ua.prototype.removeMatchingKeys=function(n,t,r){var i=this,o=fa(n);return Lo.forEach(t,function(t){var e=Zi(t.path);return Lo.waitFor([o.delete([r,e]),i.referenceDelegate.removeReference(n,t)])})},ua.prototype.removeMatchingKeysForTargetId=function(t,e){var n=fa(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)},ua.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=fa(t),o=Ao();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=no(t[1]),i=new Bi(r);o=o.add(i)}).next(function(){return o})},ua.prototype.containsKey=function(t,e){var n=Zi(e.path),r=IDBKeyRange.bound([n],[vi(n)],!1,!0),i=0;return fa(t).iterate({index:Cu.documentTargetsIndex,keysOnly:!0,range:r},function(t,e,n){var r=t[0];t[1],0!==r&&(i++,n.done())}).next(function(){return 0<i})},ua.prototype.getQueryDataForTarget=function(t,e){var n=this;return ca(t).get(e).next(function(t){return t?n.serializer.fromDbTarget(t):null})},ua);function ua(t,e){this.referenceDelegate=t,this.serializer=e,this.targetIdGenerator=zo.forQueryCache()}function ca(t){return uc.getStore(t,Tu.store)}function ha(t){return Xo.getStore(t,Nu.store).get(Nu.key).next(function(t){return xr(null!==t,"Missing metadata row."),t})}function la(t){return ha(t).next(function(t){return t.highestListenSequenceNumber})}function fa(t){return uc.getStore(t,Cu.store)}var pa=(da.fromSet=function(t){return new da(t)},da.fromArray=function(t){var e=new yo(Fi.comparator);return t.forEach(function(t){return e=e.add(t)}),new da(e)},da.prototype.covers=function(e){var n=!1;return this.fields.forEach(function(t){t.isPrefixOf(e)&&(n=!0)}),n},da.prototype.isEqual=function(t){return this.fields.isEqual(t.fields)},da);function da(t){this.fields=t}var ma=(ya.prototype.isEqual=function(t){return this.field.isEqual(t.field)&&this.transform.isEqual(t.transform)},ya);function ya(t,e){this.field=t,this.transform=e}var ga,va,ba=function(t,e){this.version=t,this.transformResults=e};(va=ga=ga||{})[va.Set=0]="Set",va[va.Patch=1]="Patch",va[va.Transform=2]="Transform",va[va.Delete=3]="Delete";var wa=(Ea.exists=function(t){return new Ea(void 0,t)},Ea.updateTime=function(t){return new Ea(t)},Object.defineProperty(Ea.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),Ea.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof Os&&t.version.isEqual(this.updateTime):void 0!==this.exists?this.exists===t instanceof Os:(xr(this.isNone,"Precondition should be empty"),!0)},Ea.prototype.isEqual=function(t){return function(t,e){return null!=t?!(!e||!t.isEqual(e)):t===e}(this.updateTime,t.updateTime)&&this.exists===t.exists},Ea.NONE=new Ea,Ea);function Ea(t,e){this.updateTime=t,this.exists=e,xr(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}var Sa=(Ta.prototype.verifyKeyMatches=function(t){null!=t&&xr(t.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")},Ta.getPostMutationVersion=function(t){return t instanceof Os?t.version:oo.MIN},Ta);function Ta(){}var Ia,Ca=(s(Da,Ia=Sa),Da.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),xr(null==e.transformResults,"Transform results received by SetMutation.");var n=e.version;return new Os(this.key,n,{hasCommittedMutations:!0},this.value)},Da.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Sa.getPostMutationVersion(t);return new Os(this.key,r,{hasLocalMutations:!0},this.value)},Da.prototype.extractBaseValue=function(t){return null},Da.prototype.isEqual=function(t){return t instanceof Da&&this.key.isEqual(t.key)&&this.value.isEqual(t.value)&&this.precondition.isEqual(t.precondition)},Da);function Da(t,e,n){var r=Ia.call(this)||this;return r.key=t,r.value=e,r.precondition=n,r.type=ga.Set,r}var Na,Aa=(s(ka,Na=Sa),ka.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),xr(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return new Vs(this.key,e.version);var n=this.patchDocument(t);return new Os(this.key,e.version,{hasCommittedMutations:!0},n)},ka.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Sa.getPostMutationVersion(t),i=this.patchDocument(t);return new Os(this.key,r,{hasLocalMutations:!0},i)},ka.prototype.extractBaseValue=function(t){return null},ka.prototype.isEqual=function(t){return t instanceof ka&&this.key.isEqual(t.key)&&this.fieldMask.isEqual(t.fieldMask)&&this.precondition.isEqual(t.precondition)},ka.prototype.patchDocument=function(t){var e;return e=t instanceof Os?t.data():Cs.EMPTY,this.patchObject(e)},ka.prototype.patchObject=function(n){var r=this;return this.fieldMask.fields.forEach(function(t){if(!t.isEmpty()){var e=r.data.field(t);n=null!==e?n.set(t,e):n.delete(t)}}),n},ka);function ka(t,e,n,r){var i=Na.call(this)||this;return i.key=t,i.data=e,i.fieldMask=n,i.precondition=r,i.type=ga.Patch,i}var Ra,Ma=(s(_a,Ra=Sa),_a.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),xr(null!=e.transformResults,"Transform results missing for TransformMutation."),!this.precondition.isValidFor(t))return new Vs(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 Os(this.key,i,{hasCommittedMutations:!0},o)},_a.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,t,e),o=this.transformObject(r.data(),i);return new Os(this.key,r.version,{hasLocalMutations:!0},o)},_a.prototype.extractBaseValue=function(t){for(var e=null,n=0,r=this.fieldTransforms;n<r.length;n++){var i=r[n],o=t instanceof Os?t.field(i.field):void 0,a=i.transform.computeBaseValue(o||null);null!=a&&(e=null==e?Cs.EMPTY.set(i.field,a):e.set(i.field,a))}return e},_a.prototype.isEqual=function(t){return t instanceof _a&&this.key.isEqual(t.key)&&gi(this.fieldTransforms,t.fieldTransforms)&&this.precondition.isEqual(t.precondition)},_a.prototype.requireDocument=function(t){xr(t instanceof Os,"Unknown MaybeDocument type "+t);var e=t;return xr(e.key.isEqual(this.key),"Can only transform a document with the same key"),e},_a.prototype.serverTransformResults=function(t,e){var n=[];xr(this.fieldTransforms.length===e.length,"server transform result count ("+e.length+") should match field transform count ("+this.fieldTransforms.length+")");for(var r=0;r<e.length;r++){var i=this.fieldTransforms[r],o=i.transform,a=null;t instanceof Os&&(a=t.field(i.field)),n.push(o.applyToRemoteDocument(a,e[r]))}return n},_a.prototype.localTransformResults=function(t,e,n){for(var r=[],i=0,o=this.fieldTransforms;i<o.length;i++){var a=o[i],s=a.transform,u=null;e instanceof Os&&(u=e.field(a.field)),null===u&&n instanceof Os&&(u=n.field(a.field)),r.push(s.applyToLocalView(u,t))}return r},_a.prototype.transformObject=function(t,e){xr(e.length===this.fieldTransforms.length,"TransformResults length mismatch.");for(var n=0;n<this.fieldTransforms.length;n++){var r=this.fieldTransforms[n].field;t=t.set(r,e[n])}return t},_a);function _a(t,e){var n=Ra.call(this)||this;return n.key=t,n.fieldTransforms=e,n.type=ga.Transform,n.precondition=wa.exists(!0),n}var Oa,Pa,La,xa,qa,Fa=(s(Va,Oa=Sa),Va.prototype.applyToRemoteDocument=function(t,e){return this.verifyKeyMatches(t),xr(null==e.transformResults,"Transform results received by DeleteMutation."),new xs(this.key,e.version,{hasCommittedMutations:!0})},Va.prototype.applyToLocalView=function(t,e,n){return this.verifyKeyMatches(t),this.precondition.isValidFor(t)?(t&&xr(t.key.isEqual(this.key),"Can only apply mutation to document with same key"),new xs(this.key,oo.forDeletedDoc())):t},Va.prototype.extractBaseValue=function(t){return null},Va.prototype.isEqual=function(t){return t instanceof Va&&this.key.isEqual(t.key)&&this.precondition.isEqual(t.precondition)},Va);function Va(t,e){var n=Oa.call(this)||this;return n.key=t,n.precondition=e,n.type=ga.Delete,n}(La=Pa=Pa||{})[La.NullValue=0]="NullValue",La[La.BooleanValue=1]="BooleanValue",La[La.NumberValue=2]="NumberValue",La[La.TimestampValue=3]="TimestampValue",La[La.StringValue=4]="StringValue",La[La.BlobValue=5]="BlobValue",La[La.RefValue=6]="RefValue",La[La.GeoPointValue=7]="GeoPointValue",La[La.ArrayValue=8]="ArrayValue",La[La.ObjectValue=9]="ObjectValue",(qa=xa=xa||{})[qa.Default=0]="Default",qa[qa.Estimate=1]="Estimate",qa[qa.Previous=2]="Previous";var Ba=(Ua.fromSnapshotOptions=function(t,e){switch(t.serverTimestamps){case"estimate":return new Ua(xa.Estimate,e);case"previous":return new Ua(xa.Previous,e);case"none":case void 0:return new Ua(xa.Default,e);default:return Lr("fromSnapshotOptions() called with invalid options.")}},Ua);function Ua(t,e){this.serverTimestampBehavior=t,this.timestampsInSnapshots=e}var Qa=(Ka.prototype.toString=function(){var t=this.value();return null===t?"null":t.toString()},Ka.prototype.defaultCompareTo=function(t){return xr(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),yi(this.typeOrder,t.typeOrder)},Ka);function Ka(){}var ja,Wa=(s(Ga,ja=Qa),Ga.prototype.value=function(t){return null},Ga.prototype.isEqual=function(t){return t instanceof Ga},Ga.prototype.compareTo=function(t){return t instanceof Ga?0:this.defaultCompareTo(t)},Ga.INSTANCE=new Ga,Ga);function Ga(){var t=ja.call(this)||this;return t.typeOrder=Pa.NullValue,t.internalValue=null,t}var za,Ha=(s(Ya,za=Qa),Ya.prototype.value=function(t){return this.internalValue},Ya.prototype.isEqual=function(t){return t instanceof Ya&&this.internalValue===t.internalValue},Ya.prototype.compareTo=function(t){return t instanceof Ya?yi(this,t):this.defaultCompareTo(t)},Ya.of=function(t){return t?Ya.TRUE:Ya.FALSE},Ya.TRUE=new Ya(!0),Ya.FALSE=new Ya(!1),Ya);function Ya(t){var e=za.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.BooleanValue,e}var Xa,Ja=(s($a,Xa=Qa),$a.prototype.value=function(t){return this.internalValue},$a.prototype.compareTo=function(t){return t instanceof $a?function(t,e){return t<e?-1:e<t?1:t===e?0:isNaN(t)?isNaN(e)?0:-1:1}(this.internalValue,t.internalValue):this.defaultCompareTo(t)},$a);function $a(t){var e=Xa.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.NumberValue,e}function Za(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}var ts,es=(s(ns,ts=Ja),ns.prototype.isEqual=function(t){return t instanceof ns&&Za(this.internalValue,t.internalValue)},ns);function ns(){return null!==ts&&ts.apply(this,arguments)||this}var rs,is=(s(os,rs=Ja),os.prototype.isEqual=function(t){return t instanceof os&&Za(this.internalValue,t.internalValue)},os.NAN=new os(NaN),os.POSITIVE_INFINITY=new os(1/0),os.NEGATIVE_INFINITY=new os(-1/0),os);function os(){return null!==rs&&rs.apply(this,arguments)||this}var as,ss=(s(us,as=Qa),us.prototype.value=function(t){return this.internalValue},us.prototype.isEqual=function(t){return t instanceof us&&this.internalValue===t.internalValue},us.prototype.compareTo=function(t){return t instanceof us?yi(this.internalValue,t.internalValue):this.defaultCompareTo(t)},us);function us(t){var e=as.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.StringValue,e}var cs,hs=(s(ls,cs=Qa),ls.prototype.value=function(t){return!t||t.timestampsInSnapshots?this.internalValue:this.internalValue.toDate()},ls.prototype.isEqual=function(t){return t instanceof ls&&this.internalValue.isEqual(t.internalValue)},ls.prototype.compareTo=function(t){return t instanceof ls?this.internalValue._compareTo(t.internalValue):t instanceof ps?-1:this.defaultCompareTo(t)},ls);function ls(t){var e=cs.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.TimestampValue,e}var fs,ps=(s(ds,fs=Qa),ds.prototype.value=function(t){return t&&t.serverTimestampBehavior===xa.Estimate?new hs(this.localWriteTime).value(t):t&&t.serverTimestampBehavior===xa.Previous&&this.previousValue?this.previousValue.value(t):null},ds.prototype.isEqual=function(t){return t instanceof ds&&this.localWriteTime.isEqual(t.localWriteTime)},ds.prototype.compareTo=function(t){return t instanceof ds?this.localWriteTime._compareTo(t.localWriteTime):t instanceof hs?1:this.defaultCompareTo(t)},ds.prototype.toString=function(){return"<ServerTimestamp localTime="+this.localWriteTime.toString()+">"},ds);function ds(t,e){var n=fs.call(this)||this;return n.localWriteTime=t,n.previousValue=e,n.typeOrder=Pa.TimestampValue,n}var ms,ys=(s(gs,ms=Qa),gs.prototype.value=function(t){return this.internalValue},gs.prototype.isEqual=function(t){return t instanceof gs&&this.internalValue.isEqual(t.internalValue)},gs.prototype.compareTo=function(t){return t instanceof gs?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},gs);function gs(t){var e=ms.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.BlobValue,e}var vs,bs=(s(ws,vs=Qa),ws.prototype.value=function(t){return this.key},ws.prototype.isEqual=function(t){return t instanceof ws&&this.key.isEqual(t.key)&&this.databaseId.isEqual(t.databaseId)},ws.prototype.compareTo=function(t){if(t instanceof ws){var e=this.databaseId.compareTo(t.databaseId);return 0!==e?e:Bi.comparator(this.key,t.key)}return this.defaultCompareTo(t)},ws);function ws(t,e){var n=vs.call(this)||this;return n.databaseId=t,n.key=e,n.typeOrder=Pa.RefValue,n}var Es,Ss=(s(Ts,Es=Qa),Ts.prototype.value=function(t){return this.internalValue},Ts.prototype.isEqual=function(t){return t instanceof Ts&&this.internalValue.isEqual(t.internalValue)},Ts.prototype.compareTo=function(t){return t instanceof Ts?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},Ts);function Ts(t){var e=Es.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.GeoPointValue,e}var Is,Cs=(s(Ds,Is=Qa),Ds.prototype.value=function(n){var r={};return this.internalValue.inorderTraversal(function(t,e){r[t]=e.value(n)}),r},Ds.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},Ds.prototype.isEqual=function(t){if(t instanceof Ds){for(var e=this.internalValue.getIterator(),n=t.internalValue.getIterator();e.hasNext()&&n.hasNext();){var r=e.getNext(),i=n.getNext();if(r.key!==i.key||!r.value.isEqual(i.value))return!1}return!e.hasNext()&&!n.hasNext()}return!1},Ds.prototype.compareTo=function(t){if(t instanceof Ds){for(var e=this.internalValue.getIterator(),n=t.internalValue.getIterator();e.hasNext()&&n.hasNext();){var r=e.getNext(),i=n.getNext(),o=yi(r.key,i.key)||r.value.compareTo(i.value);if(o)return o}return yi(e.hasNext(),n.hasNext())}return this.defaultCompareTo(t)},Ds.prototype.set=function(t,e){if(xr(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),e);var n=this.child(t.firstSegment());n instanceof Ds||(n=Ds.EMPTY);var r=n.set(t.popFirst(),e);return this.setChild(t.firstSegment(),r)},Ds.prototype.delete=function(t){if(xr(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new Ds(this.internalValue.remove(t.firstSegment()));var e=this.child(t.firstSegment());if(e instanceof Ds){var n=e.delete(t.popFirst());return new Ds(this.internalValue.insert(t.firstSegment(),n))}return this},Ds.prototype.contains=function(t){return null!==this.field(t)},Ds.prototype.field=function(t){xr(!t.isEmpty(),"Can't get field of empty path");var e=this;return t.forEach(function(t){e=e instanceof Ds?e.internalValue.get(t):null}),e},Ds.prototype.fieldMask=function(){var i=new yo(Fi.comparator);return this.internalValue.forEach(function(t,e){var n=new Fi([t]);if(e instanceof Ds){var r=e.fieldMask().fields;r.isEmpty()?i=i.add(n):r.forEach(function(t){i=i.add(n.child(t))})}else i=i.add(n)}),pa.fromSet(i)},Ds.prototype.toString=function(){return this.internalValue.toString()},Ds.prototype.child=function(t){return this.internalValue.get(t)||void 0},Ds.prototype.setChild=function(t,e){return new Ds(this.internalValue.insert(t,e))},Ds.EMPTY=new Ds(new so(yi)),Ds);function Ds(t){var e=Is.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.ObjectValue,e}var Ns,As=(s(ks,Ns=Qa),ks.prototype.value=function(e){return this.internalValue.map(function(t){return t.value(e)})},ks.prototype.contains=function(t){for(var e=0,n=this.internalValue;e<n.length;e++)if(n[e].isEqual(t))return!0;return!1},ks.prototype.forEach=function(t){this.internalValue.forEach(t)},ks.prototype.isEqual=function(t){if(t instanceof ks){if(this.internalValue.length!==t.internalValue.length)return!1;for(var e=0;e<this.internalValue.length;e++)if(!this.internalValue[e].isEqual(t.internalValue[e]))return!1;return!0}return!1},ks.prototype.compareTo=function(t){if(t instanceof ks){for(var e=Math.min(this.internalValue.length,t.internalValue.length),n=0;n<e;n++){var r=this.internalValue[n].compareTo(t.internalValue[n]);if(r)return r}return yi(this.internalValue.length,t.internalValue.length)}return this.defaultCompareTo(t)},ks.prototype.toString=function(){return"["+this.internalValue.map(function(t){return t.toString()}).join(",")+"]"},ks);function ks(t){var e=Ns.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.ArrayValue,e}var Rs=(Ms.compareByKey=function(t,e){return Bi.comparator(t.key,e.key)},Ms);function Ms(t,e){this.key=t,this.version=e}var _s,Os=(s(Ps,_s=Rs),Ps.prototype.field=function(t){if(this.objectValue)return this.objectValue.field(t);this.fieldValueCache||(this.fieldValueCache=new Map);var e=t.canonicalString(),n=this.fieldValueCache.get(e);if(void 0===n){var r=this.getProtoField(t);n=void 0===r?null:this.converter(r),this.fieldValueCache.set(e,n)}return n},Ps.prototype.data=function(){var n=this;if(!this.objectValue){var r=Cs.EMPTY;Hr(this.proto.fields,function(t,e){r=r.set(new Fi([t]),n.converter(e))}),this.objectValue=r,this.fieldValueCache=void 0}return this.objectValue},Ps.prototype.value=function(){return this.data().value()},Ps.prototype.isEqual=function(t){return t instanceof Ps&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.hasLocalMutations===t.hasLocalMutations&&this.hasCommittedMutations===t.hasCommittedMutations&&this.data().isEqual(t.data())},Ps.prototype.toString=function(){return"Document("+this.key+", "+this.version+", "+this.data.toString()+", {hasLocalMutations: "+this.hasLocalMutations+"}), {hasCommittedMutations: "+this.hasCommittedMutations+"})"},Object.defineProperty(Ps.prototype,"hasPendingWrites",{get:function(){return this.hasLocalMutations||this.hasCommittedMutations},enumerable:!0,configurable:!0}),Ps.prototype.getProtoField=function(t){xr(void 0!==this.proto,"Can only call getProtoField() when proto is defined");for(var e=this.proto.fields[t.firstSegment()],n=1;n<t.length;++n){if(!e||!e.mapValue)return;e=e.mapValue.fields[t.get(n)]}return e},Ps.compareByField=function(t,e,n){var r=e.field(t),i=n.field(t);return null!==r&&null!==i?r.compareTo(i):Lr("Trying to compare documents on fields that don't exist")},Ps);function Ps(t,e,n,r,i,o){var a=_s.call(this,t,e)||this;return a.objectValue=r,a.proto=i,a.converter=o,xr(void 0!==a.objectValue||void 0!==a.proto&&void 0!==a.converter,"If objectValue is not defined, proto and converter need to be set."),a.hasLocalMutations=!!n.hasLocalMutations,a.hasCommittedMutations=!!n.hasCommittedMutations,a}var Ls,xs=(s(qs,Ls=Rs),qs.prototype.toString=function(){return"NoDocument("+this.key+", "+this.version+")"},Object.defineProperty(qs.prototype,"hasPendingWrites",{get:function(){return this.hasCommittedMutations},enumerable:!0,configurable:!0}),qs.prototype.isEqual=function(t){return t instanceof qs&&t.hasCommittedMutations===this.hasCommittedMutations&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)},qs);function qs(t,e,n){var r=Ls.call(this,t,e)||this;return r.hasCommittedMutations=!(!n||!n.hasCommittedMutations),r}var Fs,Vs=(s(Bs,Fs=Rs),Bs.prototype.toString=function(){return"UnknownDocument("+this.key+", "+this.version+")"},Object.defineProperty(Bs.prototype,"hasPendingWrites",{get:function(){return!0},enumerable:!0,configurable:!0}),Bs.prototype.isEqual=function(t){return t instanceof Bs&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)},Bs);function Bs(){return null!==Fs&&Fs.apply(this,arguments)||this}var Us=(Qs.prototype.get=function(t){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0!==n)for(var r=0,i=n;r<i.length;r++){var o=i[r],a=o[0],s=o[1];if(a.isEqual(t))return s}},Qs.prototype.has=function(t){return void 0!==this.get(t)},Qs.prototype.set=function(t,e){var n=this.mapKeyFn(t),r=this.inner[n];if(void 0!==r){for(var i=0;i<r.length;i++)if(r[i][0].isEqual(t))return void(r[i]=[t,e]);r.push([t,e])}else this.inner[n]=[[t,e]]},Qs.prototype.delete=function(t){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0===n)return!1;for(var r=0;r<n.length;r++)if(n[r][0].isEqual(t))return 1===n.length?delete this.inner[e]:n.splice(r,1),!0;return!1},Qs.prototype.forEach=function(s){Hr(this.inner,function(t,e){for(var n=0,r=e;n<r.length;n++){var i=r[n],o=i[0],a=i[1];s(o,a)}})},Qs.prototype.isEmpty=function(){return Yr(this.inner)},Qs);function Qs(t){this.mapKeyFn=t,this.inner={}}var Ks=(js.prototype.addEntry=function(t){this.assertNotApplied(),this.changes.set(t.key,t)},js.prototype.removeEntry=function(t){this.assertNotApplied(),this.changes.set(t,null)},js.prototype.getEntry=function(t,e){this.assertNotApplied();var n=this.changes.get(e);return void 0!==n?Lo.resolve(n):this.getFromCache(t,e)},js.prototype.getEntries=function(t,e){return this.getAllFromCache(t,e)},js.prototype.apply=function(t){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(t)},js.prototype.assertNotApplied=function(){xr(!this.changesApplied,"Changes have already been applied.")},js);function js(){this.changes=new Us(function(t){return t.toString()}),this.changesApplied=!1}var Ws,Gs="The remote document changelog no longer contains all changes for all local query views. It may be necessary to rebuild these views.",zs=(Object.defineProperty(Hs.prototype,"lastProcessedDocumentChangeId",{get:function(){return this._lastProcessedDocumentChangeId},enumerable:!0,configurable:!0}),Hs.prototype.start=function(t){var e=Xo.getStore(t,_u.store);return this.synchronizeLastDocumentChangeId(e)},Hs.prototype.addEntry=function(t,e,n){var r=this;return Js(t).put(Zs(e),n).next(function(){r.indexManager.addToCollectionParentIndex(t,e.path.popLast())})},Hs.prototype.removeEntry=function(t,e){var n=Js(t),r=Zs(e);return n.delete(r)},Hs.prototype.updateMetadata=function(e,n,r){var i=this;return this.getMetadata(e).next(function(t){return t.byteSize+=r,i.setMetadata(e,t).next(function(){if(i.keepDocumentChangeLog)return $s(e).put({changes:i.serializer.toDbResourcePaths(n)})})})},Hs.prototype.getEntry=function(t,e){var n=this;return Js(t).get(Zs(e)).next(function(t){return t?n.serializer.fromDbRemoteDocument(t):null})},Hs.prototype.getSizedEntry=function(t,e){var n=this;return Js(t).get(Zs(e)).next(function(t){return t?{maybeDocument:n.serializer.fromDbRemoteDocument(t),size:tu(t)}:null})},Hs.prototype.getEntries=function(t,e){var n=this,r=So();return this.forEachDbEntry(t,e,function(t,e){r=e?r.insert(t,n.serializer.fromDbRemoteDocument(e)):r.insert(t,null)}).next(function(){return r})},Hs.prototype.getSizedEntries=function(t,e){var n=this,r=So(),i=new so(Bi.comparator);return this.forEachDbEntry(t,e,function(t,e){i=e?(r=r.insert(t,n.serializer.fromDbRemoteDocument(e)),i.insert(t,tu(e))):(r=r.insert(t,null),i.insert(t,0))}).next(function(){return{maybeDocuments:r,sizeMap:i}})},Hs.prototype.forEachDbEntry=function(t,e,i){if(e.isEmpty())return Lo.resolve();var n=IDBKeyRange.bound(e.first().path.toArray(),e.last().path.toArray()),o=e.getIterator(),a=o.getNext();return Js(t).iterate({range:n},function(t,e,n){for(var r=Bi.fromSegments(t);a&&Bi.comparator(a,r)<0;)i(a,null),a=o.getNext();a&&a.isEqual(r)&&(i(a,e),a=o.hasNext()?o.getNext():null),a?n.skip(a.path.toArray()):n.done()}).next(function(){for(;a;)i(a,null),a=o.hasNext()?o.getNext():null})},Hs.prototype.getDocumentsMatchingQuery=function(t,i){var o=this;xr(!i.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var a=Io(),s=i.path.length+1,e=i.path.toArray(),n=IDBKeyRange.lowerBound(e);return Js(t).iterate({range:n},function(t,e,n){if(t.length===s){var r=o.serializer.fromDbRemoteDocument(e);i.path.isPrefixOf(r.key.path)?r instanceof Os&&i.matches(r)&&(a=a.insert(r.key,r)):n.done()}}).next(function(){return a})},Hs.prototype.getNewDocumentChanges=function(e){var r=this;xr(this.keepDocumentChangeLog,"Can only call getNewDocumentChanges() when document change log is enabled");var n=Ao(),i=Eo(),t=IDBKeyRange.lowerBound(this._lastProcessedDocumentChangeId+1),o=!0,a=$s(e);return a.iterate({range:t},function(t,e){if(o&&(o=!1,r._lastProcessedDocumentChangeId+1!==e.id))return r.synchronizeLastDocumentChangeId(a).next(function(){return Lo.reject(new Qr(Ur.DATA_LOSS,Gs))});n=n.unionWith(r.serializer.fromDbResourcePaths(e.changes)),r._lastProcessedDocumentChangeId=e.id}).next(function(){var t=[];return n.forEach(function(n){t.push(r.getEntry(e,n).next(function(t){var e=t||new xs(n,oo.forDeletedDoc());i=i.insert(n,e)}))}),Lo.waitFor(t)}).next(function(){return i})},Hs.prototype.removeDocumentChangesThroughChangeId=function(t,e){var n=IDBKeyRange.upperBound(e);return $s(t).delete(n)},Hs.prototype.synchronizeLastDocumentChangeId=function(t){var r=this;return this._lastProcessedDocumentChangeId=0,t.iterate({keysOnly:!0,reverse:!0},function(t,e,n){r._lastProcessedDocumentChangeId=t,n.done()})},Hs.prototype.newChangeBuffer=function(){return new Hs.RemoteDocumentChangeBuffer(this)},Hs.prototype.getSize=function(t){return this.getMetadata(t).next(function(t){return t.byteSize})},Hs.prototype.getMetadata=function(t){return Xs(t).get(Eu.key).next(function(t){return xr(!!t,"Missing document cache metadata"),t})},Hs.prototype.setMetadata=function(t,e){return Xs(t).put(Eu.key,e)},Hs.RemoteDocumentChangeBuffer=(s(Ys,Ws=Ks),Ys.prototype.applyChanges=function(o){var a=this,s=[],u=0,c=Ao();return this.changes.forEach(function(t,e){var n=a.documentSizes.get(t);if(xr(void 0!==n,"Cannot modify a document that wasn't read (for "+t+")"),e){var r=a.documentCache.serializer.toDbRemoteDocument(e),i=tu(r);u+=i-n,s.push(a.documentCache.addEntry(o,t,r))}else u-=n,s.push(a.documentCache.removeEntry(o,t));c=c.add(t)}),s.push(this.documentCache.updateMetadata(o,c,u)),Lo.waitFor(s)},Ys.prototype.getFromCache=function(t,e){var n=this;return this.documentCache.getSizedEntry(t,e).next(function(t){return null===t?(n.documentSizes.set(e,0),null):(n.documentSizes.set(e,t.size),t.maybeDocument)})},Ys.prototype.getAllFromCache=function(t,e){var n=this;return this.documentCache.getSizedEntries(t,e).next(function(t){var e=t.maybeDocuments;return t.sizeMap.forEach(function(t,e){n.documentSizes.set(t,e)}),e})},Ys),Hs);function Hs(t,e,n){this.serializer=t,this.indexManager=e,this.keepDocumentChangeLog=n,this._lastProcessedDocumentChangeId=0}function Ys(t){var e=Ws.call(this)||this;return e.documentCache=t,e.documentSizes=new Us(function(t){return t.toString()}),e}function Xs(t){return uc.getStore(t,Eu.store)}function Js(t){return uc.getStore(t,bu.store)}function $s(t){return uc.getStore(t,_u.store)}function Zs(t){return t.path.toArray()}function tu(t){var e;if(t.document)e=t.document;else if(t.unknownDocument)e=t.unknownDocument;else{if(!t.noDocument)throw Lr("Unknown remote document type");e=t.noDocument}return JSON.stringify(e).length}var eu=(nu.prototype.addToCollectionParentIndex=function(t,e){return this.collectionParentIndex.add(e),Lo.resolve()},nu.prototype.getCollectionParents=function(t,e){return Lo.resolve(this.collectionParentIndex.getEntries(e))},nu);function nu(){this.collectionParentIndex=new ru}var ru=(iu.prototype.add=function(t){xr(t.length%2==1,"Expected a collection path.");var e=t.lastSegment(),n=t.popLast(),r=this.index[e]||new yo(Pi.comparator),i=!r.has(n);return this.index[e]=r.add(n),i},iu.prototype.getEntries=function(t){return(this.index[t]||new yo(Pi.comparator)).toArray()},iu);function iu(){this.index={}}var ou=8,au=(su.prototype.createOrUpgrade=function(t,e,n,r){var i=this;xr(n<r&&0<=n&&r<=ou,"Unexpected schema upgrade from v"+n+" to v{toVersion}."),n<1&&1<=r&&(function(t){t.createObjectStore(cu.store)}(t),function(t){t.createObjectStore(lu.store,{keyPath:lu.keyPath}),t.createObjectStore(pu.store,{keyPath:pu.keyPath,autoIncrement:!0}).createIndex(pu.userMutationsIndex,pu.userMutationsKeyPath,{unique:!0}),t.createObjectStore(mu.store)}(t),Mu(t),function(t){t.createObjectStore(bu.store)}(t));var o=Lo.resolve();return n<3&&3<=r&&(0!==n&&(function(t){t.deleteObjectStore(Cu.store),t.deleteObjectStore(Tu.store),t.deleteObjectStore(Nu.store)}(t),Mu(t)),o=o.next(function(){return function(t){var e=t.store(Nu.store),n=new Nu(0,0,oo.MIN.toTimestamp(),0);return e.put(Nu.key,n)}(e)})),n<4&&4<=r&&(0!==n&&(o=o.next(function(){return function(r,i){return i.store(pu.store).loadAll().next(function(t){r.deleteObjectStore(pu.store),r.createObjectStore(pu.store,{keyPath:pu.keyPath,autoIncrement:!0}).createIndex(pu.userMutationsIndex,pu.userMutationsKeyPath,{unique:!0});var e=i.store(pu.store),n=t.map(function(t){return e.put(t)});return Lo.waitFor(n)})}(t,e)})),o=o.next(function(){!function(t){t.createObjectStore(Pu.store,{keyPath:Pu.keyPath})}(t),function(t){t.createObjectStore(_u.store,{keyPath:"id",autoIncrement:!0})}(t)})),n<5&&5<=r&&(o=o.next(function(){return i.removeAcknowledgedMutations(e)})),n<6&&6<=r&&(o=o.next(function(){return function(t){t.createObjectStore(Eu.store)}(t),i.addDocumentGlobal(e)})),n<7&&7<=r&&(o=o.next(function(){return i.ensureSequenceNumbers(e)})),n<8&&8<=r&&(o=o.next(function(){return i.createCollectionParentIndex(t,e)})),o},su.prototype.addDocumentGlobal=function(e){var n=0;return e.store(bu.store).iterate(function(t,e){n+=tu(e)}).next(function(){var t=new Eu(n);return e.store(Eu.store).put(Eu.key,t)})},su.prototype.removeAcknowledgedMutations=function(r){var i=this,t=r.store(lu.store),e=r.store(pu.store);return t.loadAll().next(function(t){return Lo.forEach(t,function(n){var t=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return e.loadAll(pu.userMutationsIndex,t).next(function(t){return Lo.forEach(t,function(t){xr(t.userId===n.userId,"Cannot process batch "+t.batchId+" from unexpected user");var e=i.serializer.fromDbMutationBatch(t);return Bo(r,n.userId,e).next(function(){})})})})})},su.prototype.ensureSequenceNumbers=function(t){var a=t.store(Cu.store),e=t.store(bu.store);return la(t).next(function(i){var o=[];return e.iterate(function(t,e){var n=new Pi(t),r=function(t){return[0,Zi(t)]}(n);o.push(a.get(r).next(function(t){return t?Lo.resolve():function(t){return a.put(new Cu(0,Zi(t),i))}(n)}))}).next(function(){return Lo.waitFor(o)})})},su.prototype.createCollectionParentIndex=function(t,e){function i(t){if(o.add(t)){var e=t.lastSegment(),n=t.popLast();return r.put({collectionId:e,parent:Zi(n)})}}t.createObjectStore(ku.store,{keyPath:ku.keyPath});var r=e.store(ku.store),o=new ru;return e.store(bu.store).iterate({keysOnly:!0},function(t,e){var n=new Pi(t);return i(n.popLast())}).next(function(){return e.store(mu.store).iterate({keysOnly:!0},function(t,e){t[0];var n=t[1],r=(t[2],no(n));return i(r.popLast())})})},su);function su(t){this.serializer=t}var uu=function(t,e){this.seconds=t,this.nanoseconds=e},cu=(hu.store="owner",hu.key="owner",hu);function hu(t,e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n}var lu=(fu.store="mutationQueues",fu.keyPath="userId",fu);function fu(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}var pu=(du.store="mutations",du.keyPath="batchId",du.userMutationsIndex="userMutationsIndex",du.userMutationsKeyPath=["userId","batchId"],du);function du(t,e,n,r,i){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=i}var mu=(yu.prefixForUser=function(t){return[t]},yu.prefixForPath=function(t,e){return[t,Zi(e)]},yu.key=function(t,e,n){return[t,Zi(e),n]},yu.store="documentMutations",yu.PLACEHOLDER=new yu,yu);function yu(){}var gu=function(t,e){this.path=t,this.readTime=e},vu=function(t,e){this.path=t,this.version=e},bu=(wu.store="remoteDocuments",wu);function wu(t,e,n,r){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r}var Eu=(Su.store="remoteDocumentGlobal",Su.key="remoteDocumentGlobalKey",Su);function Su(t){this.byteSize=t}var Tu=(Iu.store="targets",Iu.keyPath="targetId",Iu.queryTargetsIndexName="queryTargetsIndex",Iu.queryTargetsKeyPath=["canonicalId","targetId"],Iu);function Iu(t,e,n,r,i,o){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.query=o}var Cu=(Du.store="targetDocuments",Du.keyPath=["targetId","path"],Du.documentTargetsIndex="documentTargetsIndex",Du.documentTargetsKeyPath=["path","targetId"],Du);function Du(t,e,n){this.targetId=t,this.path=e,xr(0===t==(void 0!==(this.sequenceNumber=n)),"A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number")}var Nu=(Au.key="targetGlobalKey",Au.store="targetGlobal",Au);function Au(t,e,n,r){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n,this.targetCount=r}var ku=(Ru.store="collectionParents",Ru.keyPath=["collectionId","parent"],Ru);function Ru(t,e){this.collectionId=t,this.parent=e}function Mu(t){t.createObjectStore(Cu.store,{keyPath:Cu.keyPath}).createIndex(Cu.documentTargetsIndex,Cu.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(Tu.store,{keyPath:Tu.keyPath}).createIndex(Tu.queryTargetsIndexName,Tu.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(Nu.store)}var _u=(Ou.store="remoteDocumentChanges",Ou.keyPath="id",Ou);function Ou(t){this.changes=t}var Pu=(Lu.store="clientMetadata",Lu.keyPath="clientId",Lu);function Lu(t,e,n,r,i){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r,this.lastProcessedDocumentChangeId=i}var xu,qu,Fu=[lu.store,pu.store,mu.store,bu.store,Tu.store,cu.store,Nu.store,Cu.store].concat([Pu.store,_u.store]).concat([Eu.store]).concat([ku.store]),Vu=(Bu.prototype.addToCollectionParentIndex=function(t,e){if(xr(e.length%2==1,"Expected a collection path."),this.collectionParentsCache.add(e)){xr(1<=e.length,"Invalid collection path.");var n=e.lastSegment(),r=e.popLast();return Uu(t).put({collectionId:n,parent:Zi(r)})}return Lo.resolve()},Bu.prototype.getCollectionParents=function(t,i){var o=[],e=IDBKeyRange.bound([i,""],[vi(i),""],!1,!0);return Uu(t).loadAll(e).next(function(t){for(var e=0,n=t;e<n.length;e++){var r=n[e];if(r.collectionId!==i)break;o.push(no(r.parent))}return o})},Bu);function Bu(){this.collectionParentsCache=new ru}function Uu(t){return uc.getStore(t,ku.store)}(qu=xu=xu||{})[qu.Listen=0]="Listen",qu[qu.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",qu[qu.LimboResolution=2]="LimboResolution";var Qu=(Ku.prototype.copy=function(t){return new Ku(this.query,this.targetId,this.purpose,void 0===t.sequenceNumber?this.sequenceNumber:t.sequenceNumber,void 0===t.snapshotVersion?this.snapshotVersion:t.snapshotVersion,void 0===t.resumeToken?this.resumeToken:t.resumeToken)},Ku.prototype.isEqual=function(t){return this.targetId===t.targetId&&this.purpose===t.purpose&&this.sequenceNumber===t.sequenceNumber&&this.snapshotVersion.isEqual(t.snapshotVersion)&&this.resumeToken===t.resumeToken&&this.query.isEqual(t.query)},Ku);function Ku(t,e,n,r,i,o){void 0===i&&(i=oo.MIN),void 0===o&&(o=Vr()),this.query=t,this.targetId=e,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.resumeToken=o}var ju=(Wu.prototype.fromDbRemoteDocument=function(t){if(t.document)return this.remoteSerializer.fromDocument(t.document,!!t.hasCommittedMutations);if(t.noDocument){var e=Bi.fromSegments(t.noDocument.path),n=this.fromDbTimestamp(t.noDocument.readTime);return new xs(e,n,{hasCommittedMutations:!!t.hasCommittedMutations})}return t.unknownDocument?(e=Bi.fromSegments(t.unknownDocument.path),n=this.fromDbTimestamp(t.unknownDocument.version),new Vs(e,n)):Lr("Unexpected DbRemoteDocument")},Wu.prototype.toDbRemoteDocument=function(t){if(t instanceof Os){var e=t.proto?t.proto:this.remoteSerializer.toDocument(t),n=t.hasCommittedMutations;return new bu(null,null,e,n)}if(t instanceof xs){var r=t.key.path.toArray(),i=this.toDbTimestamp(t.version);return n=t.hasCommittedMutations,new bu(null,new gu(r,i),null,n)}return t instanceof Vs?(r=t.key.path.toArray(),i=this.toDbTimestamp(t.version),new bu(new vu(r,i),null,null,!0)):Lr("Unexpected MaybeDocumment")},Wu.prototype.toDbTimestamp=function(t){var e=t.toTimestamp();return new uu(e.seconds,e.nanoseconds)},Wu.prototype.fromDbTimestamp=function(t){var e=new ro(t.seconds,t.nanoseconds);return oo.fromTimestamp(e)},Wu.prototype.toDbMutationBatch=function(t,e){var n=this,r=e.baseMutations.map(function(t){return n.remoteSerializer.toMutation(t)}),i=e.mutations.map(function(t){return n.remoteSerializer.toMutation(t)});return new pu(t,e.batchId,e.localWriteTime.toMillis(),r,i)},Wu.prototype.fromDbMutationBatch=function(t){var e=this,n=(t.baseMutations||[]).map(function(t){return e.remoteSerializer.fromMutation(t)}),r=t.mutations.map(function(t){return e.remoteSerializer.fromMutation(t)}),i=ro.fromMillis(t.localWriteTimeMs);return new Mo(t.batchId,i,n,r)},Wu.prototype.toDbResourcePaths=function(t){var e=[];return t.forEach(function(t){e.push(Zi(t.path))}),e},Wu.prototype.fromDbResourcePaths=function(t){for(var e=Ao(),n=0,r=t;n<r.length;n++){var i=r[n];e=e.add(new Bi(no(i)))}return e},Wu.prototype.fromDbTarget=function(t){var e,n=this.fromDbTimestamp(t.readTime);return e=function(t){return void 0!==t.documents}(t.query)?this.remoteSerializer.fromDocumentsTarget(t.query):this.remoteSerializer.fromQueryTarget(t.query),new Qu(e,t.targetId,xu.Listen,t.lastListenSequenceNumber,n,t.resumeToken)},Wu.prototype.toDbTarget=function(t){xr(xu.Listen===t.purpose,"Only queries with purpose "+xu.Listen+" may be stored, got "+t.purpose);var e,n,r=this.toDbTimestamp(t.snapshotVersion);return e=t.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(t.query):this.remoteSerializer.toQueryTarget(t.query),n=t.resumeToken instanceof Uint8Array?(xr("YES"===process.env.USE_MOCK_PERSISTENCE,"Persisting non-string stream tokens is only supported with mock persistence ."),t.resumeToken.toString()):t.resumeToken,new Tu(t.targetId,t.query.canonicalId(),r,n,t.sequenceNumber,e)},Wu);function Wu(t){this.remoteSerializer=t}function Gu(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],a=yi(n,i);return 0===a?yi(r,o):a}var zu=(Hu.prototype.nextIndex=function(){return++this.previousIndex},Hu.prototype.addElement=function(t){var e=[t,this.nextIndex()];if(this.buffer.size<this.maxElements)this.buffer=this.buffer.add(e);else{var n=this.buffer.last();Gu(e,n)<0&&(this.buffer=this.buffer.delete(n).add(e))}},Object.defineProperty(Hu.prototype,"maxValue",{get:function(){return this.buffer.last()[0]},enumerable:!0,configurable:!0}),Hu);function Hu(t){this.maxElements=t,this.buffer=new yo(Gu),this.previousIndex=0}var Yu={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},Xu=(Ju.withCacheSize=function(t){return new Ju(t,Ju.DEFAULT_COLLECTION_PERCENTILE,Ju.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)},Ju.COLLECTION_DISABLED=-1,Ju.MINIMUM_CACHE_SIZE_BYTES=1048576,Ju.DEFAULT=new Ju(Ju.DEFAULT_CACHE_SIZE_BYTES=41943040,Ju.DEFAULT_COLLECTION_PERCENTILE=10,Ju.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3),Ju.DISABLED=new Ju(Ju.COLLECTION_DISABLED,0,0),Ju);function Ju(t,e,n){this.cacheSizeCollectionThreshold=t,this.percentileToCollect=e,this.maximumSequenceNumbersToCollect=n}var $u=(Zu.prototype.start=function(){xr(null===this.gcTask,"Cannot start an already started LruScheduler"),this.garbageCollector.params.cacheSizeCollectionThreshold!==Xu.COLLECTION_DISABLED&&this.scheduleGC()},Zu.prototype.stop=function(){this.gcTask&&(this.gcTask.cancel(),this.gcTask=null)},Object.defineProperty(Zu.prototype,"started",{get:function(){return null!==this.gcTask},enumerable:!0,configurable:!0}),Zu.prototype.scheduleGC=function(){var t=this;xr(null===this.gcTask,"Cannot schedule GC while a task is pending");var e=this.hasRun?3e5:6e4;_r("LruGarbageCollector","Garbage collection scheduled in "+e+"ms"),this.gcTask=this.asyncQueue.enqueueAfterDelay(Qi.LruGarbageCollection,e,function(){return t.gcTask=null,t.hasRun=!0,t.localStore.collectGarbage(t.garbageCollector).then(function(){return t.scheduleGC()}).catch(hc)})},Zu);function Zu(t,e,n){this.garbageCollector=t,this.asyncQueue=e,this.localStore=n,this.hasRun=!1,this.gcTask=null}var tc=(ec.prototype.calculateTargetCount=function(t,e){return this.delegate.getSequenceNumberCount(t).next(function(t){return Math.floor(e/100*t)})},ec.prototype.nthSequenceNumber=function(t,e){var n=this;if(0===e)return Lo.resolve(Ai.INVALID);var r=new zu(e);return this.delegate.forEachTarget(t,function(t){return r.addElement(t.sequenceNumber)}).next(function(){return n.delegate.forEachOrphanedDocumentSequenceNumber(t,function(t){return r.addElement(t)})}).next(function(){return r.maxValue})},ec.prototype.removeTargets=function(t,e,n){return this.delegate.removeTargets(t,e,n)},ec.prototype.removeOrphanedDocuments=function(t,e){return this.delegate.removeOrphanedDocuments(t,e)},ec.prototype.collect=function(e,n){var r=this;return this.params.cacheSizeCollectionThreshold===Xu.COLLECTION_DISABLED?(_r("LruGarbageCollector","Garbage collection skipped; disabled"),Lo.resolve(Yu)):this.getCacheSize(e).next(function(t){return t<r.params.cacheSizeCollectionThreshold?(_r("LruGarbageCollector","Garbage collection skipped; Cache size "+t+" is lower than threshold "+r.params.cacheSizeCollectionThreshold),Yu):r.runGarbageCollection(e,n)})},ec.prototype.getCacheSize=function(t){return this.delegate.getCacheSize(t)},ec.prototype.runGarbageCollection=function(e,n){var r,i,o,a,s,u,c,h=this,l=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(function(t){return i=t>h.params.maximumSequenceNumbersToCollect?(_r("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+h.params.maximumSequenceNumbersToCollect+" from "+t),h.params.maximumSequenceNumbersToCollect):t,a=Date.now(),h.nthSequenceNumber(e,i)}).next(function(t){return r=t,s=Date.now(),h.removeTargets(e,r,n)}).next(function(t){return o=t,u=Date.now(),h.removeOrphanedDocuments(e,r)}).next(function(t){return c=Date.now(),Rr()<=wr.DEBUG&&_r("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(a-l)+"ms\n\tDetermined least recently used "+i+" in "+(s-a)+"ms\n\tRemoved "+o+" targets in "+(u-s)+"ms\n\tRemoved "+t+" documents in "+(c-u)+"ms\nTotal Duration: "+(c-l)+"ms"),Lo.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:o,documentsRemoved:t})})},ec);function ec(t,e){this.delegate=t,this.params=e}var nc,rc="IndexedDbPersistence",ic="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",oc="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.",ac=(s(sc,nc=function(){}),sc);function sc(t,e){var n=nc.call(this)||this;return n.simpleDbTransaction=t,n.currentSequenceNumber=e,n}var uc=(cc.getStore=function(t,e){if(t instanceof ac)return Xo.getStore(t.simpleDbTransaction,e);throw Lr("IndexedDbPersistence must use instances of IndexedDbTransaction")},cc.createIndexedDbPersistence=function(n,r,i,o,a,s){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return[4,(e=new cc(n,r,i,o,a,s)).start()];case 1:return t.sent(),[2,e]}})})},cc.createMultiClientIndexedDbPersistence=function(n,r,i,o,a,s,u){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return[4,(e=new cc(n,r,i,o,a,s,u)).start()];case 1:return t.sent(),[2,e]}})})},cc.prototype.start=function(){var n=this;return xr(!this.started,"IndexedDbPersistence double-started!"),xr(null!==this.window,"Expected 'window' to be defined"),Xo.openOrCreate(this.dbName,ou,new au(this.serializer)).then(function(t){return n.simpleDb=t,n.updateClientMetadataAndTryBecomePrimary()}).then(function(){return n.attachVisibilityHandler(),n.attachWindowUnloadHook(),n.scheduleClientMetadataAndPrimaryLeaseRefreshes(),n.startRemoteDocumentCache()}).then(function(){return n.simpleDb.runTransaction("readonly",[Nu.store],function(t){return la(t).next(function(t){var e=n.multiClientParams?n.multiClientParams.sequenceNumberSyncer:void 0;n.listenSequence=new Ai(t,e)})})}).then(function(){n._started=!0}).catch(function(t){return n.simpleDb&&n.simpleDb.close(),Promise.reject(t)})},cc.prototype.startRemoteDocumentCache=function(){var e=this;return this.simpleDb.runTransaction("readonly",Fu,function(t){return e.remoteDocumentCache.start(t)})},cc.prototype.setPrimaryStateListener=function(n){var t=this;return this.primaryStateListener=function(e){return p(t,void 0,void 0,function(){return d(this,function(t){return this.started?[2,n(e)]:[2]})})},n(this.isPrimary)},cc.prototype.setDatabaseDeletedListener=function(n){var t=this;this.simpleDb.setVersionChangeListener(function(e){return p(t,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return null!==e.newVersion?[3,2]:[4,n()];case 1:t.sent(),t.label=2;case 2:return[2]}})})})},cc.prototype.setNetworkEnabled=function(t){var e=this;this.networkEnabled!==t&&(this.networkEnabled=t,this.queue.enqueueAndForget(function(){return p(e,void 0,void 0,function(){return d(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]}})})}))},cc.prototype.updateClientMetadataAndTryBecomePrimary=function(){var r=this;return this.simpleDb.runTransaction("readwrite",Fu,function(n){return fc(n).put(new Pu(r.clientId,Date.now(),r.networkEnabled,r.inForeground,r.remoteDocumentCache.lastProcessedDocumentChangeId)).next(function(){if(r.isPrimary)return r.verifyPrimaryLease(n).next(function(t){t||(r.isPrimary=!1,r.queue.enqueueAndForget(function(){return r.primaryStateListener(!1)}))})}).next(function(){return r.canActAsPrimary(n)}).next(function(t){var e=r.isPrimary;return r.isPrimary=t,e!==r.isPrimary&&r.queue.enqueueAndForget(function(){return r.primaryStateListener(r.isPrimary)}),e&&!r.isPrimary?r.releasePrimaryLeaseIfHeld(n):r.isPrimary?r.acquireOrExtendPrimaryLease(n):void 0})})},cc.prototype.verifyPrimaryLease=function(t){var e=this;return lc(t).get(cu.key).next(function(t){return Lo.resolve(e.isLocalClient(t))})},cc.prototype.removeClientMetadata=function(t){return fc(t).delete(this.clientId)},cc.prototype.maybeGarbageCollectMultiClientState=function(){return p(this,void 0,void 0,function(){var r,i,o=this;return d(this,function(t){switch(t.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,18e5)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),i=[],[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(n){var e=cc.getStore(n,Pu.store);return e.loadAll().next(function(t){r=o.filterActiveClients(t,18e5),i=t.filter(function(t){return-1===r.indexOf(t)})}).next(function(){return Lo.forEach(i,function(t){return e.delete(t.clientId)})}).next(function(){if(0<(r=r.filter(function(t){return t.clientId!==o.clientId})).length){var t=r.map(function(t){return t.lastProcessedDocumentChangeId||0}),e=Math.min.apply(Math,t);return o.remoteDocumentCache.removeDocumentChangesThroughChangeId(n,e)}})})]);case 1:t.sent(),i.forEach(function(t){o.window.localStorage.removeItem(o.zombiedClientLocalStorageKey(t.clientId))}),t.label=2;case 2:return[2]}})})},cc.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var t=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(Qi.ClientMetadataRefresh,4e3,function(){return t.updateClientMetadataAndTryBecomePrimary().then(function(){return t.maybeGarbageCollectMultiClientState()}).then(function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()})})},cc.prototype.isLocalClient=function(t){return!!t&&t.ownerId===this.clientId},cc.prototype.canActAsPrimary=function(e){var i=this;return lc(e).get(cu.key).next(function(t){if(null!==t&&i.isWithinAge(t.leaseTimestampMs,5e3)&&!i.isClientZombied(t.ownerId)){if(i.isLocalClient(t)&&i.networkEnabled)return!0;if(!i.isLocalClient(t)){if(!t.allowTabSynchronization)throw new Qr(Ur.FAILED_PRECONDITION,oc);return!1}}return!(!i.networkEnabled||!i.inForeground)||fc(e).loadAll().next(function(t){return void 0===i.filterActiveClients(t,5e3).find(function(t){if(i.clientId!==t.clientId){var e=!i.networkEnabled&&t.networkEnabled,n=!i.inForeground&&t.inForeground,r=i.networkEnabled===t.networkEnabled;if(e||n&&r)return!0}return!1})})}).next(function(t){return i.isPrimary!==t&&_r(rc,"Client "+(t?"is":"is not")+" eligible for a primary lease."),t})},cc.prototype.shutdown=function(){return p(this,void 0,void 0,function(){var e=this;return d(this,function(t){switch(t.label){case 0:return this._started=!1,this.markClientZombied(),this.clientMetadataRefresher&&(this.clientMetadataRefresher.cancel(),this.clientMetadataRefresher=null),this.detachVisibilityHandler(),this.detachWindowUnloadHook(),[4,this.simpleDb.runTransaction("readwrite",[cu.store,Pu.store],function(t){return e.releasePrimaryLeaseIfHeld(t).next(function(){return e.removeClientMetadata(t)})})];case 1:return t.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),[2]}})})},cc.prototype.filterActiveClients=function(t,e){var n=this;return t.filter(function(t){return n.isWithinAge(t.updateTimeMs,e)&&!n.isClientZombied(t.clientId)})},cc.prototype.getActiveClients=function(){var e=this;return this.simpleDb.runTransaction("readonly",[Pu.store],function(t){return fc(t).loadAll().next(function(t){return e.filterActiveClients(t,18e5).map(function(t){return t.clientId})})})},cc.clearPersistence=function(n){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return cc.isAvailable()?(e=n+cc.MAIN_DATABASE,[4,Xo.delete(e)]):[2,Promise.resolve()];case 1:return t.sent(),[2]}})})},Object.defineProperty(cc.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),cc.prototype.getMutationQueue=function(t){return xr(this.started,"Cannot initialize MutationQueue before persistence is started."),qo.forUser(t,this.serializer,this.indexManager,this.referenceDelegate)},cc.prototype.getQueryCache=function(){return xr(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},cc.prototype.getRemoteDocumentCache=function(){return xr(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},cc.prototype.getIndexManager=function(){return xr(this.started,"Cannot initialize IndexManager before persistence is started."),this.indexManager},cc.prototype.runTransaction=function(n,t,r){var i=this;return _r(rc,"Starting transaction:",n),this.simpleDb.runTransaction("readonly"===t?"readonly":"readwrite",Fu,function(e){return"readwrite-primary"===t?i.verifyPrimaryLease(e).next(function(t){if(!t)throw Or("Failed to obtain primary lease for action '"+n+"'."),i.isPrimary=!1,i.queue.enqueueAndForget(function(){return i.primaryStateListener(!1)}),new Qr(Ur.FAILED_PRECONDITION,ic);return r(new ac(e,i.listenSequence.next()))}).next(function(t){return i.acquireOrExtendPrimaryLease(e).next(function(){return t})}):i.verifyAllowTabSynchronization(e).next(function(){return r(new ac(e,i.listenSequence.next()))})})},cc.prototype.verifyAllowTabSynchronization=function(t){var e=this;return lc(t).get(cu.key).next(function(t){if(null!==t&&e.isWithinAge(t.leaseTimestampMs,5e3)&&!e.isClientZombied(t.ownerId)&&!e.isLocalClient(t)&&!t.allowTabSynchronization)throw new Qr(Ur.FAILED_PRECONDITION,oc)})},cc.prototype.acquireOrExtendPrimaryLease=function(t){var e=new cu(this.clientId,this.allowTabSynchronization,Date.now());return lc(t).put(cu.key,e)},cc.isAvailable=function(){return Xo.isAvailable()},cc.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},cc.prototype.releasePrimaryLeaseIfHeld=function(t){var e=this,n=lc(t);return n.get(cu.key).next(function(t){return e.isLocalClient(t)?(_r(rc,"Releasing primary lease."),n.delete(cu.key)):Lo.resolve()})},cc.prototype.isWithinAge=function(t,e){var n=Date.now();return!(t<n-e||n<t&&(Or("Detected an update time that is in the future: "+t+" > "+n),1))},cc.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)},cc.prototype.detachVisibilityHandler=function(){this.documentVisibilityHandler&&(xr(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.documentVisibilityHandler),this.documentVisibilityHandler=null)},cc.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))},cc.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(xr("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},cc.prototype.isClientZombied=function(t){try{var e=null!==this.webStorage.getItem(this.zombiedClientLocalStorageKey(t));return _r(rc,"Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return Or(rc,"Failed to get zombied client id.",t),!1}},cc.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(t){Or("Failed to set zombie client id.",t)}},cc.prototype.removeClientZombiedEntry=function(){try{this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId))}catch(t){}},cc.prototype.zombiedClientLocalStorageKey=function(t){return"firestore_zombie_"+this.persistenceKey+"_"+t},cc.MAIN_DATABASE="main",cc);function cc(t,e,n,r,i,o,a){if(this.persistenceKey=t,this.clientId=e,this.queue=r,this.multiClientParams=a,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.windowUnloadHandler=null,this.inForeground=!1,this.documentVisibilityHandler=null,this.clientMetadataRefresher=null,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(t){return Promise.resolve()},!cc.isAvailable())throw new Qr(Ur.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");if(this.referenceDelegate=new pc(this,o),this.dbName=t+cc.MAIN_DATABASE,this.serializer=new ju(i),this.document=n.document,this.allowTabSynchronization=void 0!==a,this.queryCache=new sa(this.referenceDelegate,this.serializer),this.indexManager=new Vu,this.remoteDocumentCache=new zs(this.serializer,this.indexManager,this.allowTabSynchronization),!n.window||!n.window.localStorage)throw new Qr(Ur.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=n.window,this.webStorage=this.window.localStorage}function hc(e){return p(this,void 0,void 0,function(){return d(this,function(t){if(!function(t){return t.code===Ur.FAILED_PRECONDITION&&t.message===ic}(e))throw e;return _r(rc,"Unexpectedly lost primary lease"),[2]})})}function lc(t){return t.store(cu.store)}function fc(t){return t.store(Pu.store)}var pc=(dc.prototype.getSequenceNumberCount=function(t){var n=this.orphanedDocmentCount(t);return this.db.getQueryCache().getQueryCount(t).next(function(e){return n.next(function(t){return e+t})})},dc.prototype.orphanedDocmentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,function(t){e++}).next(function(){return e})},dc.prototype.forEachTarget=function(t,e){return this.db.getQueryCache().forEachTarget(t,e)},dc.prototype.forEachOrphanedDocumentSequenceNumber=function(t,n){return this.forEachOrphanedDocument(t,function(t,e){return n(e)})},dc.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},dc.prototype.addReference=function(t,e){return mc(t,e)},dc.prototype.removeReference=function(t,e){return mc(t,e)},dc.prototype.removeTargets=function(t,e,n){return this.db.getQueryCache().removeTargets(t,e,n)},dc.prototype.removeMutationReference=function(t,e){return mc(t,e)},dc.prototype.isPinned=function(t,e){return this.inMemoryPins.containsKey(e)?Lo.resolve(!0):function(e,n){var r=!1;return jo(e).iterateSerial(function(t){return Vo(e,t,n).next(function(t){return t&&(r=!0),Lo.resolve(!t)})}).next(function(){return r})}(t,e)},dc.prototype.removeOrphanedDocuments=function(r,i){var o=this,a=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[],u=0;return this.forEachOrphanedDocument(r,function(e,t){if(t<=i){var n=o.isPinned(r,e).next(function(t){if(!t)return u++,a.getEntry(r,e).next(function(){return a.removeEntry(e),fa(r).delete(function(t){return[0,Zi(t.path)]}(e))})});s.push(n)}}).next(function(){return Lo.waitFor(s)}).next(function(){return a.apply(r)}).next(function(){return u})},dc.prototype.removeTarget=function(t,e){var n=e.copy({sequenceNumber:t.currentSequenceNumber});return this.db.getQueryCache().updateQueryData(t,n)},dc.prototype.updateLimboDocument=function(t,e){return mc(t,e)},dc.prototype.forEachOrphanedDocument=function(t,o){var a,e=fa(t),s=Ai.INVALID;return e.iterate({index:Cu.documentTargetsIndex},function(t,e){var n=t[0],r=(t[1],e.path),i=e.sequenceNumber;0===n?(s!==Ai.INVALID&&o(new Bi(no(a)),s),s=i,a=r):s=Ai.INVALID}).next(function(){s!==Ai.INVALID&&o(new Bi(no(a)),s)})},dc.prototype.getCacheSize=function(t){return this.db.getRemoteDocumentCache().getSize(t)},dc);function dc(t,e){this.db=t,this.inMemoryPins=null,this.garbageCollector=new tc(this,e)}function mc(t,e){return fa(t).put(function(t,e){return new Cu(0,Zi(t.path),e)}(e,t.currentSequenceNumber))}var yc=(gc.prototype.getDocument=function(e,n){var r=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(e,n).next(function(t){return r.getDocumentInternal(e,n,t)})},gc.prototype.getDocumentInternal=function(t,r,i){return this.remoteDocumentCache.getEntry(t,r).next(function(t){for(var e=0,n=i;e<n.length;e++)t=n[e].applyToLocalView(r,t);return t})},gc.prototype.applyLocalMutationsToDocuments=function(t,e,i){var o=So();return e.forEach(function(t,e){for(var n=0,r=i;n<r.length;n++)e=r[n].applyToLocalView(t,e);o=o.insert(t,e)}),o},gc.prototype.getDocuments=function(e,t){var n=this;return this.remoteDocumentCache.getEntries(e,t).next(function(t){return n.getLocalViewOfDocuments(e,t)})},gc.prototype.getLocalViewOfDocuments=function(r,i){var o=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(r,i).next(function(t){var e=o.applyLocalMutationsToDocuments(r,i,t),n=Eo();return e.forEach(function(t,e){e=e||new xs(t,oo.forDeletedDoc()),n=n.insert(t,e)}),n})},gc.prototype.getDocumentsMatchingQuery=function(t,e){return e.isDocumentQuery()?this.getDocumentsMatchingDocumentQuery(t,e.path):e.isCollectionGroupQuery()?this.getDocumentsMatchingCollectionGroupQuery(t,e):this.getDocumentsMatchingCollectionQuery(t,e)},gc.prototype.getDocumentsMatchingDocumentQuery=function(t,e){return this.getDocument(t,new Bi(e)).next(function(t){var e=Io();return t instanceof Os&&(e=e.insert(t.key,t)),e})},gc.prototype.getDocumentsMatchingCollectionGroupQuery=function(n,r){var i=this;xr(r.path.isEmpty(),"Currently we only support collection group queries at the root.");var o=r.collectionGroup,a=Io();return this.indexManager.getCollectionParents(n,o).next(function(t){return Lo.forEach(t,function(t){var e=r.asCollectionQueryAtPath(t.child(o));return i.getDocumentsMatchingCollectionQuery(n,e).next(function(t){t.forEach(function(t,e){a=a.insert(t,e)})})}).next(function(){return a})})},gc.prototype.getDocumentsMatchingCollectionQuery=function(e,n){var h,l,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(e,n).next(function(t){return h=t,r.mutationQueue.getAllMutationBatchesAffectingQuery(e,n)}).next(function(t){return l=t,r.addMissingBaseDocuments(e,l,h).next(function(t){h=t;for(var e=0,n=l;e<n.length;e++)for(var r=n[e],i=0,o=r.mutations;i<o.length;i++){var a=o[i],s=a.key,u=h.get(s),c=a.applyToLocalView(u,u,r.localWriteTime);h=c instanceof Os?h.insert(s,c):h.remove(s)}})}).next(function(){return h.forEach(function(t,e){n.matches(e)||(h=h.remove(t))}),h})},gc.prototype.addMissingBaseDocuments=function(t,e,n){for(var r=Ao(),i=0,o=e;i<o.length;i++)for(var a=0,s=o[i].mutations;a<s.length;a++){var u=s[a];u instanceof Aa&&null===n.get(u.key)&&(r=r.add(u.key))}var c=n;return this.remoteDocumentCache.getEntries(t,r).next(function(t){return t.forEach(function(t,e){null!==e&&e instanceof Os&&(c=c.insert(t,e))}),c})},gc);function gc(t,e,n){this.remoteDocumentCache=t,this.mutationQueue=e,this.indexManager=n}var vc=(bc.prototype.isEmpty=function(){return this.refsByKey.isEmpty()},bc.prototype.addReference=function(t,e){var n=new wc(t,e);this.refsByKey=this.refsByKey.add(n),this.refsByTarget=this.refsByTarget.add(n)},bc.prototype.addReferences=function(t,e){var n=this;t.forEach(function(t){return n.addReference(t,e)})},bc.prototype.removeReference=function(t,e){this.removeRef(new wc(t,e))},bc.prototype.removeReferences=function(t,e){var n=this;t.forEach(function(t){return n.removeReference(t,e)})},bc.prototype.removeReferencesForId=function(t){var e=this,n=Bi.EMPTY,r=new wc(n,t),i=new wc(n,t+1),o=[];return this.refsByTarget.forEachInRange([r,i],function(t){e.removeRef(t),o.push(t.key)}),o},bc.prototype.removeAllReferences=function(){var e=this;this.refsByKey.forEach(function(t){return e.removeRef(t)})},bc.prototype.removeRef=function(t){this.refsByKey=this.refsByKey.delete(t),this.refsByTarget=this.refsByTarget.delete(t)},bc.prototype.referencesForId=function(t){var e=Bi.EMPTY,n=new wc(e,t),r=new wc(e,t+1),i=Ao();return this.refsByTarget.forEachInRange([n,r],function(t){i=i.add(t.key)}),i},bc.prototype.containsKey=function(t){var e=new wc(t,0),n=this.refsByKey.firstAfterOrEqual(e);return null!==n&&t.isEqual(n.key)},bc);function bc(){this.refsByKey=new yo(wc.compareByKey),this.refsByTarget=new yo(wc.compareByTargetId)}var wc=(Ec.compareByKey=function(t,e){return Bi.comparator(t.key,e.key)||yi(t.targetOrBatchId,e.targetOrBatchId)},Ec.compareByTargetId=function(t,e){return yi(t.targetOrBatchId,e.targetOrBatchId)||Bi.comparator(t.key,e.key)},Ec);function Ec(t,e){this.key=t,this.targetOrBatchId=e}var Sc=(Tc.prototype.handleUserChange=function(e){var y=this;return this.persistence.runTransaction("Handle user change","readonly",function(d){var m;return y.mutationQueue.getAllMutationBatches(d).next(function(t){return m=t,y.mutationQueue=y.persistence.getMutationQueue(e),y.localDocuments=new yc(y.remoteDocuments,y.mutationQueue,y.persistence.getIndexManager()),y.mutationQueue.getAllMutationBatches(d)}).next(function(t){for(var e=[],n=[],r=Ao(),i=0,o=m;i<o.length;i++){var a=o[i];e.push(a.batchId);for(var s=0,u=a.mutations;s<u.length;s++){var c=u[s];r=r.add(c.key)}}for(var h=0,l=t;h<l.length;h++){a=l[h],n.push(a.batchId);for(var f=0,p=a.mutations;f<p.length;f++)c=p[f],r=r.add(c.key)}return y.localDocuments.getDocuments(d,r).next(function(t){return{affectedDocuments:t,removedBatchIds:e,addedBatchIds:n}})})})},Tc.prototype.localWrite=function(s){var u=this,c=ro.now(),t=s.reduce(function(t,e){return t.add(e.key)},Ao());return this.persistence.runTransaction("Locally write mutations","readwrite",function(a){return u.localDocuments.getDocuments(a,t).next(function(n){for(var t=[],e=0,r=s;e<r.length;e++){var i=r[e],o=i.extractBaseValue(n.get(i.key));null!=o&&t.push(new Aa(i.key,o,o.fieldMask(),wa.exists(!0)))}return u.mutationQueue.addMutationBatch(a,c,t,s).next(function(t){var e=t.applyToLocalDocumentSet(n);return{batchId:t.batchId,changes:e}})})})},Tc.prototype.lookupMutationDocuments=function(t){var n=this;return this.persistence.runTransaction("Lookup mutation documents","readonly",function(e){return n.mutationQueue.lookupMutationKeys(e,t).next(function(t){return t?n.localDocuments.getDocuments(e,t):Lo.resolve(null)})})},Tc.prototype.acknowledgeBatch=function(r){var i=this;return this.persistence.runTransaction("Acknowledge batch","readwrite-primary",function(t){var e=r.batch.keys(),n=i.remoteDocuments.newChangeBuffer();return i.mutationQueue.acknowledgeBatch(t,r.batch,r.streamToken).next(function(){return i.applyWriteToRemoteDocuments(t,r,n)}).next(function(){return n.apply(t)}).next(function(){return i.mutationQueue.performConsistencyCheck(t)}).next(function(){return i.localDocuments.getDocuments(t,e)})})},Tc.prototype.rejectBatch=function(t){var r=this;return this.persistence.runTransaction("Reject batch","readwrite-primary",function(e){var n;return r.mutationQueue.lookupMutationBatch(e,t).next(function(t){return xr(null!==t,"Attempt to reject nonexistent batch!"),n=t.keys(),r.mutationQueue.removeMutationBatch(e,t)}).next(function(){return r.mutationQueue.performConsistencyCheck(e)}).next(function(){return r.localDocuments.getDocuments(e,n)})})},Tc.prototype.getHighestUnacknowledgedBatchId=function(){var e=this;return this.persistence.runTransaction("Get highest unacknowledged batch id","readonly",function(t){return e.mutationQueue.getHighestUnacknowledgedBatchId(t)})},Tc.prototype.getLastStreamToken=function(){var e=this;return this.persistence.runTransaction("Get last stream token","readonly",function(t){return e.mutationQueue.getLastStreamToken(t)})},Tc.prototype.setLastStreamToken=function(e){var n=this;return this.persistence.runTransaction("Set last stream token","readwrite-primary",function(t){return n.mutationQueue.setLastStreamToken(t,e)})},Tc.prototype.getLastRemoteSnapshotVersion=function(){var e=this;return this.persistence.runTransaction("Get last remote snapshot version","readonly",function(t){return e.queryCache.getLastRemoteSnapshotVersion(t)})},Tc.prototype.applyRemoteEvent=function(s){var u=this,c=this.remoteDocuments.newChangeBuffer(),h=s.snapshotVersion;return this.persistence.runTransaction("Apply remote event","readwrite-primary",function(o){var a=[];zr(s.targetChanges,function(t,e){var n=u.queryDataByTarget[t];if(n){a.push(u.queryCache.removeMatchingKeys(o,e.removedDocuments,t).next(function(){return u.queryCache.addMatchingKeys(o,e.addedDocuments,t)}));var r=e.resumeToken;if(0<r.length){var i=n.copy({resumeToken:r,snapshotVersion:h});u.queryDataByTarget[t]=i,Tc.shouldPersistQueryData(n,i,e)&&a.push(u.queryCache.updateQueryData(o,i))}}});var i=Eo(),n=Ao();if(s.documentUpdates.forEach(function(t,e){n=n.add(t)}),a.push(c.getEntries(o,n).next(function(r){s.documentUpdates.forEach(function(t,e){var n=r.get(t);null==n||0<e.version.compareTo(n.version)||0===e.version.compareTo(n.version)&&n.hasPendingWrites?(c.addEntry(e),i=i.insert(t,e)):e instanceof xs&&e.version.isEqual(oo.MIN)?(c.removeEntry(t),i=i.insert(t,e)):_r("LocalStore","Ignoring outdated watch update for ",t,". Current version:",n.version," Watch version:",e.version),s.resolvedLimboDocuments.has(t)&&a.push(u.persistence.referenceDelegate.updateLimboDocument(o,t))})})),!h.isEqual(oo.MIN)){var t=u.queryCache.getLastRemoteSnapshotVersion(o).next(function(t){return xr(0<=h.compareTo(t),"Watch stream reverted to previous snapshot?? "+h+" < "+t),u.queryCache.setTargetsMetadata(o,o.currentSequenceNumber,h)});a.push(t)}return Lo.waitFor(a).next(function(){return c.apply(o)}).next(function(){return u.localDocuments.getLocalViewOfDocuments(o,i)})})},Tc.shouldPersistQueryData=function(t,e,n){return xr(0<e.resumeToken.length,"Attempted to persist query data with no resume token"),0===t.resumeToken.length||e.snapshotVersion.toMicroseconds()-t.snapshotVersion.toMicroseconds()>=this.RESUME_TOKEN_MAX_AGE_MICROS||0<n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size},Tc.prototype.notifyLocalViewChanges=function(t){var n=this;return this.persistence.runTransaction("notifyLocalViewChanges","readwrite",function(e){return Lo.forEach(t,function(t){return n.localViewReferences.addReferences(t.addedKeys,t.targetId),n.localViewReferences.removeReferences(t.removedKeys,t.targetId),Lo.forEach(t.removedKeys,function(t){return n.persistence.referenceDelegate.removeReference(e,t)})})})},Tc.prototype.nextMutationBatch=function(e){var n=this;return this.persistence.runTransaction("Get next mutation batch","readonly",function(t){return void 0===e&&(e=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(t,e)})},Tc.prototype.readDocument=function(e){var n=this;return this.persistence.runTransaction("read document","readonly",function(t){return n.localDocuments.getDocument(t,e)})},Tc.prototype.allocateQuery=function(r){var i=this;return this.persistence.runTransaction("Allocate query","readwrite",function(e){var n;return i.queryCache.getQueryData(e,r).next(function(t){return t?(n=t,Lo.resolve()):i.queryCache.allocateTargetId(e).next(function(t){return n=new Qu(r,t,xu.Listen,e.currentSequenceNumber),i.queryCache.addQueryData(e,n)})}).next(function(){return xr(!i.queryDataByTarget[n.targetId],"Tried to allocate an already allocated query: "+r),i.queryDataByTarget[n.targetId]=n})})},Tc.prototype.releaseQuery=function(o,a){var s=this,t=a?"readwrite":"readwrite-primary";return this.persistence.runTransaction("Release query",t,function(i){return s.queryCache.getQueryData(i,o).next(function(t){xr(null!=t,"Tried to release nonexistent query: "+o);var e=t.targetId,n=s.queryDataByTarget[e],r=s.localViewReferences.removeReferencesForId(e);return delete s.queryDataByTarget[e],a?Lo.resolve():Lo.forEach(r,function(t){return s.persistence.referenceDelegate.removeReference(i,t)}).next(function(){return s.persistence.referenceDelegate.removeTarget(i,n)})})})},Tc.prototype.executeQuery=function(e){var n=this;return this.persistence.runTransaction("Execute query","readonly",function(t){return n.localDocuments.getDocumentsMatchingQuery(t,e)})},Tc.prototype.remoteDocumentKeys=function(e){var n=this;return this.persistence.runTransaction("Remote document keys","readonly",function(t){return n.queryCache.getMatchingKeysForTargetId(t,e)})},Tc.prototype.getActiveClients=function(){return this.persistence.getActiveClients()},Tc.prototype.removeCachedMutationBatchMetadata=function(t){this.mutationQueue.removeCachedMutationKeys(t)},Tc.prototype.setNetworkEnabled=function(t){this.persistence.setNetworkEnabled(t)},Tc.prototype.applyWriteToRemoteDocuments=function(t,i,o){var e=this,a=i.batch,n=a.keys(),s=Lo.resolve();return n.forEach(function(r){s=s.next(function(){return o.getEntry(t,r)}).next(function(t){var e=t,n=i.docVersions.get(r);xr(null!==n,"ackVersions should contain every doc in the write."),(!e||e.version.compareTo(n)<0)&&((e=a.applyToRemoteDocument(r,e,i))?o.addEntry(e):xr(!t,"Mutation batch "+a+" applied to document "+t+" resulted in null"))})}),s.next(function(){return e.mutationQueue.removeMutationBatch(t,a)})},Tc.prototype.collectGarbage=function(e){var n=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary",function(t){return e.collect(t,n.queryDataByTarget)})},Tc.prototype.getQueryForTarget=function(e){var n=this;return this.queryDataByTarget[e]?Promise.resolve(this.queryDataByTarget[e].query):this.persistence.runTransaction("Get query data","readonly",function(t){return n.queryCache.getQueryDataForTarget(t,e).next(function(t){return t?t.query:null})})},Tc.prototype.getNewDocumentChanges=function(){var e=this;return this.persistence.runTransaction("Get new document changes","readonly",function(t){return e.remoteDocuments.getNewDocumentChanges(t)})},Tc.RESUME_TOKEN_MAX_AGE_MICROS=3e8,Tc);function Tc(t,e){this.persistence=t,this.localViewReferences=new vc,this.queryDataByTarget={},xr(t.started,"LocalStore was passed an unstarted persistence implementation"),this.persistence.referenceDelegate.setInMemoryPins(this.localViewReferences),this.mutationQueue=t.getMutationQueue(e),this.remoteDocuments=t.getRemoteDocumentCache(),this.queryCache=t.getQueryCache(),this.localDocuments=new yc(this.remoteDocuments,this.mutationQueue,this.persistence.getIndexManager())}var Ic=(Cc.prototype.checkEmpty=function(t){return Lo.resolve(0===this.mutationQueue.length)},Cc.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId,i=this.indexOfExistingBatchId(r,"acknowledged");xr(0===i,"Can only acknowledge the first batch in the mutation queue");var o=this.mutationQueue[i];return xr(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),this.lastStreamToken=n,Lo.resolve()},Cc.prototype.getLastStreamToken=function(t){return Lo.resolve(this.lastStreamToken)},Cc.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,Lo.resolve()},Cc.prototype.addMutationBatch=function(t,e,n,r){xr(0!==r.length,"Mutation batches should not be empty");var i=this.nextBatchId;this.nextBatchId++,0<this.mutationQueue.length&&xr(this.mutationQueue[this.mutationQueue.length-1].batchId<i,"Mutation batchIDs must be monotonically increasing order");var o=new Mo(i,e,n,r);this.mutationQueue.push(o);for(var a=0,s=r;a<s.length;a++){var u=s[a];this.batchesByDocumentKey=this.batchesByDocumentKey.add(new wc(u.key,i)),this.indexManager.addToCollectionParentIndex(t,u.key.path.popLast())}return Lo.resolve(o)},Cc.prototype.lookupMutationBatch=function(t,e){return Lo.resolve(this.findMutationBatch(e))},Cc.prototype.lookupMutationKeys=function(t,e){var n=this.findMutationBatch(e);return xr(null!=n,"Failed to find local mutation batch."),Lo.resolve(n.keys())},Cc.prototype.getNextMutationBatchAfterBatchId=function(t,e){var n=e+1,r=this.indexOfBatchId(n),i=r<0?0:r;return Lo.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)},Cc.prototype.getHighestUnacknowledgedBatchId=function(){return Lo.resolve(0===this.mutationQueue.length?-1:this.nextBatchId-1)},Cc.prototype.getAllMutationBatches=function(t){return Lo.resolve(this.mutationQueue.slice())},Cc.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,n){var r=this,e=new wc(n,0),i=new wc(n,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([e,i],function(t){xr(n.isEqual(t.key),"Should only iterate over a single key's batches");var e=r.findMutationBatch(t.targetOrBatchId);xr(null!==e,"Batches in the index must exist in the main table"),o.push(e)}),Lo.resolve(o)},Cc.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var r=this,i=new yo(yi);return e.forEach(function(e){var t=new wc(e,0),n=new wc(e,Number.POSITIVE_INFINITY);r.batchesByDocumentKey.forEachInRange([t,n],function(t){xr(e.isEqual(t.key),"For each key, should only iterate over a single key's batches"),i=i.add(t.targetOrBatchId)})}),Lo.resolve(this.findMutationBatches(i))},Cc.prototype.getAllMutationBatchesAffectingQuery=function(t,e){xr(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var n=e.path,r=n.length+1,i=n;Bi.isDocumentKey(i)||(i=i.child(""));var o=new wc(new Bi(i),0),a=new yo(yi);return this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(a=a.add(t.targetOrBatchId)),!0)},o),Lo.resolve(this.findMutationBatches(a))},Cc.prototype.findMutationBatches=function(t){var n=this,r=[];return t.forEach(function(t){var e=n.findMutationBatch(t);null!==e&&r.push(e)}),r},Cc.prototype.removeMutationBatch=function(n,r){var i=this;xr(0===this.indexOfExistingBatchId(r.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.mutationQueue.shift();var o=this.batchesByDocumentKey;return Lo.forEach(r.mutations,function(t){var e=new wc(t.key,r.batchId);return o=o.delete(e),i.referenceDelegate.removeMutationReference(n,t.key)}).next(function(){i.batchesByDocumentKey=o})},Cc.prototype.removeCachedMutationKeys=function(t){},Cc.prototype.containsKey=function(t,e){var n=new wc(e,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return Lo.resolve(e.isEqual(r&&r.key))},Cc.prototype.performConsistencyCheck=function(t){return 0===this.mutationQueue.length&&xr(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),Lo.resolve()},Cc.prototype.indexOfExistingBatchId=function(t,e){var n=this.indexOfBatchId(t);return xr(0<=n&&n<this.mutationQueue.length,"Batches must exist to be "+e),n},Cc.prototype.indexOfBatchId=function(t){return 0===this.mutationQueue.length?0:t-this.mutationQueue[0].batchId},Cc.prototype.findMutationBatch=function(t){var e=this.indexOfBatchId(t);if(e<0||e>=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return xr(n.batchId===t,"If found batch must match"),n},Cc);function Cc(t,e){this.indexManager=t,this.referenceDelegate=e,this.mutationQueue=[],this.nextBatchId=1,this.lastStreamToken=Vr(),this.batchesByDocumentKey=new yo(wc.compareByKey)}var Dc=(Nc.prototype.getTargetCount=function(t){return Lo.resolve(this.targetCount)},Nc.prototype.forEachTarget=function(t,n){return this.queries.forEach(function(t,e){return n(e)}),Lo.resolve()},Nc.prototype.getLastRemoteSnapshotVersion=function(t){return Lo.resolve(this.lastRemoteSnapshotVersion)},Nc.prototype.getHighestSequenceNumber=function(t){return Lo.resolve(this.highestSequenceNumber)},Nc.prototype.allocateTargetId=function(t){var e=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=e,Lo.resolve(e)},Nc.prototype.setTargetsMetadata=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.highestSequenceNumber&&(this.highestSequenceNumber=e),Lo.resolve()},Nc.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)},Nc.prototype.addQueryData=function(t,e){return xr(!this.queries.has(e.query),"Adding a query that already exists"),this.saveQueryData(e),this.targetCount+=1,Lo.resolve()},Nc.prototype.updateQueryData=function(t,e){return xr(this.queries.has(e.query),"Updating a non-existent query"),this.saveQueryData(e),Lo.resolve()},Nc.prototype.removeQueryData=function(t,e){return xr(0<this.targetCount,"Removing a target from an empty cache"),xr(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,Lo.resolve()},Nc.prototype.removeTargets=function(n,r,i){var o=this,a=0,s=[];return this.queries.forEach(function(t,e){e.sequenceNumber<=r&&!i[e.targetId]&&(o.queries.delete(t),s.push(o.removeMatchingKeysForTargetId(n,e.targetId)),a++)}),Lo.waitFor(s).next(function(){return a})},Nc.prototype.getQueryCount=function(t){return Lo.resolve(this.targetCount)},Nc.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return Lo.resolve(n)},Nc.prototype.getQueryDataForTarget=function(t,e){return Lr("Not yet implemented.")},Nc.prototype.addMatchingKeys=function(e,t,n){this.references.addReferences(t,n);var r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(function(t){i.push(r.addReference(e,t))}),Lo.waitFor(i)},Nc.prototype.removeMatchingKeys=function(e,t,n){this.references.removeReferences(t,n);var r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(function(t){i.push(r.removeReference(e,t))}),Lo.waitFor(i)},Nc.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),Lo.resolve()},Nc.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return Lo.resolve(n)},Nc.prototype.containsKey=function(t,e){return Lo.resolve(this.references.containsKey(e))},Nc);function Nc(t){this.persistence=t,this.queries=new Us(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=oo.MIN,this.highestTargetId=0,this.highestSequenceNumber=0,this.references=new vc,this.targetCount=0,this.targetIdGenerator=zo.forQueryCache()}var Ac,kc=(Rc.prototype.addEntry=function(t,e){var n=e.key,r=this.docs.get(n),i=r?r.size:0,o=this.sizer(e);return this.docs=this.docs.insert(n,{maybeDocument:e,size:o}),this.newDocumentChanges=this.newDocumentChanges.add(n),this.size+=o-i,this.indexManager.addToCollectionParentIndex(t,n.path.popLast())},Rc.prototype.removeEntry=function(t){var e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)},Rc.prototype.getEntry=function(t,e){var n=this.docs.get(e);return Lo.resolve(n?n.maybeDocument:null)},Rc.prototype.getEntries=function(t,e){var n=this,r=So();return e.forEach(function(t){var e=n.docs.get(t);r=r.insert(t,e?e.maybeDocument:null)}),Lo.resolve(r)},Rc.prototype.getDocumentsMatchingQuery=function(t,e){xr(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");for(var n=Io(),r=new Bi(e.path.child("")),i=this.docs.getIteratorFrom(r);i.hasNext();){var o=i.getNext(),a=o.key,s=o.value.maybeDocument;if(!e.path.isPrefixOf(a.path))break;s instanceof Os&&e.matches(s)&&(n=n.insert(s.key,s))}return Lo.resolve(n)},Rc.prototype.forEachDocumentKey=function(t,e){return Lo.forEach(this.docs,function(t){return e(t)})},Rc.prototype.getNewDocumentChanges=function(t){var r=this,i=Eo();return this.newDocumentChanges.forEach(function(t){var e=r.docs.get(t),n=e?e.maybeDocument:new xs(t,oo.forDeletedDoc());i=i.insert(t,n)}),this.newDocumentChanges=Ao(),Lo.resolve(i)},Rc.prototype.newChangeBuffer=function(){return new Rc.RemoteDocumentChangeBuffer(this)},Rc.prototype.getSize=function(t){return Lo.resolve(this.size)},Rc.RemoteDocumentChangeBuffer=(s(Mc,Ac=Ks),Mc.prototype.applyChanges=function(n){var r=this,i=[];return this.changes.forEach(function(t,e){e?i.push(r.documentCache.addEntry(n,e)):r.documentCache.removeEntry(t)}),Lo.waitFor(i)},Mc.prototype.getFromCache=function(t,e){return this.documentCache.getEntry(t,e)},Mc.prototype.getAllFromCache=function(t,e){return this.documentCache.getEntries(t,e)},Mc),Rc);function Rc(t,e){this.indexManager=t,this.sizer=e,this.docs=new so(Bi.comparator),this.newDocumentChanges=Ao(),this.size=0}function Mc(t){var e=Ac.call(this)||this;return e.documentCache=t,e}var _c=(Oc.createLruPersistence=function(t,e,n){return new Oc(t,function(t){return new qc(t,new ju(e),n)})},Oc.createEagerPersistence=function(t){return new Oc(t,function(t){return new Lc(t)})},Oc.prototype.shutdown=function(){return this._started=!1,Promise.resolve()},Object.defineProperty(Oc.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),Oc.prototype.getActiveClients=function(){return p(this,void 0,void 0,function(){return d(this,function(t){return[2,[this.clientId]]})})},Oc.prototype.setPrimaryStateListener=function(t){return t(!0)},Oc.prototype.setDatabaseDeletedListener=function(){},Oc.prototype.setNetworkEnabled=function(t){},Oc.prototype.getIndexManager=function(){return this.indexManager},Oc.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new Ic(this.indexManager,this.referenceDelegate),this.mutationQueues[t.toKey()]=e),e},Oc.prototype.getQueryCache=function(){return this.queryCache},Oc.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},Oc.prototype.runTransaction=function(t,e,n){var r=this;_r("MemoryPersistence","Starting transaction:",t);var i=new Pc(this.listenSequence.next());return this.referenceDelegate.onTransactionStarted(),n(i).next(function(t){return r.referenceDelegate.onTransactionCommitted(i).next(function(){return t})}).toPromise()},Oc.prototype.mutationQueuesContainKey=function(e,n){return Lo.or(function(t){var n=[];return Hr(t,function(t,e){return n.push(e)}),n}(this.mutationQueues).map(function(t){return function(){return t.containsKey(e,n)}}))},Oc);function Oc(t,e){var n=this;this.clientId=t,this.mutationQueues={},this.listenSequence=new Ai(0),this._started=!1,this._started=!0,this.referenceDelegate=e(this),this.queryCache=new Dc(this);this.indexManager=new eu,this.remoteDocumentCache=new kc(this.indexManager,function(t){return n.referenceDelegate.documentSize(t)})}var Pc=function(t){this.currentSequenceNumber=t},Lc=(Object.defineProperty(xc.prototype,"orphanedDocuments",{get:function(){if(this._orphanedDocuments)return this._orphanedDocuments;throw Lr("orphanedDocuments is only valid during a transaction.")},enumerable:!0,configurable:!0}),xc.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},xc.prototype.addReference=function(t,e){return this.orphanedDocuments.delete(e),Lo.resolve()},xc.prototype.removeReference=function(t,e){return this.orphanedDocuments.add(e),Lo.resolve()},xc.prototype.removeMutationReference=function(t,e){return this.orphanedDocuments.add(e),Lo.resolve()},xc.prototype.removeTarget=function(t,e){var n=this,r=this.persistence.getQueryCache();return r.getMatchingKeysForTargetId(t,e.targetId).next(function(t){t.forEach(function(t){return n.orphanedDocuments.add(t)})}).next(function(){return r.removeQueryData(t,e)})},xc.prototype.onTransactionStarted=function(){this._orphanedDocuments=new Set},xc.prototype.onTransactionCommitted=function(t){var n=this,r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Lo.forEach(this.orphanedDocuments,function(e){return n.isReferenced(t,e).next(function(t){t||r.removeEntry(e)})}).next(function(){return n._orphanedDocuments=null,r.apply(t)})},xc.prototype.updateLimboDocument=function(t,e){var n=this;return this.isReferenced(t,e).next(function(t){t?n.orphanedDocuments.delete(e):n.orphanedDocuments.add(e)})},xc.prototype.documentSize=function(t){return 0},xc.prototype.isReferenced=function(t,e){var n=this;return Lo.or([function(){return n.persistence.getQueryCache().containsKey(t,e)},function(){return n.persistence.mutationQueuesContainKey(t,e)},function(){return Lo.resolve(n.inMemoryPins.containsKey(e))}])},xc);function xc(t){this.persistence=t,this.inMemoryPins=null,this._orphanedDocuments=null}var qc=(Fc.prototype.onTransactionStarted=function(){},Fc.prototype.onTransactionCommitted=function(t){return Lo.resolve()},Fc.prototype.forEachTarget=function(t,e){return this.persistence.getQueryCache().forEachTarget(t,e)},Fc.prototype.getSequenceNumberCount=function(t){var n=this.orphanedDocumentCount(t);return this.persistence.getQueryCache().getTargetCount(t).next(function(e){return n.next(function(t){return e+t})})},Fc.prototype.orphanedDocumentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,function(t){e++}).next(function(){return e})},Fc.prototype.forEachOrphanedDocumentSequenceNumber=function(n,r){var i=this;return Lo.forEach(this.orphanedSequenceNumbers,function(t,e){return i.isPinned(n,t,e).next(function(t){return t?Lo.resolve():r(e)})})},Fc.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},Fc.prototype.removeTargets=function(t,e,n){return this.persistence.getQueryCache().removeTargets(t,e,n)},Fc.prototype.removeOrphanedDocuments=function(t,n){var r=this,i=0,e=this.persistence.getRemoteDocumentCache(),o=e.newChangeBuffer();return e.forEachDocumentKey(t,function(e){return r.isPinned(t,e,n).next(function(t){t||(i++,o.removeEntry(e))})}).next(function(){return o.apply(t)}).next(function(){return i})},Fc.prototype.removeMutationReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),Lo.resolve()},Fc.prototype.removeTarget=function(t,e){var n=e.copy({sequenceNumber:t.currentSequenceNumber});return this.persistence.getQueryCache().updateQueryData(t,n)},Fc.prototype.addReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),Lo.resolve()},Fc.prototype.removeReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),Lo.resolve()},Fc.prototype.updateLimboDocument=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),Lo.resolve()},Fc.prototype.documentSize=function(t){var e,n=this.serializer.toDbRemoteDocument(t);if(n.document)e=n.document;else if(n.unknownDocument)e=n.unknownDocument;else{if(!n.noDocument)throw Lr("Unknown remote document type");e=n.noDocument}return JSON.stringify(e).length},Fc.prototype.isPinned=function(t,e,n){var r=this;return Lo.or([function(){return r.persistence.mutationQueuesContainKey(t,e)},function(){return Lo.resolve(r.inMemoryPins.containsKey(e))},function(){return r.persistence.getQueryCache().containsKey(t,e)},function(){var t=r.orphanedSequenceNumbers.get(e);return Lo.resolve(void 0!==t&&n<t)}])},Fc.prototype.getCacheSize=function(t){return this.persistence.getRemoteDocumentCache().getSize(t)},Fc);function Fc(t,e,n){this.persistence=t,this.serializer=e,this.inMemoryPins=null,this.orphanedSequenceNumbers=new Us(function(t){return Zi(t.path)}),this.garbageCollector=new tc(this,n)}var Vc=Number,Bc=Vc.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),Uc=Vc.MAX_SAFE_INTEGER||Math.pow(2,53)-1,Qc=Vc.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function Kc(t){return null==t}function jc(t){return Qc(t)&&t<=Uc&&Bc<=t}var Wc=(Gc.prototype.reset=function(){this.currentBaseMs=0},Gc.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},Gc.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);0<this.currentBaseMs&&_r("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.currentBaseMs<this.initialDelayMs&&(this.currentBaseMs=this.initialDelayMs),this.currentBaseMs>this.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},Gc.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},Gc.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},Gc);function Gc(t,e,n,r,i){void 0===n&&(n=1e3),void 0===r&&(r=1.5),void 0===i&&(i=6e4),this.queue=t,this.timerId=e,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=i,this.currentBaseMs=0,this.timerPromise=null,this.lastAttemptTime=Date.now(),this.reset()}var zc,Hc,Yc="PersistentStream";(Hc=zc=zc||{})[Hc.Initial=0]="Initial",Hc[Hc.Starting=1]="Starting",Hc[Hc.Open=2]="Open",Hc[Hc.Error=3]="Error",Hc[Hc.Backoff=4]="Backoff";var Xc=(Jc.prototype.isStarted=function(){return this.state===zc.Starting||this.state===zc.Open||this.state===zc.Backoff},Jc.prototype.isOpen=function(){return this.state===zc.Open},Jc.prototype.start=function(){this.state!==zc.Error?(xr(this.state===zc.Initial,"Already started"),this.auth()):this.performBackoff()},Jc.prototype.stop=function(){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.isStarted()?[4,this.close(zc.Initial)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},Jc.prototype.inhibitBackoff=function(){xr(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=zc.Initial,this.backoff.reset()},Jc.prototype.markIdle=function(){var t=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,function(){return t.handleIdleCloseTimer()}))},Jc.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},Jc.prototype.handleIdleCloseTimer=function(){return p(this,void 0,void 0,function(){return d(this,function(t){return this.isOpen()?[2,this.close(zc.Initial)]:[2]})})},Jc.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},Jc.prototype.close=function(e,n){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return xr(this.isStarted(),"Only started streams should be closed."),xr(e===zc.Error||Kc(n),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,e!==zc.Error?this.backoff.reset():n&&n.code===Ur.RESOURCE_EXHAUSTED?(Or(n.toString()),Or("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):n&&n.code===Ur.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=e,[4,this.listener.onClose(n)];case 1:return t.sent(),[2]}})})},Jc.prototype.tearDown=function(){},Jc.prototype.auth=function(){var n=this;xr(this.state===zc.Initial,"Must be in initial state to auth"),this.state=zc.Starting;var t=this.getCloseGuardedDispatcher(this.closeCount),e=this.closeCount;this.credentialsProvider.getToken().then(function(t){n.closeCount===e&&n.startStream(t)},function(e){t(function(){var t=new Qr(Ur.UNKNOWN,"Fetching auth token failed: "+e.message);return n.handleStreamClose(t)})})},Jc.prototype.startStream=function(t){var e=this;xr(this.state===zc.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 xr(e.state===zc.Starting,"Expected stream to be in state Starting, but was "+e.state),e.state=zc.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)})})},Jc.prototype.performBackoff=function(){var t=this;xr(this.state===zc.Error,"Should only perform backoff when in Error state"),this.state=zc.Backoff,this.backoff.backoffAndRun(function(){return p(t,void 0,void 0,function(){return d(this,function(t){return xr(this.state===zc.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=zc.Initial,this.start(),xr(this.isStarted(),"PersistentStream should have started"),[2]})})})},Jc.prototype.handleStreamClose=function(t){return xr(this.isStarted(),"Can't handle server close on non-started stream"),_r(Yc,"close with error: "+t),this.stream=null,this.close(zc.Error,t)},Jc.prototype.getCloseGuardedDispatcher=function(e){var n=this;return function(t){n.queue.enqueueAndForget(function(){return n.closeCount===e?t():(_r(Yc,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}},Jc);function Jc(t,e,n,r,i,o){this.queue=t,this.idleTimerId=n,this.connection=r,this.credentialsProvider=i,this.listener=o,this.state=zc.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new Wc(t,e)}var $c,Zc=(s(th,$c=Xc),th.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},th.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},th.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)},th.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},th);function th(t,e,n,r,i){var o=$c.call(this,t,Qi.ListenStreamConnectionBackoff,Qi.ListenStreamIdle,e,n,i)||this;return o.serializer=r,o}var eh,nh=(s(rh,eh=Xc),Object.defineProperty(rh.prototype,"handshakeComplete",{get:function(){return this.handshakeComplete_},enumerable:!0,configurable:!0}),rh.prototype.start=function(){this.handshakeComplete_=!1,eh.prototype.start.call(this)},rh.prototype.tearDown=function(){this.handshakeComplete_&&this.writeMutations([])},rh.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},rh.prototype.onMessage=function(t){if(xr(!!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 xr(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},rh.prototype.writeHandshake=function(){xr(this.isOpen(),"Writing handshake requires an opened stream"),xr(!this.handshakeComplete_,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},rh.prototype.writeMutations=function(t){var e=this;xr(this.isOpen(),"Writing mutations requires an opened stream"),xr(this.handshakeComplete_,"Handshake must be complete before writing mutations"),xr(0<this.lastStreamToken.length,"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)},rh);function rh(t,e,n,r,i){var o=eh.call(this,t,Qi.WriteStreamConnectionBackoff,Qi.WriteStreamIdle,e,n,i)||this;return o.serializer=r,o.handshakeComplete_=!1,o.lastStreamToken=Vr(),o}var ih=(oh.prototype.newPersistentWriteStream=function(t){return new nh(this.queue,this.connection,this.credentials,this.serializer,t)},oh.prototype.newPersistentWatchStream=function(t){return new Zc(this.queue,this.connection,this.credentials,this.serializer,t)},oh.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)})},oh.prototype.lookup=function(e){var i=this,t={database:this.serializer.encodedDatabaseId,documents:e.map(function(t){return i.serializer.toName(t)})};return this.invokeStreamingRPC("BatchGetDocuments",t).then(function(t){var n=Eo();t.forEach(function(t){var e=i.serializer.fromMaybeDocument(t);n=n.insert(e.key,e)});var r=[];return e.forEach(function(t){var e=n.get(t);xr(!!e,"Missing entity in write response for "+t),r.push(e)}),r})},oh.prototype.invokeRPC=function(e,n){var r=this;return this.credentials.getToken().then(function(t){return r.connection.invokeRPC(e,n,t)}).catch(function(t){throw t.code===Ur.UNAUTHENTICATED&&r.credentials.invalidateToken(),t})},oh.prototype.invokeStreamingRPC=function(e,n){var r=this;return this.credentials.getToken().then(function(t){return r.connection.invokeStreamingRPC(e,n,t)}).catch(function(t){throw t.code===Ur.UNAUTHENTICATED&&r.credentials.invalidateToken(),t})},oh);function oh(t,e,n,r){this.queue=t,this.connection=e,this.credentials=n,this.serializer=r}var ah,sh,uh,ch,hh=(lh.prototype.lookup=function(r){return p(this,void 0,void 0,function(){var e,n=this;return d(this,function(t){switch(t.label){case 0:if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new Qr(Ur.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");return[4,this.datastore.lookup(r)];case 1:return(e=t.sent()).forEach(function(t){t instanceof xs||t instanceof Os?n.recordVersion(t):Lr("Document in a transaction was a "+t.constructor.name)}),[2,e]}})})},lh.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t))),this.writtenDocs.add(t)},lh.prototype.update=function(t,e){try{this.write(e.toMutations(t,this.preconditionForUpdate(t)))}catch(t){this.lastWriteError=t}this.writtenDocs.add(t)},lh.prototype.delete=function(t){this.write([new Fa(t,this.precondition(t))]),this.writtenDocs.add(t)},lh.prototype.commit=function(){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;if(e=this.readVersions,this.mutations.forEach(function(t){e=e.remove(t.key)}),!e.isEmpty())throw new Qr(Ur.INVALID_ARGUMENT,"Every document read in a transaction must also be written.");return[4,this.datastore.commit(this.mutations)];case 1:return t.sent(),this.committed=!0,[2]}})})},lh.prototype.recordVersion=function(t){var e;if(t instanceof Os)e=t.version;else{if(!(t instanceof xs))throw Lr("Document in a transaction was a "+t.constructor.name);e=oo.forDeletedDoc()}var n=this.readVersions.get(t.key);if(null!==n){if(!e.isEqual(n))throw new Qr(Ur.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},lh.prototype.precondition=function(t){var e=this.readVersions.get(t);return!this.writtenDocs.has(t)&&e?wa.updateTime(e):wa.NONE},lh.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(this.writtenDocs.has(t)||!e)return wa.exists(!0);if(e.isEqual(oo.forDeletedDoc()))throw new Qr(Ur.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return wa.updateTime(e)},lh.prototype.write=function(t){this.ensureCommitNotCalled(),this.mutations=this.mutations.concat(t)},lh.prototype.ensureCommitNotCalled=function(){xr(!this.committed,"A transaction object cannot be used after its update callback has been invoked.")},lh);function lh(t){this.datastore=t,this.readVersions=Do(),this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}(sh=ah=ah||{})[sh.Unknown=0]="Unknown",sh[sh.Online=1]="Online",sh[sh.Offline=2]="Offline",(ch=uh=uh||{})[ch.RemoteStore=0]="RemoteStore",ch[ch.SharedClientState=1]="SharedClientState";var fh,ph,dh=(mh.prototype.handleWatchStreamStart=function(){var t=this;0===this.watchStreamFailures&&(this.setAndBroadcast(ah.Unknown),xr(null===this.onlineStateTimer,"onlineStateTimer shouldn't be started yet"),this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(Qi.OnlineStateTimeout,1e4,function(){return t.onlineStateTimer=null,xr(t.state===ah.Unknown,"Timer should be canceled if we transitioned to a different state."),t.logClientOfflineWarningIfNecessary("Backend didn't respond within 10 seconds."),t.setAndBroadcast(ah.Offline),Promise.resolve()}))},mh.prototype.handleWatchStreamFailure=function(t){this.state===ah.Online?(this.setAndBroadcast(ah.Unknown),xr(0===this.watchStreamFailures,"watchStreamFailures must be 0"),xr(null===this.onlineStateTimer,"onlineStateTimer must be null")):(this.watchStreamFailures++,1<=this.watchStreamFailures&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary("Connection failed 1 times. Most recent error: "+t.toString()),this.setAndBroadcast(ah.Offline)))},mh.prototype.set=function(t){this.clearOnlineStateTimer(),this.watchStreamFailures=0,t===ah.Online&&(this.shouldWarnClientIsOffline=!1),this.setAndBroadcast(t)},mh.prototype.setAndBroadcast=function(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))},mh.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?(Or(e),this.shouldWarnClientIsOffline=!1):_r("OnlineStateTracker",e)},mh.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},mh);function mh(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state=ah.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}function yh(t){switch(t){case Ur.OK:return Lr("Treated status OK as error");case Ur.CANCELLED:case Ur.UNKNOWN:case Ur.DEADLINE_EXCEEDED:case Ur.RESOURCE_EXHAUSTED:case Ur.INTERNAL:case Ur.UNAVAILABLE:case Ur.UNAUTHENTICATED:return!1;case Ur.INVALID_ARGUMENT:case Ur.NOT_FOUND:case Ur.ALREADY_EXISTS:case Ur.PERMISSION_DENIED:case Ur.FAILED_PRECONDITION:case Ur.ABORTED:case Ur.OUT_OF_RANGE:case Ur.UNIMPLEMENTED:case Ur.DATA_LOSS:return!0;default:return Lr("Unknown status code: "+t)}}function gh(t){if(void 0===t)return Or("GRPC error has no .code"),Ur.UNKNOWN;switch(t){case fh.OK:return Ur.OK;case fh.CANCELLED:return Ur.CANCELLED;case fh.UNKNOWN:return Ur.UNKNOWN;case fh.DEADLINE_EXCEEDED:return Ur.DEADLINE_EXCEEDED;case fh.RESOURCE_EXHAUSTED:return Ur.RESOURCE_EXHAUSTED;case fh.INTERNAL:return Ur.INTERNAL;case fh.UNAVAILABLE:return Ur.UNAVAILABLE;case fh.UNAUTHENTICATED:return Ur.UNAUTHENTICATED;case fh.INVALID_ARGUMENT:return Ur.INVALID_ARGUMENT;case fh.NOT_FOUND:return Ur.NOT_FOUND;case fh.ALREADY_EXISTS:return Ur.ALREADY_EXISTS;case fh.PERMISSION_DENIED:return Ur.PERMISSION_DENIED;case fh.FAILED_PRECONDITION:return Ur.FAILED_PRECONDITION;case fh.ABORTED:return Ur.ABORTED;case fh.OUT_OF_RANGE:return Ur.OUT_OF_RANGE;case fh.UNIMPLEMENTED:return Ur.UNIMPLEMENTED;case fh.DATA_LOSS:return Ur.DATA_LOSS;default:return Lr("Unknown status code: "+t)}}(ph=fh=fh||{})[ph.OK=0]="OK",ph[ph.CANCELLED=1]="CANCELLED",ph[ph.UNKNOWN=2]="UNKNOWN",ph[ph.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",ph[ph.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",ph[ph.NOT_FOUND=5]="NOT_FOUND",ph[ph.ALREADY_EXISTS=6]="ALREADY_EXISTS",ph[ph.PERMISSION_DENIED=7]="PERMISSION_DENIED",ph[ph.UNAUTHENTICATED=16]="UNAUTHENTICATED",ph[ph.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",ph[ph.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",ph[ph.ABORTED=10]="ABORTED",ph[ph.OUT_OF_RANGE=11]="OUT_OF_RANGE",ph[ph.UNIMPLEMENTED=12]="UNIMPLEMENTED",ph[ph.INTERNAL=13]="INTERNAL",ph[ph.UNAVAILABLE=14]="UNAVAILABLE",ph[ph.DATA_LOSS=15]="DATA_LOSS";var vh,bh,wh,Eh,Sh=(Th.emptySet=function(t){return new Th(t.comparator)},Th.prototype.has=function(t){return null!=this.keyedMap.get(t)},Th.prototype.get=function(t){return this.keyedMap.get(t)},Th.prototype.first=function(){return this.sortedSet.minKey()},Th.prototype.last=function(){return this.sortedSet.maxKey()},Th.prototype.isEmpty=function(){return this.sortedSet.isEmpty()},Th.prototype.indexOf=function(t){var e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1},Object.defineProperty(Th.prototype,"size",{get:function(){return this.sortedSet.size},enumerable:!0,configurable:!0}),Th.prototype.forEach=function(n){this.sortedSet.inorderTraversal(function(t,e){return n(t),!1})},Th.prototype.add=function(t){var e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))},Th.prototype.delete=function(t){var e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this},Th.prototype.isEqual=function(t){if(!(t instanceof Th))return!1;if(this.size!==t.size)return!1;for(var e=this.sortedSet.getIterator(),n=t.sortedSet.getIterator();e.hasNext();){var r=e.getNext().key,i=n.getNext().key;if(!r.isEqual(i))return!1}return!0},Th.prototype.toString=function(){var e=[];return this.forEach(function(t){e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"},Th.prototype.copy=function(t,e){var n=new Th;return n.comparator=this.comparator,n.keyedMap=t,n.sortedSet=e,n},Th);function Th(n){this.comparator=n?function(t,e){return n(t,e)||Bi.comparator(t.key,e.key)}:function(t,e){return Bi.comparator(t.key,e.key)},this.keyedMap=Io(),this.sortedSet=new so(this.comparator)}(bh=vh=vh||{})[bh.Added=0]="Added",bh[bh.Removed=1]="Removed",bh[bh.Modified=2]="Modified",bh[bh.Metadata=3]="Metadata",(Eh=wh=wh||{})[Eh.Local=0]="Local",Eh[Eh.Synced=1]="Synced";var Ih=(Ch.prototype.track=function(t){var e=t.doc.key,n=this.changeMap.get(e);n?t.type!==vh.Added&&n.type===vh.Metadata?this.changeMap=this.changeMap.insert(e,t):t.type===vh.Metadata&&n.type!==vh.Removed?this.changeMap=this.changeMap.insert(e,{type:n.type,doc:t.doc}):t.type===vh.Modified&&n.type===vh.Modified?this.changeMap=this.changeMap.insert(e,{type:vh.Modified,doc:t.doc}):t.type===vh.Modified&&n.type===vh.Added?this.changeMap=this.changeMap.insert(e,{type:vh.Added,doc:t.doc}):t.type===vh.Removed&&n.type===vh.Added?this.changeMap=this.changeMap.remove(e):t.type===vh.Removed&&n.type===vh.Modified?this.changeMap=this.changeMap.insert(e,{type:vh.Removed,doc:n.doc}):t.type===vh.Added&&n.type===vh.Removed?this.changeMap=this.changeMap.insert(e,{type:vh.Modified,doc:t.doc}):Lr("unsupported combination of changes: "+JSON.stringify(t)+" after "+JSON.stringify(n)):this.changeMap=this.changeMap.insert(e,t)},Ch.prototype.getChanges=function(){var n=[];return this.changeMap.inorderTraversal(function(t,e){n.push(e)}),n},Ch);function Ch(){this.changeMap=new so(Bi.comparator)}var Dh=(Nh.fromInitialDocuments=function(t,e,n,r){var i=[];return e.forEach(function(t){i.push({type:vh.Added,doc:t})}),new Nh(t,e,Sh.emptySet(e),i,n,r,!0,!1)},Object.defineProperty(Nh.prototype,"hasPendingWrites",{get:function(){return!this.mutatedKeys.isEmpty()},enumerable:!0,configurable:!0}),Nh.prototype.isEqual=function(t){if(!(this.fromCache===t.fromCache&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&this.query.isEqual(t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;var e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(var r=0;r<e.length;r++)if(e[r].type!==n[r].type||!e[r].doc.isEqual(n[r].doc))return!1;return!0},Nh);function Nh(t,e,n,r,i,o,a,s){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=o,this.syncStateChanged=a,this.excludesMetadataChanges=s}var Ah=(kh.createSynthesizedRemoteEventForCurrentChange=function(t,e){var n,r=((n={})[t]=Rh.createSynthesizedTargetChangeForCurrentChange(t,e),n);return new kh(oo.MIN,r,Ro(),Eo(),Ao())},kh);function kh(t,e,n,r,i){this.snapshotVersion=t,this.targetChanges=e,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}var Rh=(Mh.createSynthesizedTargetChangeForCurrentChange=function(t,e){return new Mh(Vr(),e,Ao(),Ao(),Ao())},Mh);function Mh(t,e,n,r,i){this.resumeToken=t,this.current=e,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}var _h,Oh,Ph=function(t,e,n,r){this.updatedTargetIds=t,this.removedTargetIds=e,this.key=n,this.newDoc=r},Lh=function(t,e){this.targetId=t,this.existenceFilter=e};(Oh=_h=_h||{})[Oh.NoChange=0]="NoChange",Oh[Oh.Added=1]="Added",Oh[Oh.Removed=2]="Removed",Oh[Oh.Current=3]="Current",Oh[Oh.Reset=4]="Reset";var xh=function(t,e,n,r){void 0===n&&(n=Vr()),void 0===r&&(r=null),this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r},qh=(Object.defineProperty(Fh.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(Fh.prototype,"resumeToken",{get:function(){return this._resumeToken},enumerable:!0,configurable:!0}),Object.defineProperty(Fh.prototype,"isPending",{get:function(){return 0!==this.pendingResponses},enumerable:!0,configurable:!0}),Object.defineProperty(Fh.prototype,"hasPendingChanges",{get:function(){return this._hasPendingChanges},enumerable:!0,configurable:!0}),Fh.prototype.updateResumeToken=function(t){0<t.length&&(this._hasPendingChanges=!0,this._resumeToken=t)},Fh.prototype.toTargetChange=function(){var n=Ao(),r=Ao(),i=Ao();return this.documentChanges.forEach(function(t,e){switch(e){case vh.Added:n=n.add(t);break;case vh.Modified:r=r.add(t);break;case vh.Removed:i=i.add(t);break;default:Lr("Encountered invalid change type: "+e)}}),new Rh(this._resumeToken,this._current,n,r,i)},Fh.prototype.clearPendingChanges=function(){this._hasPendingChanges=!1,this.documentChanges=Qh()},Fh.prototype.addDocumentChange=function(t,e){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.insert(t,e)},Fh.prototype.removeDocumentChange=function(t){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.remove(t)},Fh.prototype.recordPendingTargetRequest=function(){this.pendingResponses+=1},Fh.prototype.recordTargetResponse=function(){this.pendingResponses-=1},Fh.prototype.markCurrent=function(){this._hasPendingChanges=!0,this._current=!0},Fh);function Fh(){this.pendingResponses=0,this.documentChanges=Qh(),this._resumeToken=Vr(),this._current=!1,this._hasPendingChanges=!0}var Vh=(Bh.prototype.handleDocumentChange=function(t){for(var e=0,n=t.updatedTargetIds;e<n.length;e++){var r=n[e];t.newDoc instanceof Os?this.addDocumentToTarget(r,t.newDoc):t.newDoc instanceof xs&&this.removeDocumentFromTarget(r,t.key,t.newDoc)}for(var i=0,o=t.removedTargetIds;i<o.length;i++)r=o[i],this.removeDocumentFromTarget(r,t.key,t.newDoc)},Bh.prototype.handleTargetChange=function(n){var r=this;this.forEachTarget(n,function(t){var e=r.ensureTargetState(t);switch(n.state){case _h.NoChange:r.isActiveTarget(t)&&e.updateResumeToken(n.resumeToken);break;case _h.Added:e.recordTargetResponse(),e.isPending||e.clearPendingChanges(),e.updateResumeToken(n.resumeToken);break;case _h.Removed:e.recordTargetResponse(),e.isPending||r.removeTarget(t),xr(!n.cause,"WatchChangeAggregator does not handle errored targets");break;case _h.Current:r.isActiveTarget(t)&&(e.markCurrent(),e.updateResumeToken(n.resumeToken));break;case _h.Reset:r.isActiveTarget(t)&&(r.resetTarget(t),e.updateResumeToken(n.resumeToken));break;default:Lr("Unknown target watch change state: "+n.state)}})},Bh.prototype.forEachTarget=function(t,e){0<t.targetIds.length?t.targetIds.forEach(e):zr(this.targetStates,e)},Bh.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 Bi(i.path);this.removeDocumentFromTarget(e,o,new xs(o,oo.forDeletedDoc()))}else xr(1===n,"Single document existence filter with count: "+n);else this.getCurrentDocumentCountForTarget(e)!==n&&(this.resetTarget(e),this.pendingTargetResets=this.pendingTargetResets.add(e))}},Bh.prototype.createRemoteEvent=function(i){var o=this,a={};zr(this.targetStates,function(t,e){var n=o.queryDataForActiveTarget(t);if(n){if(e.current&&n.query.isDocumentQuery()){var r=new Bi(n.query.path);null!==o.pendingDocumentUpdates.get(r)||o.targetContainsDocument(t,r)||o.removeDocumentFromTarget(t,r,new xs(r,i))}e.hasPendingChanges&&(a[t]=e.toTargetChange(),e.clearPendingChanges())}});var r=Ao();this.pendingDocumentTargetMapping.forEach(function(t,e){var n=!0;e.forEachWhile(function(t){var e=o.queryDataForActiveTarget(t);return!e||e.purpose===xu.LimboResolution||(n=!1)}),n&&(r=r.add(t))});var t=new Ah(i,a,this.pendingTargetResets,this.pendingDocumentUpdates,r);return this.pendingDocumentUpdates=Eo(),this.pendingDocumentTargetMapping=Uh(),this.pendingTargetResets=new yo(yi),t},Bh.prototype.addDocumentToTarget=function(t,e){if(this.isActiveTarget(t)){var n=this.targetContainsDocument(t,e.key)?vh.Modified:vh.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))}},Bh.prototype.removeDocumentFromTarget=function(t,e,n){if(this.isActiveTarget(t)){var r=this.ensureTargetState(t);this.targetContainsDocument(t,e)?r.addDocumentChange(e,vh.Removed):r.removeDocumentChange(e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e,this.ensureDocumentTargetMapping(e).delete(t)),n&&(this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e,n))}},Bh.prototype.removeTarget=function(t){delete this.targetStates[t]},Bh.prototype.getCurrentDocumentCountForTarget=function(t){var e=this.ensureTargetState(t).toTargetChange();return this.metadataProvider.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size},Bh.prototype.recordPendingTargetRequest=function(t){this.ensureTargetState(t).recordPendingTargetRequest()},Bh.prototype.ensureTargetState=function(t){return this.targetStates[t]||(this.targetStates[t]=new qh),this.targetStates[t]},Bh.prototype.ensureDocumentTargetMapping=function(t){var e=this.pendingDocumentTargetMapping.get(t);return e||(e=new yo(yi),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(t,e)),e},Bh.prototype.isActiveTarget=function(t){var e=null!==this.queryDataForActiveTarget(t);return e||_r("WatchChangeAggregator","Detected inactive target",t),e},Bh.prototype.queryDataForActiveTarget=function(t){var e=this.targetStates[t];return e&&e.isPending?null:this.metadataProvider.getQueryDataForTarget(t)},Bh.prototype.resetTarget=function(e){var n=this;xr(!this.targetStates[e].isPending,"Should only reset active targets"),this.targetStates[e]=new qh,this.metadataProvider.getRemoteKeysForTarget(e).forEach(function(t){n.removeDocumentFromTarget(e,t,null)})},Bh.prototype.targetContainsDocument=function(t,e){return this.metadataProvider.getRemoteKeysForTarget(t).has(e)},Bh);function Bh(t){this.metadataProvider=t,this.targetStates={},this.pendingDocumentUpdates=Eo(),this.pendingDocumentTargetMapping=Uh(),this.pendingTargetResets=new yo(yi)}function Uh(){return new so(Bi.comparator)}function Qh(){return new so(Bi.comparator)}var Kh="RemoteStore",jh=(Wh.prototype.start=function(){return this.enableNetwork()},Wh.prototype.enableNetwork=function(){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return this.networkEnabled=!0,this.canUseNetwork()?(e=this.writeStream,[4,this.localStore.getLastStreamToken()]):[3,3];case 1:return e.lastStreamToken=t.sent(),this.shouldStartWatchStream()?this.startWatchStream():this.onlineStateTracker.set(ah.Unknown),[4,this.fillWritePipeline()];case 2:t.sent(),t.label=3;case 3:return[2]}})})},Wh.prototype.disableNetwork=function(){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(ah.Offline),[2]}})})},Wh.prototype.disableNetworkInternal=function(){return p(this,void 0,void 0,function(){return d(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(),0<this.writePipeline.length&&(_r(Kh,"Stopping write stream with "+this.writePipeline.length+" pending writes"),this.writePipeline=[]),this.cleanUpWatchStreamState(),[2]}})})},Wh.prototype.shutdown=function(){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return _r(Kh,"RemoteStore shutting down."),this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.connectivityMonitor.shutdown(),this.onlineStateTracker.set(ah.Unknown),[2]}})})},Wh.prototype.listen=function(t){xr(!Wr(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.watchStream.isOpen()&&this.sendWatchRequest(t)},Wh.prototype.unlisten=function(t){xr(Wr(this.listenTargets,t),"unlisten called without assigned target ID!"),delete this.listenTargets[t],this.watchStream.isOpen()&&this.sendUnwatchRequest(t),Yr(this.listenTargets)&&(this.watchStream.isOpen()?this.watchStream.markIdle():this.canUseNetwork()&&this.onlineStateTracker.set(ah.Unknown))},Wh.prototype.getQueryDataForTarget=function(t){return this.listenTargets[t]||null},Wh.prototype.getRemoteKeysForTarget=function(t){return this.syncEngine.getRemoteKeysForTarget(t)},Wh.prototype.sendWatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},Wh.prototype.sendUnwatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},Wh.prototype.startWatchStream=function(){xr(this.shouldStartWatchStream(),"startWatchStream() called when shouldStartWatchStream() is false."),this.watchChangeAggregator=new Vh(this),this.watchStream.start(),this.onlineStateTracker.handleWatchStreamStart()},Wh.prototype.shouldStartWatchStream=function(){return this.canUseNetwork()&&!this.watchStream.isStarted()&&!Yr(this.listenTargets)},Wh.prototype.canUseNetwork=function(){return this.isPrimary&&this.networkEnabled},Wh.prototype.cleanUpWatchStreamState=function(){this.watchChangeAggregator=null},Wh.prototype.onWatchStreamOpen=function(){return p(this,void 0,void 0,function(){var n=this;return d(this,function(t){return zr(this.listenTargets,function(t,e){n.sendWatchRequest(e)}),[2]})})},Wh.prototype.onWatchStreamClose=function(e){return p(this,void 0,void 0,function(){return d(this,function(t){return void 0===e&&xr(!this.shouldStartWatchStream(),"Watch stream was stopped gracefully while still needed."),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.onlineStateTracker.handleWatchStreamFailure(e),this.startWatchStream()):this.onlineStateTracker.set(ah.Unknown),[2]})})},Wh.prototype.onWatchStreamChange=function(n,r){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return this.onlineStateTracker.set(ah.Online),n instanceof xh&&n.state===_h.Removed&&n.cause?[2,this.handleTargetError(n)]:(n instanceof Ph?this.watchChangeAggregator.handleDocumentChange(n):n instanceof Lh?this.watchChangeAggregator.handleExistenceFilter(n):(xr(n instanceof xh,"Expected watchChange to be an instance of WatchTargetChange"),this.watchChangeAggregator.handleTargetChange(n)),r.isEqual(oo.MIN)?[3,3]:[4,this.localStore.getLastRemoteSnapshotVersion()]);case 1:return e=t.sent(),0<=r.compareTo(e)?[4,this.raiseWatchSnapshot(r)]:[3,3];case 2:t.sent(),t.label=3;case 3:return[2]}})})},Wh.prototype.raiseWatchSnapshot=function(r){var i=this;xr(!r.isEqual(oo.MIN),"Can't raise event for unknown SnapshotVersion");var t=this.watchChangeAggregator.createRemoteEvent(r);return zr(t.targetChanges,function(t,e){if(0<e.resumeToken.length){var n=i.listenTargets[t];n&&(i.listenTargets[t]=n.copy({resumeToken:e.resumeToken,snapshotVersion:r}))}}),t.targetMismatches.forEach(function(t){var e=i.listenTargets[t];if(e){i.listenTargets[t]=e.copy({resumeToken:Vr()}),i.sendUnwatchRequest(t);var n=new Qu(e.query,t,xu.ExistenceFilterMismatch,e.sequenceNumber);i.sendWatchRequest(n)}}),this.syncEngine.applyRemoteEvent(t)},Wh.prototype.handleTargetError=function(t){var n=this;xr(!!t.cause,"Handling target error without a cause");var r=t.cause,i=Promise.resolve();return t.targetIds.forEach(function(e){i=i.then(function(){return p(n,void 0,void 0,function(){return d(this,function(t){return Wr(this.listenTargets,e)?(delete this.listenTargets[e],this.watchChangeAggregator.removeTarget(e),[2,this.syncEngine.rejectListen(e,r)]):[2]})})})}),i},Wh.prototype.fillWritePipeline=function(){return p(this,void 0,void 0,function(){var e,n;return d(this,function(t){switch(t.label){case 0:return this.canAddToWritePipeline()?(e=0<this.writePipeline.length?this.writePipeline[this.writePipeline.length-1].batchId:-1,[4,this.localStore.nextMutationBatch(e)]):[3,4];case 1:return null!==(n=t.sent())?[3,2]:(0===this.writePipeline.length&&this.writeStream.markIdle(),[3,4]);case 2:return this.addToWritePipeline(n),[4,this.fillWritePipeline()];case 3:t.sent(),t.label=4;case 4:return this.shouldStartWriteStream()&&this.startWriteStream(),[2]}})})},Wh.prototype.canAddToWritePipeline=function(){return this.canUseNetwork()&&this.writePipeline.length<10},Wh.prototype.outstandingWrites=function(){return this.writePipeline.length},Wh.prototype.addToWritePipeline=function(t){xr(this.canAddToWritePipeline(),"addToWritePipeline called when pipeline is full"),this.writePipeline.push(t),this.writeStream.isOpen()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},Wh.prototype.shouldStartWriteStream=function(){return this.canUseNetwork()&&!this.writeStream.isStarted()&&0<this.writePipeline.length},Wh.prototype.startWriteStream=function(){xr(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},Wh.prototype.onWriteStreamOpen=function(){return p(this,void 0,void 0,function(){return d(this,function(t){return this.writeStream.writeHandshake(),[2]})})},Wh.prototype.onWriteHandshakeComplete=function(){var r=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var t=0,e=r.writePipeline;t<e.length;t++){var n=e[t];r.writeStream.writeMutations(n.mutations)}}).catch(hc)},Wh.prototype.onMutationResult=function(t,e){var n=this;xr(0<this.writePipeline.length,"Got result for empty write pipeline");var r=this.writePipeline.shift(),i=Oo.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then(function(){return n.fillWritePipeline()})},Wh.prototype.onWriteStreamClose=function(n){return p(this,void 0,void 0,function(){var e=this;return d(this,function(t){return void 0===n&&xr(!this.shouldStartWriteStream(),"Write stream was stopped gracefully while still needed."),n&&0<this.writePipeline.length?[2,(this.writeStream.handshakeComplete?this.handleWriteError(n):this.handleHandshakeError(n)).then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})]:[2]})})},Wh.prototype.handleHandshakeError=function(e){return p(this,void 0,void 0,function(){return d(this,function(t){return yh(e.code)?(_r(Kh,"RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=Vr(),[2,this.localStore.setLastStreamToken(Vr()).catch(hc)]):[2]})})},Wh.prototype.handleWriteError=function(r){return p(this,void 0,void 0,function(){var e,n=this;return d(this,function(t){return function(t){return yh(t)&&t!==Ur.ABORTED}(r.code)?(e=this.writePipeline.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(e.batchId,r).then(function(){return n.fillWritePipeline()})]):[2]})})},Wh.prototype.createTransaction=function(){return new hh(this.datastore)},Wh.prototype.restartNetwork=function(){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(ah.Unknown),[4,this.enableNetwork()];case 2:return t.sent(),[2]}})})},Wh.prototype.handleCredentialChange=function(){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.canUseNetwork()?(_r(Kh,"RemoteStore restarting streams for new credential"),[4,this.restartNetwork()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},Wh.prototype.applyPrimaryState=function(e){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return(this.isPrimary=e)&&this.networkEnabled?[4,this.enableNetwork()]:[3,2];case 1:return t.sent(),[3,4];case 2:return e?[3,4]:[4,this.disableNetworkInternal()];case 3:t.sent(),this.onlineStateTracker.set(ah.Unknown),t.label=4;case 4:return[2]}})})},Wh);function Wh(t,e,n,r,i){var o=this;this.localStore=t,this.datastore=e,this.writePipeline=[],this.listenTargets={},this.watchChangeAggregator=null,this.networkEnabled=!1,this.isPrimary=!1,this.connectivityMonitor=i,this.connectivityMonitor.addCallback(function(t){n.enqueueAndForget(function(){return p(o,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.canUseNetwork()?(_r(Kh,"Restarting streams for network reachability change."),[4,this.restartNetwork()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})})}),this.onlineStateTracker=new dh(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)})}var Gh=(Object.defineProperty(zh.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(zh.prototype,"longitude",{get:function(){return this._long},enumerable:!0,configurable:!0}),zh.prototype.isEqual=function(t){return this._lat===t._lat&&this._long===t._long},zh.prototype._compareTo=function(t){return yi(this._lat,t._lat)||yi(this._long,t._long)},zh);function zh(t,e){if(Jr("GeoPoint",arguments,2),ti("GeoPoint","number",1,t),ti("GeoPoint","number",2,e),!isFinite(t)||t<-90||90<t)throw new Qr(Ur.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||180<e)throw new Qr(Ur.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}var Hh=(Yh.atPath=function(t){return new Yh(t)},Object.defineProperty(Yh.prototype,"orderBy",{get:function(){if(null===this.memoizedOrderBy){var t=this.getInequalityFilterField(),e=this.getFirstOrderByField();if(null!==t&&null===e)t.isKeyField()?this.memoizedOrderBy=[Tl]:this.memoizedOrderBy=[new El(t),Tl];else{xr(null===t||null!==e&&t.isEqual(e),"First orderBy should match inequality field.");for(var n=!(this.memoizedOrderBy=[]),r=0,i=this.explicitOrderBy;r<i.length;r++){var o=i[r];this.memoizedOrderBy.push(o),o.field.isKeyField()&&(n=!0)}if(!n){var a=0<this.explicitOrderBy.length?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:gl.ASCENDING;this.memoizedOrderBy.push(a===gl.ASCENDING?Tl:Il)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),Yh.prototype.addFilter=function(t){xr(null==this.getInequalityFilterField()||!(t instanceof tl)||!t.isInequality()||t.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),xr(!this.isDocumentQuery(),"No filtering allowed for document query");var e=this.filters.concat([t]);return new Yh(this.path,this.collectionGroup,this.explicitOrderBy.slice(),e,this.limit,this.startAt,this.endAt)},Yh.prototype.addOrderBy=function(t){xr(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var e=this.explicitOrderBy.concat([t]);return new Yh(this.path,this.collectionGroup,e,this.filters.slice(),this.limit,this.startAt,this.endAt)},Yh.prototype.withLimit=function(t){return new Yh(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),t,this.startAt,this.endAt)},Yh.prototype.withStartAt=function(t){return new Yh(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,t,this.endAt)},Yh.prototype.withEndAt=function(t){return new Yh(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,t)},Yh.prototype.asCollectionQueryAtPath=function(t){return new Yh(t,null,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,this.endAt)},Yh.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();this.isCollectionGroupQuery()&&(t+="|cg:"+this.collectionGroup),t+="|f:";for(var e=0,n=this.filters;e<n.length;e++)t+=n[e].canonicalId(),t+=",";t+="|ob:";for(var r=0,i=this.orderBy;r<i.length;r++)t+=i[r].canonicalId(),t+=",";Kc(this.limit)||(t+="|l:",t+=this.limit),this.startAt&&(t+="|lb:",t+=this.startAt.canonicalId()),this.endAt&&(t+="|ub:",t+=this.endAt.canonicalId()),this.memoizedCanonicalId=t}return this.memoizedCanonicalId},Yh.prototype.toString=function(){var t="Query("+this.path.canonicalString();return this.isCollectionGroupQuery()&&(t+=" collectionGroup="+this.collectionGroup),0<this.filters.length&&(t+=", filters: ["+this.filters.join(", ")+"]"),Kc(this.limit)||(t+=", limit: "+this.limit),0<this.explicitOrderBy.length&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},Yh.prototype.isEqual=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e<this.orderBy.length;e++)if(!this.orderBy[e].isEqual(t.orderBy[e]))return!1;if(this.filters.length!==t.filters.length)return!1;for(e=0;e<this.filters.length;e++)if(!this.filters[e].isEqual(t.filters[e]))return!1;return this.collectionGroup===t.collectionGroup&&!!this.path.isEqual(t.path)&&!(null!==this.startAt?!this.startAt.isEqual(t.startAt):null!==t.startAt)&&(null!==this.endAt?this.endAt.isEqual(t.endAt):null===t.endAt)},Yh.prototype.docComparator=function(t,e){for(var n=!1,r=0,i=this.orderBy;r<i.length;r++){var o=i[r],a=o.compare(t,e);if(0!==a)return a;n=n||o.field.isKeyField()}return xr(n,"orderBy used that doesn't compare on key field"),0},Yh.prototype.matches=function(t){return this.matchesPathAndCollectionGroup(t)&&this.matchesOrderBy(t)&&this.matchesFilters(t)&&this.matchesBounds(t)},Yh.prototype.hasLimit=function(){return!Kc(this.limit)},Yh.prototype.getFirstOrderByField=function(){return 0<this.explicitOrderBy.length?this.explicitOrderBy[0].field:null},Yh.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t<e.length;t++){var n=e[t];if(n instanceof tl&&n.isInequality())return n.field}return null},Yh.prototype.findFilterOperator=function(t){for(var e=0,n=this.filters;e<n.length;e++){var r=n[e];if(r instanceof tl&&0<=t.indexOf(r.op))return r.op}return null},Yh.prototype.isDocumentQuery=function(){return Bi.isDocumentKey(this.path)&&null===this.collectionGroup&&0===this.filters.length},Yh.prototype.isCollectionGroupQuery=function(){return null!==this.collectionGroup},Yh.prototype.matchesPathAndCollectionGroup=function(t){var e=t.key.path;return null!==this.collectionGroup?t.key.hasCollectionId(this.collectionGroup)&&this.path.isPrefixOf(e):Bi.isDocumentKey(this.path)?this.path.isEqual(e):this.path.isImmediateParentOf(e)},Yh.prototype.matchesOrderBy=function(t){for(var e=0,n=this.explicitOrderBy;e<n.length;e++){var r=n[e];if(!r.field.isKeyField()&&null===t.field(r.field))return!1}return!0},Yh.prototype.matchesFilters=function(t){for(var e=0,n=this.filters;e<n.length;e++)if(!n[e].matches(t))return!1;return!0},Yh.prototype.matchesBounds=function(t){return!(this.startAt&&!this.startAt.sortsBeforeDocument(this.orderBy,t)||this.endAt&&this.endAt.sortsBeforeDocument(this.orderBy,t))},Yh.prototype.assertValidBound=function(t){xr(t.position.length<=this.orderBy.length,"Bound is longer than orderBy")},Yh);function Yh(t,e,n,r,i,o,a){void 0===e&&(e=null),void 0===n&&(n=[]),void 0===r&&(r=[]),void 0===i&&(i=null),void 0===o&&(o=null),void 0===a&&(a=null),this.path=t,this.collectionGroup=e,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.startAt=o,this.endAt=a,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}function Xh(){}var Jh=($h.fromString=function(t){switch(t){case"<":return $h.LESS_THAN;case"<=":return $h.LESS_THAN_OR_EQUAL;case"==":return $h.EQUAL;case">=":return $h.GREATER_THAN_OR_EQUAL;case">":return $h.GREATER_THAN;case"array-contains":return $h.ARRAY_CONTAINS;case"in":return $h.IN;case"array-contains-any":return $h.ARRAY_CONTAINS_ANY;default:return Lr("Unknown FieldFilter operator: "+t)}},$h.prototype.toString=function(){return this.name},$h.prototype.isEqual=function(t){return this.name===t.name},$h.LESS_THAN=new $h("<"),$h.LESS_THAN_OR_EQUAL=new $h("<="),$h.EQUAL=new $h("=="),$h.GREATER_THAN=new $h(">"),$h.GREATER_THAN_OR_EQUAL=new $h(">="),$h.ARRAY_CONTAINS=new $h("array-contains"),$h.IN=new $h("in"),$h.ARRAY_CONTAINS_ANY=new $h("array-contains-any"),$h);function $h(t){this.name=t}var Zh,tl=(s(el,Zh=Xh),el.create=function(t,e,n){if(t.isKeyField())return e===Jh.IN?(xr(n instanceof As,"Comparing on key with IN, but filter value not an ArrayValue"),xr(n.internalValue.every(function(t){return t instanceof bs}),"Comparing on key with IN, but an array value was not a RefValue"),new al(t,n)):(xr(n instanceof bs,"Comparing on key, but filter value not a RefValue"),xr(e!==Jh.ARRAY_CONTAINS&&e!==Jh.ARRAY_CONTAINS_ANY,"'"+e.toString()+"' queries don't make sense on document keys."),new rl(t,e,n));if(n.isEqual(Wa.INSTANCE)){if(e!==Jh.EQUAL)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. Null supports only equality comparisons.");return new el(t,e,n)}if(n.isEqual(is.NAN)){if(e!==Jh.EQUAL)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. NaN supports only equality comparisons.");return new el(t,e,n)}return e===Jh.ARRAY_CONTAINS?new cl(t,n):e===Jh.IN?(xr(n instanceof As,"IN filter has invalid value: "+n.toString()),new fl(t,n)):e===Jh.ARRAY_CONTAINS_ANY?(xr(n instanceof As,"ARRAY_CONTAINS_ANY filter has invalid value: "+n.toString()),new ml(t,n)):new el(t,e,n)},el.prototype.matches=function(t){var e=t.field(this.field);return null!==e&&this.value.typeOrder===e.typeOrder&&this.matchesComparison(e.compareTo(this.value))},el.prototype.matchesComparison=function(t){switch(this.op){case Jh.LESS_THAN:return t<0;case Jh.LESS_THAN_OR_EQUAL:return t<=0;case Jh.EQUAL:return 0===t;case Jh.GREATER_THAN:return 0<t;case Jh.GREATER_THAN_OR_EQUAL:return 0<=t;default:return Lr("Unknown FieldFilter operator: "+this.op)}},el.prototype.isInequality=function(){return 0<=[Jh.LESS_THAN,Jh.LESS_THAN_OR_EQUAL,Jh.GREATER_THAN,Jh.GREATER_THAN_OR_EQUAL].indexOf(this.op)},el.prototype.canonicalId=function(){return this.field.canonicalString()+this.op.toString()+this.value.toString()},el.prototype.isEqual=function(t){return t instanceof el&&this.op.isEqual(t.op)&&this.field.isEqual(t.field)&&this.value.isEqual(t.value)},el.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},el);function el(t,e,n){var r=Zh.call(this)||this;return r.field=t,r.op=e,r.value=n,r}var nl,rl=(s(il,nl=tl),il.prototype.matches=function(t){var e=this.value,n=Bi.comparator(t.key,e.key);return this.matchesComparison(n)},il);function il(){return null!==nl&&nl.apply(this,arguments)||this}var ol,al=(s(sl,ol=tl),sl.prototype.matches=function(e){return this.value.internalValue.some(function(t){return e.key.isEqual(t.key)})},sl);function sl(t,e){var n=ol.call(this,t,Jh.IN,e)||this;return n.value=e,n}var ul,cl=(s(hl,ul=tl),hl.prototype.matches=function(t){var e=t.field(this.field);return e instanceof As&&e.contains(this.value)},hl);function hl(t,e){return ul.call(this,t,Jh.ARRAY_CONTAINS,e)||this}var ll,fl=(s(pl,ll=tl),pl.prototype.matches=function(t){var e=this.value,n=t.field(this.field);return null!==n&&e.contains(n)},pl);function pl(t,e){var n=ll.call(this,t,Jh.IN,e)||this;return n.value=e,n}var dl,ml=(s(yl,dl=tl),yl.prototype.matches=function(t){var e=this,n=t.field(this.field);return n instanceof As&&n.internalValue.some(function(t){return e.value.contains(t)})},yl);function yl(t,e){var n=dl.call(this,t,Jh.ARRAY_CONTAINS_ANY,e)||this;return n.value=e,n}var gl=(vl.prototype.toString=function(){return this.name},vl.ASCENDING=new vl("asc"),vl.DESCENDING=new vl("desc"),vl);function vl(t){this.name=t}var bl=(wl.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e<n.length;e++)t+=n[e].toString();return t},wl.prototype.sortsBeforeDocument=function(t,e){xr(this.position.length<=t.length,"Bound has more components than query's orderBy");for(var n=0,r=0;r<this.position.length;r++){var i=t[r],o=this.position[r];if(i.field.isKeyField())xr(o instanceof bs,"Bound has a non-key value where the key path is being used."),n=Bi.comparator(o.key,e.key);else{var a=e.field(i.field);xr(null!==a,"Field should exist since document matched the orderBy already."),n=o.compareTo(a)}if(i.dir===gl.DESCENDING&&(n*=-1),0!==n)break}return this.before?n<=0:n<0},wl.prototype.isEqual=function(t){if(null===t)return!1;if(this.before!==t.before||this.position.length!==t.position.length)return!1;for(var e=0;e<this.position.length;e++){var n=this.position[e],r=t.position[e];if(!n.isEqual(r))return!1}return!0},wl);function wl(t,e){this.position=t,this.before=e}var El=(Sl.prototype.compare=function(t,e){var n=this.isKeyOrderBy?Os.compareByKey(t,e):Os.compareByField(this.field,t,e);switch(this.dir){case gl.ASCENDING:return n;case gl.DESCENDING:return-1*n;default:return Lr("Unknown direction: "+this.dir)}},Sl.prototype.canonicalId=function(){return this.field.canonicalString()+this.dir.toString()},Sl.prototype.toString=function(){return this.field.canonicalString()+" ("+this.dir+")"},Sl.prototype.isEqual=function(t){return this.dir===t.dir&&this.field.isEqual(t.field)},Sl);function Sl(t,e){this.field=t,void 0===e&&(e=gl.ASCENDING),this.dir=e,this.isKeyOrderBy=t.isKeyField()}var Tl=new El(Fi.keyField(),gl.ASCENDING),Il=new El(Fi.keyField(),gl.DESCENDING),Cl=(Dl.prototype.applyToLocalView=function(t,e){return new ps(e,t)},Dl.prototype.applyToRemoteDocument=function(t,e){return e},Dl.prototype.computeBaseValue=function(t){return null},Dl.prototype.isEqual=function(t){return t instanceof Dl},Dl.instance=new Dl,Dl);function Dl(){}var Nl=(Al.prototype.applyToLocalView=function(t,e){return this.apply(t)},Al.prototype.applyToRemoteDocument=function(t,e){return this.apply(t)},Al.prototype.apply=function(t){for(var n=Ol(t),e=function(e){n.find(function(t){return t.isEqual(e)})||n.push(e)},r=0,i=this.elements;r<i.length;r++)e(i[r]);return new As(n)},Al.prototype.computeBaseValue=function(t){return null},Al.prototype.isEqual=function(t){return t instanceof Al&&gi(t.elements,this.elements)},Al);function Al(t){this.elements=t}var kl=(Rl.prototype.applyToLocalView=function(t,e){return this.apply(t)},Rl.prototype.applyToRemoteDocument=function(t,e){return this.apply(t)},Rl.prototype.apply=function(t){for(var n=Ol(t),e=function(e){n=n.filter(function(t){return!t.isEqual(e)})},r=0,i=this.elements;r<i.length;r++)e(i[r]);return new As(n)},Rl.prototype.computeBaseValue=function(t){return null},Rl.prototype.isEqual=function(t){return t instanceof Rl&&gi(t.elements,this.elements)},Rl);function Rl(t){this.elements=t}var Ml=(_l.prototype.applyToLocalView=function(t,e){var n=this.computeBaseValue(t);if(n instanceof es&&this.operand instanceof es){var r=n.internalValue+this.operand.internalValue;return new es(r)}return r=n.internalValue+this.operand.internalValue,new is(r)},_l.prototype.applyToRemoteDocument=function(t,e){return xr(null!==e,"Didn't receive transformResult for NUMERIC_ADD transform"),e},_l.prototype.computeBaseValue=function(t){return t instanceof Ja?t:new es(0)},_l.prototype.isEqual=function(t){return t instanceof _l&&this.operand.isEqual(t.operand)},_l);function _l(t){this.operand=t}function Ol(t){return t instanceof As?t.internalValue.slice():[]}var Pl=(Ll.prototype.isEqual=function(t){return t&&t.count===this.count},Ll);function Ll(t){this.count=t}var xl,ql,Fl=((xl={})[gl.ASCENDING.name]="ASCENDING",xl[gl.DESCENDING.name]="DESCENDING",xl),Vl=((ql={})[Jh.LESS_THAN.name]="LESS_THAN",ql[Jh.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",ql[Jh.GREATER_THAN.name]="GREATER_THAN",ql[Jh.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",ql[Jh.EQUAL.name]="EQUAL",ql[Jh.ARRAY_CONTAINS.name]="ARRAY_CONTAINS",ql[Jh.IN.name]="IN",ql[Jh.ARRAY_CONTAINS_ANY.name]="ARRAY_CONTAINS_ANY",ql),Bl=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Ul(t,e){xr(!Kc(t),e+" is missing")}function Ql(t){return"number"==typeof t?t:"string"==typeof t?Number(t):Lr("can't parse "+t)}var Kl=(jl.prototype.emptyByteString=function(){return this.options.useProto3Json?"":new Uint8Array(0)},jl.prototype.unsafeCastProtoByteString=function(t){return t},jl.prototype.fromRpcStatus=function(t){var e=void 0===t.code?Ur.UNKNOWN:gh(t.code);return new Qr(e,t.message||"")},jl.prototype.toInt32Value=function(t){return Kc(t)?void 0:{value:t}},jl.prototype.fromInt32Value=function(t){var e;return Kc(e="object"==typeof t?t.value:t)?null:e},jl.prototype.toTimestamp=function(t){return{seconds:""+t.seconds,nanos:t.nanoseconds}},jl.prototype.fromTimestamp=function(t){if("string"==typeof t)return this.fromIso8601String(t);xr(!!t,"Cannot deserialize null or undefined timestamp.");var e=Ql(t.seconds||"0"),n=t.nanos||0;return new ro(e,n)},jl.prototype.fromIso8601String=function(t){var e=0,n=Bl.exec(t);if(xr(!!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 ro(o,e)},jl.prototype.toBytes=function(t){return this.options.useProto3Json?t.toBase64():this.unsafeCastProtoByteString(t.toUint8Array())},jl.prototype.fromBlob=function(t){return"string"==typeof t?(xr(this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Ei.fromBase64String(t)):(xr(!this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Ei.fromUint8Array(t))},jl.prototype.toVersion=function(t){return this.toTimestamp(t.toTimestamp())},jl.prototype.fromVersion=function(t){return xr(!!t,"Trying to deserialize version that isn't set"),oo.fromTimestamp(this.fromTimestamp(t))},jl.prototype.toResourceName=function(t,e){return this.fullyQualifiedPrefixPath(t).child("documents").child(e).canonicalString()},jl.prototype.fromResourceName=function(t){var e=Pi.fromString(t);return xr(this.isValidResourceName(e),"Tried to deserialize invalid key "+e.toString()),e},jl.prototype.toName=function(t){return this.toResourceName(this.databaseId,t.path)},jl.prototype.fromName=function(t){var e=this.fromResourceName(t);return xr(e.get(1)===this.databaseId.projectId,"Tried to deserialize key from different project: "+e.get(1)+" vs "+this.databaseId.projectId),xr(!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 Bi(this.extractLocalPathFromResourceName(e))},jl.prototype.toQueryPath=function(t){return this.toResourceName(this.databaseId,t)},jl.prototype.fromQueryPath=function(t){var e=this.fromResourceName(t);return 4===e.length?Pi.EMPTY_PATH:this.extractLocalPathFromResourceName(e)},Object.defineProperty(jl.prototype,"encodedDatabaseId",{get:function(){return new Pi(["projects",this.databaseId.projectId,"databases",this.databaseId.database]).canonicalString()},enumerable:!0,configurable:!0}),jl.prototype.fullyQualifiedPrefixPath=function(t){return new Pi(["projects",t.projectId,"databases",t.database])},jl.prototype.extractLocalPathFromResourceName=function(t){return xr(4<t.length&&"documents"===t.get(4),"tried to deserialize invalid key "+t.toString()),t.popFirst(5)},jl.prototype.isValidResourceName=function(t){return 4<=t.length&&"projects"===t.get(0)&&"databases"===t.get(2)},jl.prototype.toValue=function(t){if(t instanceof Wa)return{nullValue:"NULL_VALUE"};if(t instanceof Ha)return{booleanValue:t.value()};if(t instanceof es)return{integerValue:""+t.value()};if(t instanceof is){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 ss?{stringValue:t.value()}:t instanceof Cs?{mapValue:this.toMapValue(t)}:t instanceof As?{arrayValue:this.toArrayValue(t)}:t instanceof hs?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof Ss?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof ys?{bytesValue:this.toBytes(t.value())}:t instanceof bs?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:Lr("Unknown FieldValue "+JSON.stringify(t))},jl.prototype.fromValue=function(t){var e=this;if("nullValue"in t)return Wa.INSTANCE;if("booleanValue"in t)return Ha.of(t.booleanValue);if("integerValue"in t)return new es(Ql(t.integerValue));if("doubleValue"in t){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return is.NAN;if("Infinity"===t.doubleValue)return is.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return is.NEGATIVE_INFINITY}return new is(t.doubleValue)}if("stringValue"in t)return new ss(t.stringValue);if("mapValue"in t)return this.fromFields(t.mapValue.fields||{});if("arrayValue"in t){Ul(t.arrayValue,"arrayValue");var n=t.arrayValue.values||[];return new As(n.map(function(t){return e.fromValue(t)}))}if("timestampValue"in t)return Ul(t.timestampValue,"timestampValue"),new hs(this.fromTimestamp(t.timestampValue));if("geoPointValue"in t){Ul(t.geoPointValue,"geoPointValue");var r=t.geoPointValue.latitude||0,i=t.geoPointValue.longitude||0;return new Ss(new Gh(r,i))}if("bytesValue"in t){Ul(t.bytesValue,"bytesValue");var o=this.fromBlob(t.bytesValue);return new ys(o)}if("referenceValue"in t){Ul(t.referenceValue,"referenceValue");var a=this.fromResourceName(t.referenceValue),s=new Di(a.get(1),a.get(3)),u=new Bi(this.extractLocalPathFromResourceName(a));return new bs(s,u)}return Lr("Unknown Value proto "+JSON.stringify(t))},jl.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},jl.prototype.toDocument=function(t){return xr(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data()),updateTime:this.toTimestamp(t.version.toTimestamp())}},jl.prototype.fromDocument=function(t,e){var n=this,r=this.fromName(t.name),i=this.fromVersion(t.updateTime);return new Os(r,i,{hasCommittedMutations:!!e},void 0,t,function(t){return n.fromValue(t)})},jl.prototype.toFields=function(t){var n=this,r={};return t.forEach(function(t,e){r[t]=n.toValue(e)}),r},jl.prototype.fromFields=function(t){var n=this,e=t,r=Cs.EMPTY;return Hr(e,function(t,e){r=r.set(new Fi([t]),n.fromValue(e))}),r},jl.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},jl.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},jl.prototype.fromFound=function(t){var e=this;xr(!!t.found,"Tried to deserialize a found document from a missing document."),Ul(t.found.name,"doc.found.name"),Ul(t.found.updateTime,"doc.found.updateTime");var n=this.fromName(t.found.name),r=this.fromVersion(t.found.updateTime);return new Os(n,r,{},void 0,t.found,function(t){return e.fromValue(t)})},jl.prototype.fromMissing=function(t){xr(!!t.missing,"Tried to deserialize a missing document from a found document."),xr(!!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 xs(e,n)},jl.prototype.fromMaybeDocument=function(t){return"found"in t?this.fromFound(t):"missing"in t?this.fromMissing(t):Lr("invalid batch get response: "+JSON.stringify(t))},jl.prototype.toWatchTargetChangeState=function(t){switch(t){case _h.Added:return"ADD";case _h.Current:return"CURRENT";case _h.NoChange:return"NO_CHANGE";case _h.Removed:return"REMOVE";case _h.Reset:return"RESET";default:return Lr("Unknown WatchTargetChangeState: "+t)}},jl.prototype.toTestWatchChange=function(t){if(t instanceof Lh)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof Ph){if(t.newDoc instanceof Os){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 xs)return e=t.newDoc,{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 xh){var n=void 0;return t.cause&&(n={code:function(t){if(void 0===t)return fh.OK;switch(t){case Ur.OK:return fh.OK;case Ur.CANCELLED:return fh.CANCELLED;case Ur.UNKNOWN:return fh.UNKNOWN;case Ur.DEADLINE_EXCEEDED:return fh.DEADLINE_EXCEEDED;case Ur.RESOURCE_EXHAUSTED:return fh.RESOURCE_EXHAUSTED;case Ur.INTERNAL:return fh.INTERNAL;case Ur.UNAVAILABLE:return fh.UNAVAILABLE;case Ur.UNAUTHENTICATED:return fh.UNAUTHENTICATED;case Ur.INVALID_ARGUMENT:return fh.INVALID_ARGUMENT;case Ur.NOT_FOUND:return fh.NOT_FOUND;case Ur.ALREADY_EXISTS:return fh.ALREADY_EXISTS;case Ur.PERMISSION_DENIED:return fh.PERMISSION_DENIED;case Ur.FAILED_PRECONDITION:return fh.FAILED_PRECONDITION;case Ur.ABORTED:return fh.ABORTED;case Ur.OUT_OF_RANGE:return fh.OUT_OF_RANGE;case Ur.UNIMPLEMENTED:return fh.UNIMPLEMENTED;case Ur.DATA_LOSS:return fh.DATA_LOSS;default:return Lr("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 Lr("Unrecognized watch change: "+JSON.stringify(t))},jl.prototype.fromWatchChange=function(t){var e,n=this;if("targetChange"in t){Ul(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],o=t.targetChange.resumeToken||this.emptyByteString(),a=t.targetChange.cause,s=a&&this.fromRpcStatus(a);e=new xh(r,i,o,s||null)}else if("documentChange"in t){Ul(t.documentChange,"documentChange"),Ul(t.documentChange.document,"documentChange.name"),Ul(t.documentChange.document.name,"documentChange.document.name"),Ul(t.documentChange.document.updateTime,"documentChange.document.updateTime");var u=t.documentChange,c=this.fromName(u.document.name),h=this.fromVersion(u.document.updateTime),l=new Os(c,h,{},void 0,u.document,function(t){return n.fromValue(t)}),f=u.targetIds||[],p=u.removedTargetIds||[];e=new Ph(f,p,l.key,l)}else if("documentDelete"in t){Ul(t.documentDelete,"documentDelete"),Ul(t.documentDelete.document,"documentDelete.document");var d=t.documentDelete;c=this.fromName(d.document),h=d.readTime?this.fromVersion(d.readTime):oo.forDeletedDoc(),l=new xs(c,h),p=d.removedTargetIds||[],e=new Ph([],p,l.key,l)}else if("documentRemove"in t){Ul(t.documentRemove,"documentRemove"),Ul(t.documentRemove.document,"documentRemove");var m=t.documentRemove;c=this.fromName(m.document),p=m.removedTargetIds||[],e=new Ph([],p,c,null)}else{if(!("filter"in t))return Lr("Unknown change type "+JSON.stringify(t));Ul(t.filter,"filter"),Ul(t.filter.targetId,"filter.targetId");var y=t.filter,g=y.count||0,v=new Pl(g),b=y.targetId;e=new Lh(b,v)}return e},jl.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?_h.NoChange:"ADD"===t?_h.Added:"REMOVE"===t?_h.Removed:"CURRENT"===t?_h.Current:"RESET"===t?_h.Reset:Lr("Got unexpected TargetChange.state: "+t)},jl.prototype.versionFromListenResponse=function(t){if(!("targetChange"in t))return oo.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?oo.MIN:e.readTime?this.fromVersion(e.readTime):oo.MIN},jl.prototype.toMutation=function(t){var e,n=this;if(t instanceof Ca)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof Fa)e={delete:this.toName(t.key)};else if(t instanceof Aa)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof Ma))return Lr("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},jl.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):wa.NONE;if(t.update){Ul(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 Aa(r,i,o,n)}return new Ca(r,i,n)}if(t.delete)return r=this.fromName(t.delete),new Fa(r,n);if(t.transform){r=this.fromName(t.transform.document);var a=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return xr(!0===n.exists,'Transforms only support precondition "exists == true"'),new Ma(r,a)}return Lr("unknown mutation proto: "+JSON.stringify(t))},jl.prototype.toPrecondition=function(t){return xr(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:Lr("Unknown precondition")},jl.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?wa.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?wa.exists(t.exists):wa.NONE},jl.prototype.fromWriteResult=function(t,e){var n=this,r=t.updateTime?this.fromVersion(t.updateTime):this.fromVersion(e),i=null;return t.transformResults&&0<t.transformResults.length&&(i=t.transformResults.map(function(t){return n.fromValue(t)})),new ba(r,i)},jl.prototype.fromWriteResults=function(t,e){var n=this;return t&&0<t.length?(xr(void 0!==e,"Received a write result without a commit time"),t.map(function(t){return n.fromWriteResult(t,e)})):[]},jl.prototype.toFieldTransform=function(t){var e=this,n=t.transform;if(n instanceof Cl)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Nl)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements.map(function(t){return e.toValue(t)})}};if(n instanceof kl)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements.map(function(t){return e.toValue(t)})}};if(n instanceof Ml)return{fieldPath:t.field.canonicalString(),increment:this.toValue(n.operand)};throw Lr("Unknown transform: "+t.transform)},jl.prototype.fromFieldTransform=function(t){var e=this,n=null;if("setToServerValue"in t)xr("REQUEST_TIME"===t.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(t)),n=Cl.instance;else if("appendMissingElements"in t){var r=t.appendMissingElements.values||[];n=new Nl(r.map(function(t){return e.fromValue(t)}))}else if("removeAllFromArray"in t)r=t.removeAllFromArray.values||[],n=new kl(r.map(function(t){return e.fromValue(t)}));else if("increment"in t){var i=this.fromValue(t.increment);xr(i instanceof Ja,"NUMERIC_ADD transform requires a NumberValue"),n=new Ml(i)}else Lr("Unknown transform proto: "+JSON.stringify(t));var o=Fi.fromServerFormat(t.fieldPath);return new ma(o,n)},jl.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},jl.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;xr(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return Hh.atPath(this.fromQueryPath(n))},jl.prototype.toQueryTarget=function(t){var e={structuredQuery:{}},n=t.path;null!==t.collectionGroup?(xr(n.length%2==0,"Collection Group queries should be within a document path or root."),e.parent=this.toQueryPath(n),e.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(xr(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},jl.prototype.fromQueryTarget=function(t){var e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0,i=null;if(0<r){xr(1===r,"StructuredQuery.from with more than one collection is not supported.");var o=n.from[0];o.allDescendants?i=o.collectionId:e=e.child(o.collectionId)}var a=[];n.where&&(a=this.fromFilter(n.where));var s=[];n.orderBy&&(s=this.fromOrder(n.orderBy));var u=null;n.limit&&(u=this.fromInt32Value(n.limit));var c=null;n.startAt&&(c=this.fromCursor(n.startAt));var h=null;return n.endAt&&(h=this.fromCursor(n.endAt)),new Hh(e,i,s,a,u,c,h)},jl.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},jl.prototype.toLabel=function(t){switch(t){case xu.Listen:return null;case xu.ExistenceFilterMismatch:return"existence-filter-mismatch";case xu.LimboResolution:return"limbo-document";default:return Lr("Unrecognized query purpose: "+t)}},jl.prototype.toTarget=function(t){var e,n=t.query;return(e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)}).targetId=t.targetId,0<t.resumeToken.length&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},jl.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(t){return t instanceof tl?e.toUnaryOrFieldFilter(t):Lr("Unrecognized filter: "+JSON.stringify(t))});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},jl.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromFieldFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):Lr("Unknown filter: "+JSON.stringify(t)):[]},jl.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},jl.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},jl.prototype.toCursor=function(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},jl.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new bl(r,n)},jl.prototype.toDirection=function(t){return Fl[t.name]},jl.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return gl.ASCENDING;case"DESCENDING":return gl.DESCENDING;default:return}},jl.prototype.toOperatorName=function(t){return Vl[t.name]},jl.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return Jh.EQUAL;case"GREATER_THAN":return Jh.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return Jh.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return Jh.LESS_THAN;case"LESS_THAN_OR_EQUAL":return Jh.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return Jh.ARRAY_CONTAINS;case"IN":return Jh.IN;case"ARRAY_CONTAINS_ANY":return Jh.ARRAY_CONTAINS_ANY;case"OPERATOR_UNSPECIFIED":return Lr("Unspecified operator");default:return Lr("Unknown operator")}},jl.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},jl.prototype.fromFieldPathReference=function(t){return Fi.fromServerFormat(t.fieldPath)},jl.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},jl.prototype.fromPropertyOrder=function(t){return new El(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},jl.prototype.fromFieldFilter=function(t){return tl.create(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},jl.prototype.toUnaryOrFieldFilter=function(t){if(t.op===Jh.EQUAL){if(t.value.isEqual(is.NAN))return{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}};if(t.value.isEqual(Wa.INSTANCE))return{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}}return{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}},jl.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return tl.create(e,Jh.EQUAL,is.NAN);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return tl.create(n,Jh.EQUAL,Wa.INSTANCE);case"OPERATOR_UNSPECIFIED":return Lr("Unspecified filter");default:return Lr("Unknown filter")}},jl.prototype.toDocumentMask=function(t){var e=[];return t.fields.forEach(function(t){return e.push(t.canonicalString())}),{fieldPaths:e}},jl.prototype.fromDocumentMask=function(t){var e=(t.fieldPaths||[]).map(function(t){return Fi.fromServerFormat(t)});return pa.fromArray(e)},jl);function jl(t,e){this.databaseId=t,this.options=e}var Wl=function(){this.viewSnap=null,this.targetId=0,this.listeners=[]},Gl=(zl.prototype.listen=function(t){var e=t.query,n=!1,r=this.queries.get(e);return r||(n=!0,r=new Wl,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}):Promise.resolve(r.targetId)},zl.prototype.unlisten=function(o){return p(this,void 0,void 0,function(){var e,n,r,i;return d(this,function(t){return e=o.query,n=!1,(r=this.queries.get(e))&&0<=(i=r.listeners.indexOf(o))&&(r.listeners.splice(i,1),n=0===r.listeners.length),n?(this.queries.delete(e),[2,this.syncEngine.unlisten(e)]):[2]})})},zl.prototype.onWatchChange=function(t){for(var e=0,n=t;e<n.length;e++){var r=n[e],i=r.query,o=this.queries.get(i);if(o){for(var a=0,s=o.listeners;a<s.length;a++)s[a].onViewSnapshot(r);o.viewSnap=r}}},zl.prototype.onWatchError=function(t,e){var n=this.queries.get(t);if(n)for(var r=0,i=n.listeners;r<i.length;r++)i[r].onError(e);this.queries.delete(t)},zl.prototype.onOnlineStateChange=function(i){this.onlineState=i,this.queries.forEach(function(t,e){for(var n=0,r=e.listeners;n<r.length;n++)r[n].applyOnlineStateChange(i)})},zl);function zl(t){this.syncEngine=t,this.queries=new Us(function(t){return t.canonicalId()}),this.onlineState=ah.Unknown,this.syncEngine.subscribe(this)}var Hl=(Yl.prototype.onViewSnapshot=function(t){if(xr(0<t.docChanges.length||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeMetadataChanges){for(var e=[],n=0,r=t.docChanges;n<r.length;n++){var i=r[n];i.type!==vh.Metadata&&e.push(i)}t=new Dh(t.query,t.docs,t.oldDocs,e,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0)}this.raisedInitialEvent?this.shouldRaiseEvent(t)&&this.queryObserver.next(t):this.shouldRaiseInitialEvent(t,this.onlineState)&&this.raiseInitialEvent(t),this.snap=t},Yl.prototype.onError=function(t){this.queryObserver.error(t)},Yl.prototype.applyOnlineStateChange=function(t){this.onlineState=t,this.snap&&!this.raisedInitialEvent&&this.shouldRaiseInitialEvent(this.snap,t)&&this.raiseInitialEvent(this.snap)},Yl.prototype.shouldRaiseInitialEvent=function(t,e){if(xr(!this.raisedInitialEvent,"Determining whether to raise first event but already had first event"),!t.fromCache)return!0;var n=e!==ah.Offline;return this.options.waitForSyncWhenOnline&&n?(xr(t.fromCache,"Waiting for sync, but snapshot is not from cache"),!1):!t.docs.isEmpty()||e===ah.Offline},Yl.prototype.shouldRaiseEvent=function(t){if(0<t.docChanges.length)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeMetadataChanges},Yl.prototype.raiseInitialEvent=function(t){xr(!this.raisedInitialEvent,"Trying to raise initial events for second time"),t=Dh.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache),this.raisedInitialEvent=!0,this.queryObserver.next(t)},Yl);function Yl(t,e,n){this.query=t,this.queryObserver=e,this.raisedInitialEvent=!1,this.snap=null,this.onlineState=ah.Unknown,this.options=n||{}}var Xl=(Jl.fromSnapshot=function(t,e){for(var n=Ao(),r=Ao(),i=0,o=e.docChanges;i<o.length;i++){var a=o[i];switch(a.type){case vh.Added:n=n.add(a.doc.key);break;case vh.Removed:r=r.add(a.doc.key)}}return new Jl(t,n,r)},Jl);function Jl(t,e,n){this.targetId=t,this.addedKeys=e,this.removedKeys=n}var $l=function(t){this.key=t},Zl=function(t){this.key=t},tf=(Object.defineProperty(ef.prototype,"syncedDocuments",{get:function(){return this._syncedDocuments},enumerable:!0,configurable:!0}),ef.prototype.computeDocChanges=function(t,e){var s=this,u=e?e.changeSet:new Ih,c=e?e.documentSet:this.documentSet,h=e?e.mutatedKeys:this.mutatedKeys,l=c,f=!1,p=this.query.hasLimit()&&c.size===this.query.limit?c.last():null;if(t.inorderTraversal(function(t,e){var n=c.get(t),r=e instanceof Os?e:null;r&&(xr(t.isEqual(r.key),"Mismatching keys found in document changes: "+t+" != "+r.key),r=s.query.matches(r)?r:null);var i=!!n&&s.mutatedKeys.has(n.key),o=!!r&&(r.hasLocalMutations||s.mutatedKeys.has(r.key)&&r.hasCommittedMutations),a=!1;n&&r?n.data().isEqual(r.data())?i!==o&&(u.track({type:vh.Metadata,doc:r}),a=!0):s.shouldWaitForSyncedDocument(n,r)||(u.track({type:vh.Modified,doc:r}),a=!0,p&&0<s.query.docComparator(r,p)&&(f=!0)):!n&&r?(u.track({type:vh.Added,doc:r}),a=!0):n&&!r&&(u.track({type:vh.Removed,doc:n}),a=!0,p&&(f=!0)),a&&(h=r?(l=l.add(r),o?h.add(t):h.delete(t)):(l=l.delete(t),h.delete(t)))}),this.query.hasLimit())for(;l.size>this.query.limit;){var n=l.last();l=l.delete(n.key),h=h.delete(n.key),u.track({type:vh.Removed,doc:n})}return xr(!f||!e,"View was refilled using docs that themselves needed refilling."),{documentSet:l,changeSet:u,needsRefill:f,mutatedKeys:h}},ef.prototype.shouldWaitForSyncedDocument=function(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations},ef.prototype.applyChanges=function(t,e,n){var r=this;xr(!t.needsRefill,"Cannot apply changes that need a refill");var i=this.documentSet;this.documentSet=t.documentSet,this.mutatedKeys=t.mutatedKeys;var o=t.changeSet.getChanges();o.sort(function(t,e){return function(t,e){function n(t){switch(t){case vh.Added:return 1;case vh.Modified:case vh.Metadata:return 2;case vh.Removed:return 0;default:return Lr("Unknown ChangeType: "+t)}}return n(t)-n(e)}(t.type,e.type)||r.query.docComparator(t.doc,e.doc)}),this.applyTargetChange(n);var a=e?this.updateLimboDocuments():[],s=0===this.limboDocuments.size&&this.current?wh.Synced:wh.Local,u=s!==this.syncState;return this.syncState=s,0!==o.length||u?{snapshot:new Dh(this.query,t.documentSet,i,o,t.mutatedKeys,s===wh.Local,u,!1),limboChanges:a}:{limboChanges:a}},ef.prototype.applyOnlineStateChange=function(t){return this.current&&t===ah.Offline?(this.current=!1,this.applyChanges({documentSet:this.documentSet,changeSet:new Ih,mutatedKeys:this.mutatedKeys,needsRefill:!1},!1)):{limboChanges:[]}},ef.prototype.shouldBeInLimbo=function(t){return!this._syncedDocuments.has(t)&&!!this.documentSet.has(t)&&!this.documentSet.get(t).hasLocalMutations},ef.prototype.applyTargetChange=function(t){var e=this;t&&(t.addedDocuments.forEach(function(t){return e._syncedDocuments=e._syncedDocuments.add(t)}),t.modifiedDocuments.forEach(function(t){return xr(e._syncedDocuments.has(t),"Modified document "+t+" not found in view.")}),t.removedDocuments.forEach(function(t){return e._syncedDocuments=e._syncedDocuments.delete(t)}),this.current=t.current)},ef.prototype.updateLimboDocuments=function(){var e=this;if(!this.current)return[];var n=this.limboDocuments;this.limboDocuments=Ao(),this.documentSet.forEach(function(t){e.shouldBeInLimbo(t.key)&&(e.limboDocuments=e.limboDocuments.add(t.key))});var r=[];return n.forEach(function(t){e.limboDocuments.has(t)||r.push(new Zl(t))}),this.limboDocuments.forEach(function(t){n.has(t)||r.push(new $l(t))}),r},ef.prototype.synchronizeWithPersistedState=function(t,e){this._syncedDocuments=e,this.limboDocuments=Ao();var n=this.computeDocChanges(t);return this.applyChanges(n,!0)},ef.prototype.computeInitialSnapshot=function(){return Dh.fromInitialDocuments(this.query,this.documentSet,this.mutatedKeys,this.syncState===wh.Local)},ef);function ef(t,e){this.query=t,this._syncedDocuments=e,this.syncState=null,this.current=!1,this.limboDocuments=Ao(),this.mutatedKeys=Ao(),this.documentSet=new Sh(t.docComparator.bind(t))}var nf=(rf.prototype.run=function(){this.runWithBackOff()},rf.prototype.runWithBackOff=function(){var t=this;this.backoff.backoffAndRun(function(){return p(t,void 0,void 0,function(){var e,n,r=this;return d(this,function(t){return e=this.remoteStore.createTransaction(),(n=this.tryRunUpdateFunction(e))&&n.then(function(t){r.asyncQueue.enqueueAndForget(function(){return e.commit().then(function(){r.deferred.resolve(t)}).catch(function(t){r.handleTransactionError(t)})})}).catch(function(t){r.handleTransactionError(t)}),[2]})})})},rf.prototype.tryRunUpdateFunction=function(t){try{var e=this.updateFunction(t);return!Kc(e)&&e.catch&&e.then?e:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(t){return this.deferred.reject(t),null}},rf.prototype.handleTransactionError=function(t){var e=this;0<this.retries&&this.isRetryableTransactionError(t)?(this.retries-=1,this.asyncQueue.enqueueAndForget(function(){return e.runWithBackOff(),Promise.resolve()})):this.deferred.reject(t)},rf.prototype.isRetryableTransactionError=function(t){if("FirebaseError"!==t.name)return!1;var e=t.code;return"aborted"===e||"failed-precondition"===e||!yh(e)},rf);function rf(t,e,n,r){this.asyncQueue=t,this.remoteStore=e,this.updateFunction=n,this.deferred=r,this.retries=5,this.backoff=new Wc(this.asyncQueue,Qi.RetryTransaction)}var of="SyncEngine",af=function(t,e,n){this.query=t,this.targetId=e,this.view=n},sf=function(t){this.key=t,this.receivedDocument=!1},uf=(Object.defineProperty(cf.prototype,"isPrimaryClient",{get:function(){return!0===this.isPrimary},enumerable:!0,configurable:!0}),cf.prototype.subscribe=function(t){xr(null!==t,"SyncEngine listener cannot be null"),xr(null===this.syncEngineListener,"SyncEngine already has a subscriber."),this.syncEngineListener=t},cf.prototype.listen=function(a){return p(this,void 0,void 0,function(){var e,n,r,i,o;return d(this,function(t){switch(t.label){case 0:return this.assertSubscribed("listen()"),(r=this.queryViewsByQuery.get(a))?(e=r.targetId,this.sharedClientState.addLocalQueryTarget(e),n=r.view.computeInitialSnapshot(),[3,4]):[3,1];case 1:return[4,this.localStore.allocateQuery(a)];case 2:return i=t.sent(),o=this.sharedClientState.addLocalQueryTarget(i.targetId),e=i.targetId,[4,this.initializeViewAndComputeSnapshot(i,"current"===o)];case 3:n=t.sent(),this.isPrimary&&this.remoteStore.listen(i),t.label=4;case 4:return this.syncEngineListener.onWatchChange([n]),[2,e]}})})},cf.prototype.initializeViewAndComputeSnapshot=function(c,h){return p(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u;return d(this,function(t){switch(t.label){case 0:return e=c.query,[4,this.localStore.executeQuery(e)];case 1:return n=t.sent(),[4,this.localStore.remoteDocumentKeys(c.targetId)];case 2:return r=t.sent(),i=new tf(e,r),o=i.computeDocChanges(n),a=Rh.createSynthesizedTargetChangeForCurrentChange(c.targetId,h&&this.onlineState!==ah.Offline),xr(0===(s=i.applyChanges(o,!0===this.isPrimary,a)).limboChanges.length,"View returned limbo docs before target ack from the server."),xr(!!s.snapshot,"applyChanges for new view should always return a snapshot"),u=new af(e,c.targetId,i),this.queryViewsByQuery.set(e,u),this.queryViewsByTarget[c.targetId]=u,[2,s.snapshot]}})})},cf.prototype.synchronizeViewAndComputeSnapshot=function(i){return p(this,void 0,void 0,function(){var e,n,r;return d(this,function(t){switch(t.label){case 0:return[4,this.localStore.executeQuery(i.query)];case 1:return e=t.sent(),[4,this.localStore.remoteDocumentKeys(i.targetId)];case 2:return n=t.sent(),r=i.view.synchronizeWithPersistedState(e,n),this.isPrimary&&this.updateTrackedLimbos(i.targetId,r.limboChanges),[2,r]}})})},cf.prototype.unlisten=function(r){return p(this,void 0,void 0,function(){var e,n=this;return d(this,function(t){switch(t.label){case 0:return this.assertSubscribed("unlisten()"),xr(!!(e=this.queryViewsByQuery.get(r)),"Trying to unlisten on query not found:"+r),this.isPrimary?(this.sharedClientState.removeLocalQueryTarget(e.targetId),this.sharedClientState.isActiveQueryTarget(e.targetId)?[3,2]:[4,this.localStore.releaseQuery(r,!1).then(function(){n.sharedClientState.clearQueryState(e.targetId),n.remoteStore.unlisten(e.targetId),n.removeAndCleanupQuery(e)}).catch(hc)]):[3,3];case 1:t.sent(),t.label=2;case 2:return[3,5];case 3:return this.removeAndCleanupQuery(e),[4,this.localStore.releaseQuery(r,!0)];case 4:t.sent(),t.label=5;case 5:return[2]}})})},cf.prototype.write=function(n,r){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return this.assertSubscribed("write()"),[4,this.localStore.localWrite(n)];case 1:return e=t.sent(),this.sharedClientState.addPendingMutation(e.batchId),this.addMutationCallback(e.batchId,r),[4,this.emitNewSnapsAndNotifyLocalStore(e.changes)];case 2:return t.sent(),[4,this.remoteStore.fillWritePipeline()];case 3:return t.sent(),[2]}})})},cf.prototype.runTransaction=function(t,e,n){new nf(t,this.remoteStore,e,n).run()},cf.prototype.applyRemoteEvent=function(n){return p(this,void 0,void 0,function(){var e,r=this;return d(this,function(t){switch(t.label){case 0:this.assertSubscribed("applyRemoteEvent()"),t.label=1;case 1:return t.trys.push([1,4,,6]),[4,this.localStore.applyRemoteEvent(n)];case 2:return e=t.sent(),Hr(n.targetChanges,function(t,e){var n=r.limboResolutionsByTarget[Number(t)];n&&(xr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1,"Limbo resolution for single document contains multiple changes."),0<e.addedDocuments.size?n.receivedDocument=!0:0<e.modifiedDocuments.size?xr(n.receivedDocument,"Received change for limbo target document without add."):0<e.removedDocuments.size&&(xr(n.receivedDocument,"Received remove for limbo target document without add."),n.receivedDocument=!1))}),[4,this.emitNewSnapsAndNotifyLocalStore(e,n)];case 3:return t.sent(),[3,6];case 4:return[4,hc(t.sent())];case 5:return t.sent(),[3,6];case 6:return[2]}})})},cf.prototype.applyOnlineStateChange=function(r,t){if(this.isPrimary&&t===uh.RemoteStore||!this.isPrimary&&t===uh.SharedClientState){this.assertSubscribed("applyOnlineStateChange()");var i=[];this.queryViewsByQuery.forEach(function(t,e){var n=e.view.applyOnlineStateChange(r);xr(0===n.limboChanges.length,"OnlineState should not affect limbo documents."),n.snapshot&&i.push(n.snapshot)}),this.syncEngineListener.onOnlineStateChange(r),this.syncEngineListener.onWatchChange(i),this.onlineState=r,this.isPrimary&&this.sharedClientState.setOnlineState(r)}},cf.prototype.rejectListen=function(u,c){return p(this,void 0,void 0,function(){var e,n,r,i,o,a,s=this;return d(this,function(t){switch(t.label){case 0:return this.assertSubscribed("rejectListens()"),this.sharedClientState.updateQueryState(u,"rejected",c),e=this.limboResolutionsByTarget[u],(n=e&&e.key)?(this.limboTargetsByKey=this.limboTargetsByKey.remove(n),delete this.limboResolutionsByTarget[u],r=(r=new so(Bi.comparator)).insert(n,new xs(n,oo.forDeletedDoc())),i=Ao().add(n),o=new Ah(oo.MIN,{},new yo(yi),r,i),[2,this.applyRemoteEvent(o)]):[3,1];case 1:return xr(!!(a=this.queryViewsByTarget[u]),"Unknown targetId: "+u),[4,this.localStore.releaseQuery(a.query,!1).then(function(){return s.removeAndCleanupQuery(a)}).catch(hc)];case 2:t.sent(),this.syncEngineListener.onWatchError(a.query,c),t.label=3;case 3:return[2]}})})},cf.prototype.applyBatchState=function(n,r,i){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return this.assertSubscribed("applyBatchState()"),[4,this.localStore.lookupMutationDocuments(n)];case 1:return null===(e=t.sent())?(_r(of,"Cannot apply mutation batch with id: "+n),[2]):"pending"!==r?[3,3]:[4,this.remoteStore.fillWritePipeline()];case 2:return t.sent(),[3,4];case 3:"acknowledged"===r||"rejected"===r?(this.processUserCallback(n,i||null),this.localStore.removeCachedMutationBatchMetadata(n)):Lr("Unknown batchState: "+r),t.label=4;case 4:return[4,this.emitNewSnapsAndNotifyLocalStore(e)];case 5:return t.sent(),[2]}})})},cf.prototype.applySuccessfulWrite=function(r){return p(this,void 0,void 0,function(){var e,n;return d(this,function(t){switch(t.label){case 0:this.assertSubscribed("applySuccessfulWrite()"),e=r.batch.batchId,this.processUserCallback(e,null),this.triggerPendingWritesCallbacks(e),t.label=1;case 1:return t.trys.push([1,4,,6]),[4,this.localStore.acknowledgeBatch(r)];case 2:return n=t.sent(),this.sharedClientState.updateMutationState(e,"acknowledged"),[4,this.emitNewSnapsAndNotifyLocalStore(n)];case 3:return t.sent(),[3,6];case 4:return[4,hc(t.sent())];case 5:return t.sent(),[3,6];case 6:return[2]}})})},cf.prototype.rejectFailedWrite=function(n,r){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(n,r),this.triggerPendingWritesCallbacks(n),t.label=1;case 1:return t.trys.push([1,4,,6]),[4,this.localStore.rejectBatch(n)];case 2:return e=t.sent(),this.sharedClientState.updateMutationState(n,"rejected",r),[4,this.emitNewSnapsAndNotifyLocalStore(e)];case 3:return t.sent(),[3,6];case 4:return[4,hc(t.sent())];case 5:return t.sent(),[3,6];case 6:return[2]}})})},cf.prototype.registerPendingWritesCallback=function(r){return p(this,void 0,void 0,function(){var e,n;return d(this,function(t){switch(t.label){case 0:return this.remoteStore.canUseNetwork()||_r(of,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),[4,this.localStore.getHighestUnacknowledgedBatchId()];case 1:return-1===(e=t.sent())?r.resolve():((n=this.pendingWritesCallbacks.get(e)||[]).push(r),this.pendingWritesCallbacks.set(e,n)),[2]}})})},cf.prototype.triggerPendingWritesCallbacks=function(t){(this.pendingWritesCallbacks.get(t)||[]).forEach(function(t){t.resolve()}),this.pendingWritesCallbacks.delete(t)},cf.prototype.rejectOutstandingPendingWritesCallbacks=function(e){this.pendingWritesCallbacks.forEach(function(t){t.forEach(function(t){t.reject(new Qr(Ur.CANCELLED,e))})}),this.pendingWritesCallbacks.clear()},cf.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n=(n=n||new so(yi)).insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},cf.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(xr(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}},cf.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)})}},cf.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])},cf.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n<r.length;n++){var i=r[n];i instanceof $l?(this.limboDocumentRefs.addReference(i.key,t),this.trackLimboChange(i)):i instanceof Zl?(_r(of,"Document no longer in limbo: "+i.key),this.limboDocumentRefs.removeReference(i.key,t),this.limboDocumentRefs.containsKey(i.key)||this.removeLimboTarget(i.key)):Lr("Unknown limbo change: "+JSON.stringify(i))}},cf.prototype.trackLimboChange=function(t){var e=t.key;if(!this.limboTargetsByKey.get(e)){_r(of,"New document in limbo: "+e);var n=this.limboTargetIdGenerator.next(),r=Hh.atPath(e.path);this.limboResolutionsByTarget[n]=new sf(e),this.remoteStore.listen(new Qu(r,n,xu.LimboResolution,Ai.INVALID)),this.limboTargetsByKey=this.limboTargetsByKey.insert(e,n)}},cf.prototype.currentLimboDocs=function(){return this.limboTargetsByKey},cf.prototype.emitNewSnapsAndNotifyLocalStore=function(n,u){return p(this,void 0,void 0,function(){var o,a,e,s=this;return d(this,function(t){switch(t.label){case 0:return o=[],a=[],e=[],this.queryViewsByQuery.forEach(function(t,i){e.push(Promise.resolve().then(function(){var e=i.view.computeDocChanges(n);return e.needsRefill?s.localStore.executeQuery(i.query).then(function(t){return i.view.computeDocChanges(t,e)}):e}).then(function(t){var e=u&&u.targetChanges[i.targetId],n=i.view.applyChanges(t,!0===s.isPrimary,e);if(s.updateTrackedLimbos(i.targetId,n.limboChanges),n.snapshot){s.isPrimary&&s.sharedClientState.updateQueryState(i.targetId,n.snapshot.fromCache?"not-current":"current"),o.push(n.snapshot);var r=Xl.fromSnapshot(i.targetId,n.snapshot);a.push(r)}}))}),[4,Promise.all(e)];case 1:return t.sent(),this.syncEngineListener.onWatchChange(o),[4,this.localStore.notifyLocalViewChanges(a)];case 2:return t.sent(),[2]}})})},cf.prototype.assertSubscribed=function(t){xr(null!==this.syncEngineListener,"Trying to call "+t+" before calling subscribe().")},cf.prototype.handleCredentialChange=function(r){return p(this,void 0,void 0,function(){var e,n;return d(this,function(t){switch(t.label){case 0:return e=!this.currentUser.isEqual(r),this.currentUser=r,e?(this.rejectOutstandingPendingWritesCallbacks("'waitForPendingWrites' promise is rejected due to a user change."),[4,this.localStore.handleUserChange(r)]):[3,3];case 1:return n=t.sent(),this.sharedClientState.handleUserChange(r,n.removedBatchIds,n.addedBatchIds),[4,this.emitNewSnapsAndNotifyLocalStore(n.affectedDocuments)];case 2:t.sent(),t.label=3;case 3:return[4,this.remoteStore.handleCredentialChange()];case 4:return t.sent(),[2]}})})},cf.prototype.applyPrimaryState=function(c){return p(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u=this;return d(this,function(t){switch(t.label){case 0:return!0!==c||!0===this.isPrimary?[3,3]:(this.isPrimary=!0,[4,this.remoteStore.applyPrimaryState(!0)]);case 1:return t.sent(),e=this.sharedClientState.getAllActiveQueryTargets(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(e.toArray())];case 2:for(n=t.sent(),r=0,i=n;r<i.length;r++)o=i[r],this.remoteStore.listen(o);return[3,7];case 3:return!1!==c||!1===this.isPrimary?[3,7]:(this.isPrimary=!1,a=[],s=Promise.resolve(),zr(this.queryViewsByTarget,function(t,e){u.sharedClientState.isLocalQueryTarget(t)?a.push(t):s=s.then(function(){return u.unlisten(e.query)}),u.remoteStore.unlisten(e.targetId)}),[4,s]);case 4:return t.sent(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(a)];case 5:return t.sent(),this.resetLimboDocuments(),[4,this.remoteStore.applyPrimaryState(!1)];case 6:t.sent(),t.label=7;case 7:return[2]}})})},cf.prototype.resetLimboDocuments=function(){var e=this;zr(this.limboResolutionsByTarget,function(t){e.remoteStore.unlisten(t)}),this.limboDocumentRefs.removeAllReferences(),this.limboResolutionsByTarget=[],this.limboTargetsByKey=new so(Bi.comparator)},cf.prototype.synchronizeQueryViewsAndRaiseSnapshots=function(h){return p(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u,c;return d(this,function(t){switch(t.label){case 0:e=[],n=[],r=0,i=h,t.label=1;case 1:return r<i.length?(o=i[r],a=void 0,(s=this.queryViewsByTarget[o])?[4,this.localStore.releaseQuery(s.query,!0)]:[3,5]):[3,11];case 2:return t.sent(),[4,this.localStore.allocateQuery(s.query)];case 3:return a=t.sent(),[4,this.synchronizeViewAndComputeSnapshot(s)];case 4:return(u=t.sent()).snapshot&&n.push(u.snapshot),[3,9];case 5:return xr(!0===this.isPrimary,"A secondary tab should never have an active query without an active view."),[4,this.localStore.getQueryForTarget(o)];case 6:return xr(!!(c=t.sent()),"Query data for target "+o+" not found"),[4,this.localStore.allocateQuery(c)];case 7:return a=t.sent(),[4,this.initializeViewAndComputeSnapshot(a,!1)];case 8:t.sent(),t.label=9;case 9:e.push(a),t.label=10;case 10:return r++,[3,1];case 11:return this.syncEngineListener.onWatchChange(n),[2,e]}})})},cf.prototype.getActiveClients=function(){return this.localStore.getActiveClients()},cf.prototype.applyTargetState=function(a,s,u){return p(this,void 0,void 0,function(){var e,n,r,i,o;return d(this,function(t){switch(t.label){case 0:if(this.isPrimary)return _r(of,"Ignoring unexpected query state notification."),[2];if(!this.queryViewsByTarget[a])return[3,11];switch(s){case"current":case"not-current":return[3,1];case"rejected":return[3,8]}return[3,10];case 1:return t.trys.push([1,4,,8]),[4,this.localStore.getNewDocumentChanges()];case 2:return e=t.sent(),n=Ah.createSynthesizedRemoteEventForCurrentChange(a,"current"===s),[4,this.emitNewSnapsAndNotifyLocalStore(e,n)];case 3:return t.sent(),[3,11];case 4:return function(t){return t.code===Ur.DATA_LOSS&&t.message===Gs}(r=t.sent())?(i=[],zr(this.queryViewsByTarget,function(t){return i.push(t)}),[4,this.synchronizeQueryViewsAndRaiseSnapshots(i)]):[3,6];case 5:return t.sent(),[3,7];case 6:throw r;case 7:return[3,8];case 8:return o=this.queryViewsByTarget[a],this.removeAndCleanupQuery(o),[4,this.localStore.releaseQuery(o.query,!0)];case 9:return t.sent(),this.syncEngineListener.onWatchError(o.query,u),[3,11];case 10:Lr("Unexpected target state: "+s),t.label=11;case 11:return[2]}})})},cf.prototype.applyActiveTargetsChange=function(l,f){return p(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u,c,h=this;return d(this,function(t){switch(t.label){case 0:if(!this.isPrimary)return[2];e=0,n=l,t.label=1;case 1:return e<n.length?(c=n[e],xr(!this.queryViewsByTarget[c],"Trying to add an already active target"),[4,this.localStore.getQueryForTarget(c)]):[3,6];case 2:return xr(!!(r=t.sent()),"Query data for active target "+c+" not found"),[4,this.localStore.allocateQuery(r)];case 3:return i=t.sent(),[4,this.initializeViewAndComputeSnapshot(i,!1)];case 4:t.sent(),this.remoteStore.listen(i),t.label=5;case 5:return e++,[3,1];case 6:o=function(e){var n;return d(this,function(t){switch(t.label){case 0:return(n=a.queryViewsByTarget[e])?[4,a.localStore.releaseQuery(n.query,!1).then(function(){h.remoteStore.unlisten(e),h.removeAndCleanupQuery(n)}).catch(hc)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},a=this,s=0,u=f,t.label=7;case 7:return s<u.length?(c=u[s],[5,o(c)]):[3,10];case 8:t.sent(),t.label=9;case 9:return s++,[3,7];case 10:return[2]}})})},cf.prototype.enableNetwork=function(){return this.localStore.setNetworkEnabled(!0),this.remoteStore.enableNetwork()},cf.prototype.disableNetwork=function(){return this.localStore.setNetworkEnabled(!1),this.remoteStore.disableNetwork()},cf.prototype.getRemoteKeysForTarget=function(t){var e=this.limboResolutionsByTarget[t];return e&&e.receivedDocument?Ao().add(e.key):this.queryViewsByTarget[t]?this.queryViewsByTarget[t].view.syncedDocuments:Ao()},cf);function cf(t,e,n,r){this.localStore=t,this.remoteStore=e,this.sharedClientState=n,this.currentUser=r,this.syncEngineListener=null,this.queryViewsByQuery=new Us(function(t){return t.canonicalId()}),this.queryViewsByTarget={},this.limboTargetsByKey=new so(Bi.comparator),this.limboResolutionsByTarget={},this.limboDocumentRefs=new vc,this.mutationUserCallbacks={},this.pendingWritesCallbacks=new Map,this.limboTargetIdGenerator=zo.forSyncEngine(),this.isPrimary=void 0,this.onlineState=ah.Unknown}var hf=(lf.prototype.isAuthenticated=function(){return null!=this.uid},lf.prototype.toKey=function(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"},lf.prototype.isEqual=function(t){return t.uid===this.uid},lf.UNAUTHENTICATED=new lf(null),lf.GOOGLE_CREDENTIALS=new lf("google-credentials-uid"),lf.FIRST_PARTY=new lf("first-party-uid"),lf);function lf(t){this.uid=t}var ff="SharedClientState",pf="firestore_clients",df="firestore_mutations",mf="firestore_targets",yf=(gf.fromWebStorageEntry=function(t,e,n){var r=JSON.parse(n),i="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error),o=void 0;return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(o=new Qr(r.error.code,r.error.message)),i?new gf(t,e,r.state,o):(Or(ff,"Failed to parse mutation state for ID '"+e+"': "+n),null)},gf.prototype.toWebStorageJSON=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)},gf);function gf(t,e,n,r){this.user=t,this.batchId=e,this.state=n,xr(void 0!==(this.error=r)==("rejected"===n),"MutationMetadata must contain an error iff state is 'rejected'")}var vf=(bf.fromWebStorageEntry=function(t,e){var n=JSON.parse(e),r="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error),i=void 0;return r&&n.error&&(r="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(i=new Qr(n.error.code,n.error.message)),r?new bf(t,n.state,i):(Or(ff,"Failed to parse target state for ID '"+t+"': "+e),null)},bf.prototype.toWebStorageJSON=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)},bf);function bf(t,e,n){this.targetId=t,this.state=e,xr(void 0!==(this.error=n)==("rejected"===e),"QueryTargetMetadata must contain an error iff state is 'rejected'")}var wf=(Ef.fromWebStorageEntry=function(t,e){for(var n=JSON.parse(e),r="object"==typeof n&&n.activeTargetIds instanceof Array,i=Ro(),o=0;r&&o<n.activeTargetIds.length;++o)r=jc(n.activeTargetIds[o]),i=i.add(n.activeTargetIds[o]);return r?new Ef(t,i):(Or(ff,"Failed to parse client data for instance '"+t+"': "+e),null)},Ef);function Ef(t,e){this.clientId=t,this.activeTargetIds=e}var Sf=(Tf.fromWebStorageEntry=function(t){var e=JSON.parse(t);return"object"==typeof e&&e.onlineState in ah&&"string"==typeof e.clientId?new Tf(e.clientId,ah[e.onlineState]):(Or(ff,"Failed to parse online state: "+t),null)},Tf);function Tf(t,e){this.clientId=t,this.onlineState=e}var If=(Cf.prototype.addQueryTarget=function(t){xr(!this.activeTargetIds.has(t),"Target with ID '"+t+"' already active."),this.activeTargetIds=this.activeTargetIds.add(t)},Cf.prototype.removeQueryTarget=function(t){this.activeTargetIds=this.activeTargetIds.delete(t)},Cf.prototype.toWebStorageJSON=function(){var t={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(t)},Cf);function Cf(){this.activeTargetIds=Ro()}var Df=(Nf.isAvailable=function(t){return!(!t.window||null==t.window.localStorage)},Nf.prototype.start=function(){return p(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u,c,h,l,f=this;return d(this,function(t){switch(t.label){case 0:return xr(!this.started,"WebStorageSharedClientState already started"),xr(null!==this.syncEngine,"syncEngine property must be set before calling start()"),xr(null!==this.onlineStateHandler,"onlineStateHandler property must be set before calling start()"),[4,this.syncEngine.getActiveClients()];case 1:for(e=t.sent(),n=0,r=e;n<r.length;n++)(i=r[n])!==this.localClientId&&(o=this.getItem(this.toWebStorageClientStateKey(i)))&&(a=wf.fromWebStorageEntry(i,o))&&(this.activeClients[a.clientId]=a);for(this.persistClientState(),(s=this.storage.getItem(this.onlineStateKey))&&(u=this.fromWebStorageOnlineState(s))&&this.handleOnlineStateEvent(u),c=0,h=this.earlyEvents;c<h.length;c++)l=h[c],this.handleWebStorageEvent(l);return this.earlyEvents=[],this.platform.window.addEventListener("unload",function(){return f.shutdown()}),this.started=!0,[2]}})})},Nf.prototype.writeSequenceNumber=function(t){this.setItem(this.sequenceNumberKey,JSON.stringify(t))},Nf.prototype.getAllActiveQueryTargets=function(){var n=Ro();return Hr(this.activeClients,function(t,e){n=n.unionWith(e.activeTargetIds)}),n},Nf.prototype.isActiveQueryTarget=function(t){for(var e in this.activeClients)if(this.activeClients.hasOwnProperty(e)&&this.activeClients[e].activeTargetIds.has(t))return!0;return!1},Nf.prototype.addPendingMutation=function(t){this.persistMutationState(t,"pending")},Nf.prototype.updateMutationState=function(t,e,n){this.persistMutationState(t,e,n),this.removeMutationState(t)},Nf.prototype.addLocalQueryTarget=function(t){var e="not-current";if(this.isActiveQueryTarget(t)){var n=this.storage.getItem(this.toWebStorageQueryTargetMetadataKey(t));if(n){var r=vf.fromWebStorageEntry(t,n);r&&(e=r.state)}}return this.localClientState.addQueryTarget(t),this.persistClientState(),e},Nf.prototype.removeLocalQueryTarget=function(t){this.localClientState.removeQueryTarget(t),this.persistClientState()},Nf.prototype.isLocalQueryTarget=function(t){return this.localClientState.activeTargetIds.has(t)},Nf.prototype.clearQueryState=function(t){this.removeItem(this.toWebStorageQueryTargetMetadataKey(t))},Nf.prototype.updateQueryState=function(t,e,n){this.persistQueryTargetState(t,e,n)},Nf.prototype.handleUserChange=function(t,e,n){var r=this;e.forEach(function(t){r.removeMutationState(t)}),this.currentUser=t,n.forEach(function(t){r.addPendingMutation(t)})},Nf.prototype.setOnlineState=function(t){this.persistOnlineState(t)},Nf.prototype.shutdown=function(){this.started&&(this.platform.window.removeEventListener("storage",this.storageListener),this.removeItem(this.localClientStorageKey),this.started=!1)},Nf.prototype.getItem=function(t){var e=this.storage.getItem(t);return _r(ff,"READ",t,e),e},Nf.prototype.setItem=function(t,e){_r(ff,"SET",t,e),this.storage.setItem(t,e)},Nf.prototype.removeItem=function(t){_r(ff,"REMOVE",t),this.storage.removeItem(t)},Nf.prototype.handleWebStorageEvent=function(s){var t=this;if(s.storageArea===this.storage){if(_r(ff,"EVENT",s.key,s.newValue),s.key===this.localClientStorageKey)return void Or("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.queue.enqueueAndForget(function(){return p(t,void 0,void 0,function(){var e,n,r,i,o,a;return d(this,function(t){if(!this.started)return this.earlyEvents.push(s),[2];if(null===s.key)return[2];if(this.clientStateKeyRe.test(s.key)){if(null==s.newValue)return n=this.fromWebStorageClientStateKey(s.key),[2,this.handleClientStateEvent(n,null)];if(e=this.fromWebStorageClientState(s.key,s.newValue))return[2,this.handleClientStateEvent(e.clientId,e)]}else if(this.mutationBatchKeyRe.test(s.key)){if(null!==s.newValue&&(r=this.fromWebStorageMutationMetadata(s.key,s.newValue)))return[2,this.handleMutationBatchEvent(r)]}else if(this.queryTargetKeyRe.test(s.key)){if(null!==s.newValue&&(i=this.fromWebStorageQueryTargetMetadata(s.key,s.newValue)))return[2,this.handleQueryTargetEvent(i)]}else if(s.key===this.onlineStateKey){if(null!==s.newValue&&(o=this.fromWebStorageOnlineState(s.newValue)))return[2,this.handleOnlineStateEvent(o)]}else s.key===this.sequenceNumberKey&&(xr(!!this.sequenceNumberHandler,"Missing sequenceNumberHandler"),(a=function(t){var e=Ai.INVALID;if(null!=t)try{var n=JSON.parse(t);xr("number"==typeof n,"Found non-numeric sequence number"),e=n}catch(t){Or(ff,"Failed to read sequence number from WebStorage",t)}return e}(s.newValue))!==Ai.INVALID&&this.sequenceNumberHandler(a));return[2]})})})}},Object.defineProperty(Nf.prototype,"localClientState",{get:function(){return this.activeClients[this.localClientId]},enumerable:!0,configurable:!0}),Nf.prototype.persistClientState=function(){this.setItem(this.localClientStorageKey,this.localClientState.toWebStorageJSON())},Nf.prototype.persistMutationState=function(t,e,n){var r=new yf(this.currentUser,t,e,n),i=this.toWebStorageMutationBatchKey(t);this.setItem(i,r.toWebStorageJSON())},Nf.prototype.removeMutationState=function(t){var e=this.toWebStorageMutationBatchKey(t);this.removeItem(e)},Nf.prototype.persistOnlineState=function(t){var e={clientId:this.localClientId,onlineState:ah[t]};this.storage.setItem(this.onlineStateKey,JSON.stringify(e))},Nf.prototype.persistQueryTargetState=function(t,e,n){var r=this.toWebStorageQueryTargetMetadataKey(t),i=new vf(t,e,n);this.setItem(r,i.toWebStorageJSON())},Nf.prototype.toWebStorageClientStateKey=function(t){return xr(-1===t.indexOf("_"),"Client key cannot contain '_', but was '"+t+"'"),pf+"_"+this.persistenceKey+"_"+t},Nf.prototype.toWebStorageQueryTargetMetadataKey=function(t){return mf+"_"+this.persistenceKey+"_"+t},Nf.prototype.toWebStorageMutationBatchKey=function(t){var e=df+"_"+this.persistenceKey+"_"+t;return this.currentUser.isAuthenticated()&&(e+="_"+this.currentUser.uid),e},Nf.prototype.fromWebStorageClientStateKey=function(t){var e=this.clientStateKeyRe.exec(t);return e?e[1]:null},Nf.prototype.fromWebStorageClientState=function(t,e){var n=this.fromWebStorageClientStateKey(t);return xr(null!==n,"Cannot parse client state key '"+t+"'"),wf.fromWebStorageEntry(n,e)},Nf.prototype.fromWebStorageMutationMetadata=function(t,e){var n=this.mutationBatchKeyRe.exec(t);xr(null!==n,"Cannot parse mutation batch key '"+t+"'");var r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return yf.fromWebStorageEntry(new hf(i),r,e)},Nf.prototype.fromWebStorageQueryTargetMetadata=function(t,e){var n=this.queryTargetKeyRe.exec(t);xr(null!==n,"Cannot parse query target key '"+t+"'");var r=Number(n[1]);return vf.fromWebStorageEntry(r,e)},Nf.prototype.fromWebStorageOnlineState=function(t){return Sf.fromWebStorageEntry(t)},Nf.prototype.handleMutationBatchEvent=function(e){return p(this,void 0,void 0,function(){return d(this,function(t){return e.user.uid!==this.currentUser.uid?(_r(ff,"Ignoring mutation for non-active user "+e.user.uid),[2]):[2,this.syncEngine.applyBatchState(e.batchId,e.state,e.error)]})})},Nf.prototype.handleQueryTargetEvent=function(t){return this.syncEngine.applyTargetState(t.targetId,t.state,t.error)},Nf.prototype.handleClientStateEvent=function(t,e){var n=this,r=this.getAllActiveQueryTargets();e?this.activeClients[t]=e:delete this.activeClients[t];var i=this.getAllActiveQueryTargets(),o=[],a=[];return i.forEach(function(e){return p(n,void 0,void 0,function(){return d(this,function(t){return r.has(e)||o.push(e),[2]})})}),r.forEach(function(e){return p(n,void 0,void 0,function(){return d(this,function(t){return i.has(e)||a.push(e),[2]})})}),this.syncEngine.applyActiveTargetsChange(o,a)},Nf.prototype.handleOnlineStateEvent=function(t){this.activeClients[t.clientId]&&this.onlineStateHandler(t.onlineState)},Nf);function Nf(t,e,n,r,i){if(this.queue=t,this.platform=e,this.persistenceKey=n,this.localClientId=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.activeClients={},this.storageListener=this.handleWebStorageEvent.bind(this),this.started=!1,this.earlyEvents=[],!Nf.isAvailable(this.platform))throw new Qr(Ur.UNIMPLEMENTED,"LocalStorage is not available on this platform.");var o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.platform.window.localStorage,this.currentUser=i,this.localClientStorageKey=this.toWebStorageClientStateKey(this.localClientId),this.sequenceNumberKey="firestore_sequence_number_"+n,this.activeClients[this.localClientId]=new If,this.clientStateKeyRe=new RegExp("^"+pf+"_"+o+"_([^_]*)$"),this.mutationBatchKeyRe=new RegExp("^"+df+"_"+o+"_(\\d+)(?:_(.*))?$"),this.queryTargetKeyRe=new RegExp("^"+mf+"_"+o+"_(\\d+)$"),this.onlineStateKey="firestore_online_state_"+n,this.platform.window.addEventListener("storage",this.storageListener)}var Af=(kf.prototype.addPendingMutation=function(t){},kf.prototype.updateMutationState=function(t,e,n){},kf.prototype.addLocalQueryTarget=function(t){return this.localState.addQueryTarget(t),this.queryState[t]||"not-current"},kf.prototype.updateQueryState=function(t,e,n){this.queryState[t]=e},kf.prototype.removeLocalQueryTarget=function(t){this.localState.removeQueryTarget(t)},kf.prototype.isLocalQueryTarget=function(t){return this.localState.activeTargetIds.has(t)},kf.prototype.clearQueryState=function(t){delete this.queryState[t]},kf.prototype.getAllActiveQueryTargets=function(){return this.localState.activeTargetIds},kf.prototype.isActiveQueryTarget=function(t){return this.localState.activeTargetIds.has(t)},kf.prototype.start=function(){return this.localState=new If,Promise.resolve()},kf.prototype.handleUserChange=function(t,e,n){},kf.prototype.setOnlineState=function(t){},kf.prototype.shutdown=function(){},kf.prototype.writeSequenceNumber=function(t){},kf);function kf(){this.localState=new If,this.queryState={},this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null}var Rf="FirestoreClient",Mf=(_f.prototype.lruParams=function(){return Xu.withCacheSize(this.cacheSizeBytes)},_f);function _f(t,e){this.cacheSizeBytes=t,this.synchronizeTabs=e}var Of=function(){},Pf=(Lf.prototype.start=function(t){var n=this;this.verifyNotTerminated();var r=new ji,i=new ji,o=!1;return this.credentials.setChangeListener(function(e){o?n.asyncQueue.enqueueAndForget(function(){return n.handleCredentialChange(e)}):(o=!0,n.initializePersistence(t,i,e).then(function(t){return n.initializeRest(e,t)}).then(r.resolve,r.reject))}),this.asyncQueue.enqueueAndForget(function(){return r.promise}),i.promise},Lf.prototype.enableNetwork=function(){var t=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue(function(){return t.syncEngine.enableNetwork()})},Lf.prototype.initializePersistence=function(t,e,n){var r=this;return t instanceof Mf?this.startIndexedDbPersistence(n,t).then(function(t){return e.resolve(),t}).catch(function(t){if(e.reject(t),!r.canFallback(t))throw t;return console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+t),r.startMemoryPersistence()}):(e.resolve(),this.startMemoryPersistence())},Lf.prototype.canFallback=function(t){return t instanceof Qr?t.code===Ur.FAILED_PRECONDITION||t.code===Ur.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code},Lf.prototype.verifyNotTerminated=function(){if(this.asyncQueue.isShuttingDown)throw new Qr(Ur.FAILED_PRECONDITION,"The client has already been terminated.")},Lf.prototype.startIndexedDbPersistence=function(r,i){var t=this,o=uc.buildStoragePrefix(this.databaseInfo),a=new Kl(this.databaseInfo.databaseId,{useProto3Json:!0});return Promise.resolve().then(function(){return p(t,void 0,void 0,function(){var e,n;return d(this,function(t){switch(t.label){case 0:if(i.synchronizeTabs&&!Df.isAvailable(this.platform))throw new Qr(Ur.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");return n=i.lruParams(),i.synchronizeTabs?(this.sharedClientState=new Df(this.asyncQueue,this.platform,o,this.clientId,r),[4,uc.createMultiClientIndexedDbPersistence(o,this.clientId,this.platform,this.asyncQueue,a,n,{sequenceNumberSyncer:this.sharedClientState})]):[3,2];case 1:return e=t.sent(),[3,4];case 2:return this.sharedClientState=new Af,[4,uc.createIndexedDbPersistence(o,this.clientId,this.platform,this.asyncQueue,a,n)];case 3:e=t.sent(),t.label=4;case 4:return[2,(this.persistence=e).referenceDelegate.garbageCollector]}})})})},Lf.prototype.startMemoryPersistence=function(){return this.persistence=_c.createEagerPersistence(this.clientId),this.sharedClientState=new Af,Promise.resolve(null)},Lf.prototype.initializeRest=function(u,c){var t=this;return _r(Rf,"Initializing. user=",u.uid),this.platform.loadConnection(this.databaseInfo).then(function(s){return p(t,void 0,void 0,function(){var e,n,r,i,o,a=this;return d(this,function(t){switch(t.label){case 0:return this.localStore=new Sc(this.persistence,u),c&&(this.lruScheduler=new $u(c,this.asyncQueue,this.localStore)),e=this.platform.newConnectivityMonitor(),n=this.platform.newSerializer(this.databaseInfo.databaseId),r=new ih(this.asyncQueue,s,this.credentials,n),i=function(t){return a.syncEngine.applyOnlineStateChange(t,uh.RemoteStore)},o=function(t){return a.syncEngine.applyOnlineStateChange(t,uh.SharedClientState)},this.remoteStore=new jh(this.localStore,r,this.asyncQueue,i,e),this.syncEngine=new uf(this.localStore,this.remoteStore,this.sharedClientState,u),this.sharedClientState.onlineStateHandler=o,this.remoteStore.syncEngine=this.syncEngine,this.sharedClientState.syncEngine=this.syncEngine,this.eventMgr=new Gl(this.syncEngine),[4,this.sharedClientState.start()];case 1:return t.sent(),[4,this.remoteStore.start()];case 2:return t.sent(),[4,this.persistence.setPrimaryStateListener(function(e){return p(a,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return[4,this.syncEngine.applyPrimaryState(e)];case 1:return t.sent(),this.lruScheduler&&(e&&!this.lruScheduler.started?this.lruScheduler.start():e||this.lruScheduler.stop()),[2]}})})})];case 3:return t.sent(),[4,this.persistence.setDatabaseDeletedListener(function(){return p(a,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return[4,this.terminate()];case 1:return t.sent(),[2]}})})})];case 4:return t.sent(),[2]}})})})},Lf.prototype.handleCredentialChange=function(t){return this.asyncQueue.verifyOperationInProgress(),_r(Rf,"Credential Changed. Current user: "+t.uid),this.syncEngine.handleCredentialChange(t)},Lf.prototype.disableNetwork=function(){var t=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue(function(){return t.syncEngine.disableNetwork()})},Lf.prototype.terminate=function(){var t=this;return this.asyncQueue.enqueueAndInitiateShutdown(function(){return p(t,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.lruScheduler&&this.lruScheduler.stop(),[4,this.remoteStore.shutdown()];case 1:return t.sent(),[4,this.sharedClientState.shutdown()];case 2:return t.sent(),[4,this.persistence.shutdown()];case 3:return t.sent(),this.credentials.removeChangeListener(),[2]}})})})},Lf.prototype.waitForPendingWrites=function(){var t=this;this.verifyNotTerminated();var e=new ji;return this.asyncQueue.enqueueAndForget(function(){return t.syncEngine.registerPendingWritesCallback(e)}),e.promise},Lf.prototype.listen=function(t,e,n){var r=this;this.verifyNotTerminated();var i=new Hl(t,e,n);return this.asyncQueue.enqueueAndForget(function(){return r.eventMgr.listen(i)}),i},Lf.prototype.unlisten=function(t){var e=this;this.clientTerminated||this.asyncQueue.enqueueAndForget(function(){return e.eventMgr.unlisten(t)})},Lf.prototype.getDocumentFromLocalCache=function(t){var e=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue(function(){return e.localStore.readDocument(t)}).then(function(t){if(t instanceof Os)return t;if(t instanceof xs)return null;throw new Qr(Ur.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")})},Lf.prototype.getDocumentsFromLocalCache=function(i){var t=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue(function(){return t.localStore.executeQuery(i)}).then(function(t){var e=Ao(),n=new tf(i,e),r=n.computeDocChanges(t);return n.applyChanges(r,!1).snapshot})},Lf.prototype.write=function(t){var e=this;this.verifyNotTerminated();var n=new ji;return this.asyncQueue.enqueueAndForget(function(){return e.syncEngine.write(t,n)}),n.promise},Lf.prototype.databaseId=function(){return this.databaseInfo.databaseId},Object.defineProperty(Lf.prototype,"clientTerminated",{get:function(){return this.asyncQueue.isShuttingDown},enumerable:!0,configurable:!0}),Lf.prototype.transaction=function(t){var e=this;this.verifyNotTerminated();var n=new ji;return this.asyncQueue.enqueueAndForget(function(){return e.syncEngine.runTransaction(e.asyncQueue,t,n),Promise.resolve()}),n.promise},Lf);function Lf(t,e,n,r){this.platform=t,this.databaseInfo=e,this.credentials=n,this.asyncQueue=r,this.clientId=di.newId()}var xf=(qf.prototype.next=function(t){this.scheduleEvent(this.observer.next,t)},qf.prototype.error=function(t){this.scheduleEvent(this.observer.error,t)},qf.prototype.mute=function(){this.muted=!0},qf.prototype.scheduleEvent=function(t,e){var n=this;this.muted||setTimeout(function(){n.muted||t(e)},0)},qf);function qf(t){this.observer=t,this.muted=!1}var Ff=(Vf.documentId=function(){return Vf._DOCUMENT_ID},Vf.prototype.isEqual=function(t){if(!(t instanceof Vf))throw li("isEqual","FieldPath",1,t);return this._internalPath.isEqual(t._internalPath)},Vf._DOCUMENT_ID=new Vf(Fi.keyField().canonicalString()),Vf);function Vf(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];!function(t,e,n,r){if(!(e instanceof Array)||e.length<r)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires its "+n+" argument to be an array with at least "+pi(r,"element")+".")}("FieldPath",t,"fieldNames",1);for(var n=0;n<t.length;++n)if(ti("FieldPath","string",n,t[n]),0===t[n].length)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Fi(t)}var Bf=new RegExp("[~\\*/\\[\\]]");var Uf=function(t,e){this.user=e,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+t}},Qf=(Kf.prototype.getToken=function(){return Promise.resolve(null)},Kf.prototype.invalidateToken=function(){},Kf.prototype.setChangeListener=function(t){xr(!this.changeListener,"Can only call setChangeListener() once."),(this.changeListener=t)(hf.UNAUTHENTICATED)},Kf.prototype.removeChangeListener=function(){xr(null!==this.changeListener,"removeChangeListener() when no listener registered"),this.changeListener=null},Kf);function Kf(){this.changeListener=null}var jf=(Wf.prototype.getToken=function(){var e=this;xr(null!=this.tokenListener,"getToken cannot be called after listener removed.");var n=this.tokenCounter,t=this.forceRefresh;return this.forceRefresh=!1,this.app.INTERNAL.getToken(t).then(function(t){if(e.tokenCounter!==n)throw new Qr(Ur.ABORTED,"getToken aborted due to token change.");return t?(xr("string"==typeof t.accessToken,"Invalid tokenData returned from getToken():"+t),new Uf(t.accessToken,e.currentUser)):null})},Wf.prototype.invalidateToken=function(){this.forceRefresh=!0},Wf.prototype.setChangeListener=function(t){xr(!this.changeListener,"Can only call setChangeListener() once."),(this.changeListener=t)(this.currentUser)},Wf.prototype.removeChangeListener=function(){xr(null!=this.tokenListener,"removeChangeListener() called twice"),xr(null!==this.changeListener,"removeChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.changeListener=null},Wf.prototype.getUser=function(){var t=this.app.INTERNAL.getUid();return xr(null===t||"string"==typeof t,"Received invalid UID: "+t),new hf(t)},Wf);function Wf(t){var e=this;this.app=t,this.tokenListener=null,this.currentUser=hf.UNAUTHENTICATED,this.tokenCounter=0,this.changeListener=null,this.forceRefresh=!1,this.tokenListener=function(){e.tokenCounter++,e.currentUser=e.getUser(),e.changeListener&&e.changeListener(e.currentUser)},this.currentUser=this.getUser(),this.tokenCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}var Gf=(Object.defineProperty(zf.prototype,"authHeaders",{get:function(){var t={"X-Goog-AuthUser":this.sessionIndex},e=this.gapi.auth.getAuthHeaderValueForFirstParty([]);return e&&(t.Authorization=e),t},enumerable:!0,configurable:!0}),zf);function zf(t,e){this.gapi=t,this.sessionIndex=e,this.type="FirstParty",this.user=hf.FIRST_PARTY}var Hf=(Yf.prototype.getToken=function(){return Promise.resolve(new Gf(this.gapi,this.sessionIndex))},Yf.prototype.setChangeListener=function(t){t(hf.FIRST_PARTY)},Yf.prototype.removeChangeListener=function(){},Yf.prototype.invalidateToken=function(){},Yf);function Yf(t,e){this.gapi=t,this.sessionIndex=e}function Xf(t){return function(t,e){if("object"!=typeof t||null===t)return!1;for(var n=t,r=0,i=e;r<i.length;r++){var o=i[r];if(o in n&&"function"==typeof n[o])return!0}return!1}(t,["next","error","complete"])}var Jf=($f.delete=function(){return Xr("FieldValue.delete",arguments),tp.instance},$f.serverTimestamp=function(){return Xr("FieldValue.serverTimestamp",arguments),rp.instance},$f.arrayUnion=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return $r("FieldValue.arrayUnion",arguments,1),new ap(t)},$f.arrayRemove=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return $r("FieldValue.arrayRemove",arguments,1),new cp(t)},$f.increment=function(t){return ti("FieldValue.increment","number",1,t),Jr("FieldValue.increment",arguments,1),new fp(t)},$f.prototype.isEqual=function(t){return this===t},$f);function $f(t){this._methodName=t}var Zf,tp=(s(ep,Zf=Jf),ep.instance=new ep,ep);function ep(){return Zf.call(this,"FieldValue.delete")||this}var np,rp=(s(ip,np=Jf),ip.instance=new ip,ip);function ip(){return np.call(this,"FieldValue.serverTimestamp")||this}var op,ap=(s(sp,op=Jf),sp);function sp(t){var e=op.call(this,"FieldValue.arrayUnion")||this;return e._elements=t,e}var up,cp=(s(hp,up=Jf),hp);function hp(t){var e=up.call(this,"FieldValue.arrayRemove")||this;return e._elements=t,e}var lp,fp=(s(pp,lp=Jf),pp);function pp(t){var e=lp.call(this,"FieldValue.increment")||this;return e._operand=t,e}var dp=jr(Jf,"Use FieldValue.<field>() instead."),mp=/^__.*__$/,yp=(gp.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new Aa(t,this.data,this.fieldMask,e)):n.push(new Ca(t,this.data,e)),0<this.fieldTransforms.length&&n.push(new Ma(t,this.fieldTransforms)),n},gp);function gp(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}var vp,bp,wp=(Ep.prototype.toMutations=function(t,e){var n=[new Aa(t,this.data,this.fieldMask,e)];return 0<this.fieldTransforms.length&&n.push(new Ma(t,this.fieldTransforms)),n},Ep);function Ep(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}function Sp(t){switch(t){case vp.Set:case vp.MergeSet:case vp.Update:return!0;case vp.Argument:return!1;default:throw Lr("Unexpected case for UserDataSource: "+t)}}(bp=vp=vp||{})[bp.Set=0]="Set",bp[bp.Update=1]="Update",bp[bp.MergeSet=2]="MergeSet",bp[bp.Argument=3]="Argument";var Tp=(Ip.prototype.childContextForField=function(t){var e=null==this.path?null:this.path.child(t),n=new Ip(this.dataSource,this.methodName,e,!1,this.fieldTransforms,this.fieldMask);return n.validatePathSegment(t),n},Ip.prototype.childContextForFieldPath=function(t){var e=null==this.path?null:this.path.child(t),n=new Ip(this.dataSource,this.methodName,e,!1,this.fieldTransforms,this.fieldMask);return n.validatePath(),n},Ip.prototype.childContextForArray=function(t){return new Ip(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},Ip.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path.toString()+")";return new Qr(Ur.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},Ip.prototype.contains=function(e){return void 0!==this.fieldMask.find(function(t){return e.isPrefixOf(t)})||void 0!==this.fieldTransforms.find(function(t){return e.isPrefixOf(t.field)})},Ip.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t<this.path.length;t++)this.validatePathSegment(this.path.get(t))},Ip.prototype.validatePathSegment=function(t){if(Sp(this.dataSource)&&mp.test(t))throw this.createError("Document fields cannot begin and end with __")},Ip);function Ip(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||[]}var Cp=function(t,e){this.databaseId=t,this.key=e},Dp=(Np.prototype.parseSetData=function(t,e){var n=new Tp(vp.Set,t,Fi.EMPTY_PATH);kp("Data must be an object, but it was:",n,e);var r=this.parseData(e,n);return new yp(r,null,n.fieldTransforms)},Np.prototype.parseMergeData=function(t,e,n){var r=new Tp(vp.MergeSet,t,Fi.EMPTY_PATH);kp("Data must be an object, but it was:",r,e);var i,o,a=this.parseData(e,r);if(n){for(var s=new yo(Fi.comparator),u=0,c=n;u<c.length;u++){var h=c[u],l=void 0;if(h instanceof Ff)l=h._internalPath;else{if("string"!=typeof h)throw Lr("Expected stringOrFieldPath to be a string or a FieldPath");l=Mp(t,h)}if(!r.contains(l))throw new Qr(Ur.INVALID_ARGUMENT,"Field '"+l+"' is specified in your field mask but missing from your input data.");s=s.add(l)}i=pa.fromSet(s),o=r.fieldTransforms.filter(function(t){return i.covers(t.field)})}else i=pa.fromArray(r.fieldMask),o=r.fieldTransforms;return new yp(a,i,o)},Np.prototype.parseUpdateData=function(o,t){var a=this,s=new Tp(vp.Update,o,Fi.EMPTY_PATH);kp("Data must be an object, but it was:",s,t);var u=new yo(Fi.comparator),c=Cs.EMPTY;Hr(t,function(t,e){var n=Mp(o,t),r=s.childContextForFieldPath(n);if((e=a.runPreConverter(e,r))instanceof tp)u=u.add(n);else{var i=a.parseData(e,r);null!=i&&(u=u.add(n),c=c.set(n,i))}});var e=pa.fromSet(u);return new wp(c,e,s.fieldTransforms)},Np.prototype.parseUpdateVarargs=function(t,e,n,r){var i=new Tp(vp.Update,t,Fi.EMPTY_PATH),o=[Rp(t,e)],a=[n];if(r.length%2!=0)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() needs to be called with an even number of arguments that alternate between field names and values.");for(var s=0;s<r.length;s+=2)o.push(Rp(t,r[s])),a.push(r[s+1]);var u=new yo(Fi.comparator),c=Cs.EMPTY;for(s=0;s<o.length;++s){var h=o[s],l=i.childContextForFieldPath(h),f=this.runPreConverter(a[s],l);if(f instanceof tp)u=u.add(h);else{var p=this.parseData(f,l);null!=p&&(u=u.add(h),c=c.set(h,p))}}var d=pa.fromSet(u);return new wp(c,d,i.fieldTransforms)},Np.prototype.parseQueryValue=function(t,e){var n=new Tp(vp.Argument,t,Fi.EMPTY_PATH),r=this.parseData(e,n);return xr(null!=r,"Parsed data should not be null."),xr(0===n.fieldTransforms.length,"Field transforms should have been disallowed."),r},Np.prototype.runPreConverter=function(t,e){try{return this.preConverter(t)}catch(t){var n=_p(t);throw e.createError(n)}},Np.prototype.parseData=function(t,e){if(Ap(t=this.runPreConverter(t,e)))return kp("Unsupported field value:",e,t),this.parseObject(t,e);if(t instanceof Jf)return this.parseSentinelFieldValue(t,e),null;if(e.path&&e.fieldMask.push(e.path),t instanceof Array){if(e.arrayElement)throw e.createError("Nested arrays are not supported");return this.parseArray(t,e)}return this.parseScalarValue(t,e)},Np.prototype.parseObject=function(t,r){var i=this,o=new so(yi);return Yr(t)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):Hr(t,function(t,e){var n=i.parseData(e,r.childContextForField(t));null!=n&&(o=o.insert(t,n))}),new Cs(o)},Np.prototype.parseArray=function(t,e){for(var n=[],r=0,i=0,o=t;i<o.length;i++){var a=o[i],s=this.parseData(a,e.childContextForArray(r));null==s&&(s=Wa.INSTANCE),n.push(s),r++}return new As(n)},Np.prototype.parseSentinelFieldValue=function(t,e){if(!Sp(e.dataSource))throw e.createError(t._methodName+"() can only be used with update() and set()");if(null===e.path)throw e.createError(t._methodName+"() is not currently supported inside arrays");if(t instanceof tp){if(e.dataSource!==vp.MergeSet)throw e.dataSource===vp.Update?(xr(0<e.path.length,"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 rp)e.fieldTransforms.push(new ma(e.path,Cl.instance));else if(t instanceof ap){var n=this.parseArrayTransformElements(t._methodName,t._elements),r=new Nl(n);e.fieldTransforms.push(new ma(e.path,r))}else if(t instanceof cp){n=this.parseArrayTransformElements(t._methodName,t._elements);var i=new kl(n);e.fieldTransforms.push(new ma(e.path,i))}else if(t instanceof fp){var o=this.parseQueryValue("FieldValue.increment",t._operand),a=new Ml(o);e.fieldTransforms.push(new ma(e.path,a))}else Lr("Unknown FieldValue type: "+t)},Np.prototype.parseScalarValue=function(t,e){if(null===t)return Wa.INSTANCE;if("number"==typeof t)return jc(t)?new es(t):new is(t);if("boolean"==typeof t)return Ha.of(t);if("string"==typeof t)return new ss(t);if(t instanceof Date)return new hs(ro.fromDate(t));if(t instanceof ro)return new hs(new ro(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)));if(t instanceof Gh)return new Ss(t);if(t instanceof Ei)return new ys(t);if(t instanceof Cp)return new bs(t.databaseId,t.key);throw e.createError("Unsupported field value: "+ui(t))},Np.prototype.parseArrayTransformElements=function(r,t){var i=this;return t.map(function(t,e){var n=new Tp(vp.Argument,r,Fi.EMPTY_PATH);return i.parseData(t,n.childContextForArray(e))})},Np);function Np(t){this.preConverter=t}function Ap(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof ro||t instanceof Gh||t instanceof Ei||t instanceof Cp||t instanceof Jf)}function kp(t,e,n){if(!Ap(n)||!si(n)){var r=ui(n);throw"an object"===r?e.createError(t+" a custom object"):e.createError(t+" "+r)}}function Rp(t,e){if(e instanceof Ff)return e._internalPath;if("string"==typeof e)return Mp(t,e);throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function Mp(e,t){try{return function(e){if(0<=e.search(Bf))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid field path ("+e+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(Ff.bind.apply(Ff,[void 0].concat(e.split("."))))}catch(t){throw new Qr(Ur.INVALID_ARGUMENT,"Invalid field path ("+e+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}(t)._internalPath}catch(t){var n=_p(t);throw new Qr(Ur.INVALID_ARGUMENT,"Function "+e+"() called with invalid data. "+n)}}function _p(t){return t instanceof Error?t.message:t.toString()}var Op=Xu.COLLECTION_DISABLED,Pp=(Lp.prototype.isEqual=function(t){return this.host===t.host&&this.ssl===t.ssl&&this.timestampsInSnapshots===t.timestampsInSnapshots&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes&&this.forceLongPolling===t.forceLongPolling},Lp);function Lp(t){if(void 0===t.host){if(void 0!==t.ssl)throw new Qr(Ur.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else ni("settings","non-empty string","host",t.host),this.host=t.host,ri("settings","boolean","ssl",t.ssl),this.ssl=Gr(t.ssl,!0);if(hi("settings",t,["host","ssl","credentials","timestampsInSnapshots","cacheSizeBytes","experimentalForceLongPolling"]),ri("settings","object","credentials",t.credentials),this.credentials=t.credentials,ri("settings","boolean","timestampsInSnapshots",t.timestampsInSnapshots),!0===t.timestampsInSnapshots?Or("\n The timestampsInSnapshots setting now defaults to true and you no\n longer need to explicitly set it. In a future release, the setting\n will be removed entirely and so it is recommended that you remove it\n from your firestore.settings() call now."):!1===t.timestampsInSnapshots&&Or("\n The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\n YOUR CODE.\n\n To hide this warning, stop using the timestampsInSnapshots setting in your\n firestore.settings({ ... }) call.\n\n Once you remove the setting, Timestamps stored in Cloud Firestore will be\n read back as Firebase Timestamp objects instead of as system Date objects.\n So you will also need to update code expecting a Date to instead expect a\n Timestamp. For example:\n\n // Old:\n const date = snapshot.get('created_at');\n // New:\n const timestamp = snapshot.get('created_at'); const date =\n timestamp.toDate();\n\n Please audit all existing usages of Date when you enable the new\n behavior."),this.timestampsInSnapshots=Gr(t.timestampsInSnapshots,!0),ri("settings","number","cacheSizeBytes",t.cacheSizeBytes),void 0===t.cacheSizeBytes)this.cacheSizeBytes=Xu.DEFAULT_CACHE_SIZE_BYTES;else{if(t.cacheSizeBytes!==Op&&t.cacheSizeBytes<Xu.MINIMUM_CACHE_SIZE_BYTES)throw new Qr(Ur.INVALID_ARGUMENT,"cacheSizeBytes must be at least "+Xu.MINIMUM_CACHE_SIZE_BYTES);this.cacheSizeBytes=t.cacheSizeBytes}ri("settings","boolean","experimentalForceLongPolling",t.experimentalForceLongPolling),this.forceLongPolling=void 0!==t.experimentalForceLongPolling&&t.experimentalForceLongPolling}var xp=(qp.prototype.settings=function(t){if(Jr("Firestore.settings",arguments,1),ti("Firestore.settings","object",1,t),Wr(t,"persistence"))throw new Qr(Ur.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var e=new Pp(t);if(this._firestoreClient&&!this._settings.isEqual(e))throw new Qr(Ur.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");void 0!==(this._settings=e).credentials&&(this._credentials=function(t){if(!t)return new Qf;switch(t.type){case"gapi":var e=t.client;return xr(!("object"!=typeof e||null===e||!e.auth||!e.auth.getAuthHeaderValueForFirstParty),"unexpected gapi interface"),new Hf(e,t.sessionIndex||"0");case"provider":return t.client;default:throw new Qr(Ur.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}(e.credentials))},qp.prototype.enableNetwork=function(){return this.ensureClientConfigured(),this._firestoreClient.enableNetwork()},qp.prototype.disableNetwork=function(){return this.ensureClientConfigured(),this._firestoreClient.disableNetwork()},qp.prototype.enablePersistence=function(t){if(this._firestoreClient)throw new Qr(Ur.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");var e=!1;return t&&(void 0!==t.experimentalTabSynchronization&&Or("The 'experimentalTabSynchronization' setting has been renamed to 'synchronizeTabs'. In a future release, the setting will be removed and it is recommended that you update your firestore.enablePersistence() call to use 'synchronizeTabs'."),e=Gr(void 0!==t.synchronizeTabs?t.synchronizeTabs:t.experimentalTabSynchronization,!1)),this.configureClient(new Mf(this._settings.cacheSizeBytes,e))},qp.prototype.clearPersistence=function(){var t=this,n=uc.buildStoragePrefix(this.makeDatabaseInfo()),r=new ji;return this._queue.enqueueAndForgetEvenAfterShutdown(function(){return p(t,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:if(t.trys.push([0,2,,3]),void 0!==this._firestoreClient&&!this._firestoreClient.clientTerminated)throw new Qr(Ur.FAILED_PRECONDITION,"Persistence cannot be cleared after this Firestore instance is initialized.");return[4,uc.clearPersistence(n)];case 1:return t.sent(),r.resolve(),[3,3];case 2:return e=t.sent(),r.reject(e),[3,3];case 3:return[2]}})})}),r.promise},qp.prototype.terminate=function(){return this.app._removeServiceInstance("firestore"),this.INTERNAL.delete()},Object.defineProperty(qp.prototype,"_isTerminated",{get:function(){return this.ensureClientConfigured(),this._firestoreClient.clientTerminated},enumerable:!0,configurable:!0}),qp.prototype.waitForPendingWrites=function(){return this.ensureClientConfigured(),this._firestoreClient.waitForPendingWrites()},qp.prototype.ensureClientConfigured=function(){return this._firestoreClient||this.configureClient(new Of),this._firestoreClient},qp.prototype.makeDatabaseInfo=function(){return new Ii(this._databaseId,this._persistenceKey,this._settings.host,this._settings.ssl,this._settings.forceLongPolling)},qp.prototype.configureClient=function(t){xr(!!this._settings.host,"FirestoreSettings.host is not set"),xr(!this._firestoreClient,"configureClient() called multiple times");var e=this.makeDatabaseInfo();return this._firestoreClient=new Pf(qr.getPlatform(),e,this._credentials,this._queue),this._firestoreClient.start(t)},qp.prototype.createDataConverter=function(r){return new Dp(function(t){if(t instanceof Qp){var e=r,n=t.firestore._databaseId;if(!n.isEqual(e))throw new Qr(Ur.INVALID_ARGUMENT,"Document reference is for database "+n.projectId+"/"+n.database+" but should be for database "+e.projectId+"/"+e.database);return new Cp(r,t._key)}return t})},qp.databaseIdFromApp=function(t){var e=t.options;if(!Wr(e,"projectId"))throw new Qr(Ur.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');var n=e.projectId;if(!n||"string"!=typeof n)throw new Qr(Ur.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new Di(n)},Object.defineProperty(qp.prototype,"app",{get:function(){if(!this._firebaseApp)throw new Qr(Ur.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._firebaseApp},enumerable:!0,configurable:!0}),qp.prototype.collection=function(t){return Jr("Firestore.collection",arguments,1),ti("Firestore.collection","non-empty string",1,t),this.ensureClientConfigured(),new nd(Pi.fromString(t),this)},qp.prototype.doc=function(t){return Jr("Firestore.doc",arguments,1),ti("Firestore.doc","non-empty string",1,t),this.ensureClientConfigured(),Qp.forPath(Pi.fromString(t),this)},qp.prototype.collectionGroup=function(t){if(Jr("Firestore.collectionGroup",arguments,1),ti("Firestore.collectionGroup","non-empty string",1,t),0<=t.indexOf("/"))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid collection ID '"+t+"' passed to function Firestore.collectionGroup(). Collection IDs must not contain '/'.");return this.ensureClientConfigured(),new Jp(new Hh(Pi.EMPTY_PATH,t),this)},qp.prototype.runTransaction=function(e){var n=this;return Jr("Firestore.runTransaction",arguments,1),ti("Firestore.runTransaction","function",1,e),this.ensureClientConfigured().transaction(function(t){return e(new Fp(n,t))})},qp.prototype.batch=function(){return this.ensureClientConfigured(),new Bp(this)},Object.defineProperty(qp,"logLevel",{get:function(){switch(Rr()){case wr.DEBUG:return"debug";case wr.ERROR:return"error";case wr.SILENT:return"silent";default:return Lr("Unknown log level: "+Rr())}},enumerable:!0,configurable:!0}),qp.setLogLevel=function(t){switch(Jr("Firestore.setLogLevel",arguments,1),ti("Firestore.setLogLevel","non-empty string",1,t),t){case"debug":Mr(wr.DEBUG);break;case"error":Mr(wr.ERROR);break;case"silent":Mr(wr.SILENT);break;default:throw new Qr(Ur.INVALID_ARGUMENT,"Invalid log level: "+t)}},qp.prototype._areTimestampsInSnapshotsEnabled=function(){return this._settings.timestampsInSnapshots},qp);function qp(t){var e=this;if(this._firebaseApp=null,this._queue=new zi,this.INTERNAL={delete:function(){return p(e,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.ensureClientConfigured(),[4,this._firestoreClient.terminate()];case 1:return t.sent(),[2]}})})}},"object"==typeof t.options){var n=t;this._firebaseApp=n,this._databaseId=qp.databaseIdFromApp(n),this._persistenceKey=n.name,this._credentials=new jf(n)}else{var r=t;if(!r.projectId)throw new Qr(Ur.INVALID_ARGUMENT,"Must provide projectId");this._databaseId=new Di(r.projectId,r.database),this._persistenceKey="[DEFAULT]",this._credentials=new Qf}this._settings=new Pp({}),this._dataConverter=this.createDataConverter(this._databaseId)}var Fp=(Vp.prototype.get=function(t){var n=this;Jr("Transaction.get",arguments,1);var r=sd("Transaction.get",t,this._firestore);return this._transaction.lookup([r._key]).then(function(t){if(!t||1!==t.length)return Lr("Mismatch in docs returned from document lookup.");var e=t[0];if(e instanceof xs)return new Gp(n._firestore,r._key,null,!1,!1);if(e instanceof Os)return new Gp(n._firestore,r._key,e,!1,!1);throw Lr("BatchGetDocumentsRequest returned unexpected document type: "+e.constructor.name)})},Vp.prototype.set=function(t,e,n){Zr("Transaction.set",arguments,2,3);var r=sd("Transaction.set",t,this._firestore),i=(n=id("Transaction.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("Transaction.set",e,n.mergeFields):this._firestore._dataConverter.parseSetData("Transaction.set",e);return this._transaction.set(r._key,i),this},Vp.prototype.update=function(t,e,n){for(var r,i,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return i="string"==typeof e||e instanceof Ff?($r("Transaction.update",arguments,3),r=sd("Transaction.update",t,this._firestore),this._firestore._dataConverter.parseUpdateVarargs("Transaction.update",e,n,o)):(Jr("Transaction.update",arguments,2),r=sd("Transaction.update",t,this._firestore),this._firestore._dataConverter.parseUpdateData("Transaction.update",e)),this._transaction.update(r._key,i),this},Vp.prototype.delete=function(t){Jr("Transaction.delete",arguments,1);var e=sd("Transaction.delete",t,this._firestore);return this._transaction.delete(e._key),this},Vp);function Vp(t,e){this._firestore=t,this._transaction=e}var Bp=(Up.prototype.set=function(t,e,n){Zr("WriteBatch.set",arguments,2,3),this.verifyNotCommitted();var r=sd("WriteBatch.set",t,this._firestore),i=(n=id("WriteBatch.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("WriteBatch.set",e,n.mergeFields):this._firestore._dataConverter.parseSetData("WriteBatch.set",e);return this._mutations=this._mutations.concat(i.toMutations(r._key,wa.NONE)),this},Up.prototype.update=function(t,e,n){for(var r,i,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return this.verifyNotCommitted(),i="string"==typeof e||e instanceof Ff?($r("WriteBatch.update",arguments,3),r=sd("WriteBatch.update",t,this._firestore),this._firestore._dataConverter.parseUpdateVarargs("WriteBatch.update",e,n,o)):(Jr("WriteBatch.update",arguments,2),r=sd("WriteBatch.update",t,this._firestore),this._firestore._dataConverter.parseUpdateData("WriteBatch.update",e)),this._mutations=this._mutations.concat(i.toMutations(r._key,wa.exists(!0))),this},Up.prototype.delete=function(t){Jr("WriteBatch.delete",arguments,1),this.verifyNotCommitted();var e=sd("WriteBatch.delete",t,this._firestore);return this._mutations=this._mutations.concat(new Fa(e._key,wa.NONE)),this},Up.prototype.commit=function(){return p(this,void 0,void 0,function(){return d(this,function(t){return this.verifyNotCommitted(),this._committed=!0,0<this._mutations.length?[2,this._firestore.ensureClientConfigured().write(this._mutations)]:[2]})})},Up.prototype.verifyNotCommitted=function(){if(this._committed)throw new Qr(Ur.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},Up);function Up(t){this._firestore=t,this._mutations=[],this._committed=!1}var Qp=(Kp.forPath=function(t,e){if(t.length%2!=0)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+t.canonicalString()+" has "+t.length);return new Kp(new Bi(t),e)},Object.defineProperty(Kp.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(Kp.prototype,"parent",{get:function(){return new nd(this._key.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(Kp.prototype,"path",{get:function(){return this._key.path.canonicalString()},enumerable:!0,configurable:!0}),Kp.prototype.collection=function(t){if(Jr("DocumentReference.collection",arguments,1),ti("DocumentReference.collection","non-empty string",1,t),!t)throw new Qr(Ur.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=Pi.fromString(t);return new nd(this._key.path.child(e),this.firestore)},Kp.prototype.isEqual=function(t){if(!(t instanceof Kp))throw li("isEqual","DocumentReference",1,t);return this.firestore===t.firestore&&this._key.isEqual(t._key)},Kp.prototype.set=function(t,e){Zr("DocumentReference.set",arguments,1,2);var n=(e=id("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,wa.NONE))},Kp.prototype.update=function(t,e){for(var n,r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];return n="string"==typeof t||t instanceof Ff?($r("DocumentReference.update",arguments,2),this.firestore._dataConverter.parseUpdateVarargs("DocumentReference.update",t,e,r)):(Jr("DocumentReference.update",arguments,1),this.firestore._dataConverter.parseUpdateData("DocumentReference.update",t)),this._firestoreClient.write(n.toMutations(this._key,wa.exists(!0)))},Kp.prototype.delete=function(){return Jr("DocumentReference.delete",arguments,0),this._firestoreClient.write([new Fa(this._key,wa.NONE)])},Kp.prototype.onSnapshot=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Zr("DocumentReference.onSnapshot",arguments,1,4);var n,r={includeMetadataChanges:!1},i=0;"object"!=typeof t[i]||Xf(t[i])||(hi("DocumentReference.onSnapshot",r=t[i],["includeMetadataChanges"]),ri("DocumentReference.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++);var o={includeMetadataChanges:r.includeMetadataChanges};return n=Xf(t[i])?t[i]:(ti("DocumentReference.onSnapshot","function",i,t[i]),ei("DocumentReference.onSnapshot","function",i+1,t[i+1]),ei("DocumentReference.onSnapshot","function",i+2,t[i+2]),{next:t[i],error:t[i+1],complete:t[i+2]}),this.onSnapshotInternal(o,n)},Kp.prototype.onSnapshotInternal=function(t,n){var r=this,e=function(t){console.error("Uncaught Error in onSnapshot:",t)};n.error&&(e=n.error.bind(n));var i=new xf({next:function(t){if(n.next){xr(t.docs.size<=1,"Too many documents returned on a document query");var e=t.docs.get(r._key);n.next(new Gp(r.firestore,r._key,e,t.fromCache,t.hasPendingWrites))}},error:e}),o=this._firestoreClient.listen(Hh.atPath(this._key.path),i,t);return function(){i.mute(),r._firestoreClient.unlisten(o)}},Kp.prototype.get=function(n){var r=this;return Zr("DocumentReference.get",arguments,0,1),ad("DocumentReference.get",n),new Promise(function(e,t){n&&"cache"===n.source?r.firestore.ensureClientConfigured().getDocumentFromLocalCache(r._key).then(function(t){e(new Gp(r.firestore,r._key,t,!0,t instanceof Os&&t.hasLocalMutations))},t):r.getViaSnapshotListener(e,t,n)})},Kp.prototype.getViaSnapshotListener=function(e,n,r){var i=this.onSnapshotInternal({includeMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(t){i(),!t.exists&&t.metadata.fromCache?n(new Qr(Ur.UNAVAILABLE,"Failed to get document because the client is offline.")):t.exists&&t.metadata.fromCache&&r&&"server"===r.source?n(new Qr(Ur.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):e(t)},error:n})},Kp);function Kp(t,e){this._key=t,this.firestore=e,this._firestoreClient=this.firestore.ensureClientConfigured()}var jp=(Wp.prototype.isEqual=function(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache},Wp);function Wp(t,e){this.hasPendingWrites=t,this.fromCache=e}var Gp=(zp.prototype.data=function(t){return Zr("DocumentSnapshot.data",arguments,0,1),t=od("DocumentSnapshot.data",t),this._document?this.convertObject(this._document.data(),Ba.fromSnapshotOptions(t,this._firestore._areTimestampsInSnapshotsEnabled())):void 0},zp.prototype.get=function(t,e){if(Zr("DocumentSnapshot.get",arguments,1,2),e=od("DocumentSnapshot.get",e),this._document){var n=this._document.data().field(Rp("DocumentSnapshot.get",t));if(null!==n)return this.convertValue(n,Ba.fromSnapshotOptions(e,this._firestore._areTimestampsInSnapshotsEnabled()))}},Object.defineProperty(zp.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(zp.prototype,"ref",{get:function(){return new Qp(this._key,this._firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(zp.prototype,"exists",{get:function(){return null!==this._document},enumerable:!0,configurable:!0}),Object.defineProperty(zp.prototype,"metadata",{get:function(){return new jp(this._hasPendingWrites,this._fromCache)},enumerable:!0,configurable:!0}),zp.prototype.isEqual=function(t){if(!(t instanceof zp))throw li("isEqual","DocumentSnapshot",1,t);return this._firestore===t._firestore&&this._fromCache===t._fromCache&&this._key.isEqual(t._key)&&(null===this._document?null===t._document:this._document.isEqual(t._document))},zp.prototype.convertObject=function(t,n){var r=this,i={};return t.forEach(function(t,e){i[t]=r.convertValue(e,n)}),i},zp.prototype.convertValue=function(t,e){if(t instanceof Cs)return this.convertObject(t,e);if(t instanceof As)return this.convertArray(t,e);if(t instanceof bs){var n=t.value(e),r=this._firestore.ensureClientConfigured().databaseId();return t.databaseId.isEqual(r)||Or("Document "+this._key.path+" contains a document reference within a different database ("+t.databaseId.projectId+"/"+t.databaseId.database+") which is not supported. It will be treated as a reference in the current database ("+r.projectId+"/"+r.database+") instead."),new Qp(n,this._firestore)}return t.value(e)},zp.prototype.convertArray=function(t,e){var n=this;return t.internalValue.map(function(t){return n.convertValue(t,e)})},zp);function zp(t,e,n,r,i){this._firestore=t,this._key=e,this._document=n,this._fromCache=r,this._hasPendingWrites=i}var Hp,Yp=(s(Xp,Hp=Gp),Xp.prototype.data=function(t){var e=Hp.prototype.data.call(this,t);return xr("object"==typeof e,"Document in a QueryDocumentSnapshot should exist"),e},Xp);function Xp(){return null!==Hp&&Hp.apply(this,arguments)||this}var Jp=($p.prototype.where=function(t,e,n){Jr("Query.where",arguments,3),ci("Query.where",3,n),"in"!==e&&"array-contains-any"!==e&&function(t,e,n,r){if(!e.some(function(t){return t===r}))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid value "+ui(r)+" provided to function "+t+"() for its "+fi(n)+" argument. Acceptable values: "+e.join(", "))}("Query.where",["<","<=","==",">=",">","array-contains"],2,e);var r,i=Rp("Query.where",t),o=Jh.fromString(e);if(i.isKeyField()){if(o===Jh.ARRAY_CONTAINS||o===Jh.ARRAY_CONTAINS_ANY)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid Query. You can't perform '"+o.toString()+"' queries on FieldPath.documentId().");if(o===Jh.IN){this.validateDisjunctiveFilterElements(n,o);for(var a=[],s=0,u=n;s<u.length;s++){var c=u[s];a.push(this.parseDocumentIdValue(c))}r=new As(a)}else r=this.parseDocumentIdValue(n)}else o!==Jh.IN&&o!==Jh.ARRAY_CONTAINS_ANY||this.validateDisjunctiveFilterElements(n,o),r=this.firestore._dataConverter.parseQueryValue("Query.where",n);var h=tl.create(i,o,r);return this.validateNewFilter(h),new $p(this._query.addFilter(h),this.firestore)},$p.prototype.orderBy=function(t,e){var n;if(Zr("Query.orderBy",arguments,1,2),ei("Query.orderBy","non-empty string",2,e),void 0===e||"asc"===e)n=gl.ASCENDING;else{if("desc"!==e)throw new Qr(Ur.INVALID_ARGUMENT,"Function Query.orderBy() has unknown direction '"+e+"', expected 'asc' or 'desc'.");n=gl.DESCENDING}if(null!==this._query.startAt)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");if(null!==this._query.endAt)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");var r=Rp("Query.orderBy",t),i=new El(r,n);return this.validateNewOrderBy(i),new $p(this._query.addOrderBy(i),this.firestore)},$p.prototype.limit=function(t){if(Jr("Query.limit",arguments,1),ti("Query.limit","number",1,t),t<=0)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid Query. Query limit ("+t+") is invalid. Limit must be positive.");return new $p(this._query.withLimit(t),this.firestore)},$p.prototype.startAt=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];$r("Query.startAt",arguments,1);var r=this.boundFromDocOrFields("Query.startAt",t,e,!0);return new $p(this._query.withStartAt(r),this.firestore)},$p.prototype.startAfter=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];$r("Query.startAfter",arguments,1);var r=this.boundFromDocOrFields("Query.startAfter",t,e,!1);return new $p(this._query.withStartAt(r),this.firestore)},$p.prototype.endBefore=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];$r("Query.endBefore",arguments,1);var r=this.boundFromDocOrFields("Query.endBefore",t,e,!0);return new $p(this._query.withEndAt(r),this.firestore)},$p.prototype.endAt=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];$r("Query.endAt",arguments,1);var r=this.boundFromDocOrFields("Query.endAt",t,e,!1);return new $p(this._query.withEndAt(r),this.firestore)},$p.prototype.isEqual=function(t){if(!(t instanceof $p))throw li("isEqual","Query",1,t);return this.firestore===t.firestore&&this._query.isEqual(t._query)},$p.prototype.boundFromDocOrFields=function(t,e,n,r){if(ci(t,1,e),e instanceof Gp){if(0<n.length)throw new Qr(Ur.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var i=e;if(!i.exists)throw new Qr(Ur.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)},$p.prototype.boundFromDocument=function(t,e,n){for(var r=[],i=0,o=this._query.orderBy;i<o.length;i++){var a=o[i];if(a.field.isKeyField())r.push(new bs(this.firestore._databaseId,e.key));else{var s=e.field(a.field);if(s instanceof ps)throw new Qr(Ur.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+a.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===s){var u=a.field.canonicalString();throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You are trying to start or end a query using a document for which the field '"+u+"' (used as the orderBy) does not exist.")}r.push(s)}}return new bl(r,n)},$p.prototype.boundFromFields=function(t,e,n){var r=this._query.explicitOrderBy;if(e.length>r.length)throw new Qr(Ur.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<e.length;o++){var a=e[o];if(r[o].field.isKeyField()){if("string"!=typeof a)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in "+t+"(), but got a "+typeof a);if(!this._query.isCollectionGroupQuery()&&-1!==a.indexOf("/"))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. When querying a collection and ordering by FieldPath.documentId(), the value passed to "+t+"() must be a plain document ID, but '"+a+"' contains a slash.");var s=this._query.path.child(Pi.fromString(a));if(!Bi.isDocumentKey(s))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. When querying a collection group and ordering by FieldPath.documentId(), the value passed to "+t+"() must result in a valid document path, but '"+s+"' is not because it contains an odd number of segments.");var u=new Bi(s);i.push(new bs(this.firestore._databaseId,u))}else{var c=this.firestore._dataConverter.parseQueryValue(t,a);i.push(c)}}return new bl(i,n)},$p.prototype.onSnapshot=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Zr("Query.onSnapshot",arguments,1,4);var n,r={},i=0;return"object"!=typeof t[i]||Xf(t[i])||(hi("Query.onSnapshot",r=t[i],["includeMetadataChanges"]),ri("Query.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++),n=Xf(t[i])?t[i]:(ti("Query.onSnapshot","function",i,t[i]),ei("Query.onSnapshot","function",i+1,t[i+1]),ei("Query.onSnapshot","function",i+2,t[i+2]),{next:t[i],error:t[i+1],complete:t[i+2]}),this.onSnapshotInternal(r,n)},$p.prototype.onSnapshotInternal=function(t,e){var n=this,r=function(t){console.error("Uncaught Error in onSnapshot:",t)};e.error&&(r=e.error.bind(e));var i=new xf({next:function(t){e.next&&e.next(new Zp(n.firestore,n._query,t))},error:r}),o=this.firestore.ensureClientConfigured(),a=o.listen(this._query,i,t);return function(){i.mute(),o.unlisten(a)}},$p.prototype.get=function(n){var r=this;return Zr("Query.get",arguments,0,1),ad("Query.get",n),new Promise(function(e,t){n&&"cache"===n.source?r.firestore.ensureClientConfigured().getDocumentsFromLocalCache(r._query).then(function(t){e(new Zp(r.firestore,r._query,t))},t):r.getViaSnapshotListener(e,t,n)})},$p.prototype.getViaSnapshotListener=function(e,n,r){var i=this.onSnapshotInternal({includeMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(t){i(),t.metadata.fromCache&&r&&"server"===r.source?n(new Qr(Ur.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):e(t)},error:n})},$p.prototype.parseDocumentIdValue=function(t){if("string"==typeof t){if(""===t)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");if(!this._query.isCollectionGroupQuery()&&-1!==t.indexOf("/"))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '"+t+"' contains a '/' character.");var e=this._query.path.child(Pi.fromString(t));if(!Bi.isDocumentKey(e))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but '"+e+"' is not because it has an odd number of segments ("+e.length+").");return new bs(this.firestore._databaseId,new Bi(e))}if(t instanceof Qp){var n=t;return new bs(this.firestore._databaseId,n._key)}throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: "+ui(t)+".")},$p.prototype.validateDisjunctiveFilterElements=function(t,e){if(!Array.isArray(t)||0===t.length)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for '"+e.toString()+"' filters.");if(10<t.length)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters support a maximum of 10 elements in the value array.");if(0<=t.indexOf(null))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters cannot contain 'null' in the value array.");if(0<t.filter(function(t){return Number.isNaN(t)}).length)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters cannot contain 'NaN' in the value array.")},$p.prototype.validateNewFilter=function(t){if(t instanceof tl){var e=[Jh.ARRAY_CONTAINS,Jh.ARRAY_CONTAINS_ANY],n=[Jh.IN,Jh.ARRAY_CONTAINS_ANY],r=0<=e.indexOf(t.op),i=0<=n.indexOf(t.op);if(t.isInequality()){var o=this._query.getInequalityFilterField();if(null!==o&&!o.isEqual(t.field))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+o.toString()+"' and '"+t.field.toString()+"'");var a=this._query.getFirstOrderByField();null!==a&&this.validateOrderByAndInequalityMatch(t.field,a)}else if(i||r){var s=null;if(i&&(s=this._query.findFilterOperator(n)),null===s&&r&&(s=this._query.findFilterOperator(e)),null!=s)throw s===t.op?new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '"+t.op.toString()+"' filter."):new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You cannot use '"+t.op.toString()+"' filters with '"+s.toString()+"' filters.")}}},$p.prototype.validateNewOrderBy=function(t){if(null===this._query.getFirstOrderByField()){var e=this._query.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},$p.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.isEqual(t))throw new Qr(Ur.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.")},$p);function $p(t,e){this._query=t,this.firestore=e}var Zp=(Object.defineProperty(td.prototype,"docs",{get:function(){var e=[];return this.forEach(function(t){return e.push(t)}),e},enumerable:!0,configurable:!0}),Object.defineProperty(td.prototype,"empty",{get:function(){return this._snapshot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(td.prototype,"size",{get:function(){return this._snapshot.docs.size},enumerable:!0,configurable:!0}),td.prototype.forEach=function(e,n){var r=this;Zr("QuerySnapshot.forEach",arguments,1,2),ti("QuerySnapshot.forEach","function",1,e),this._snapshot.docs.forEach(function(t){e.call(n,r.convertToDocumentImpl(t))})},Object.defineProperty(td.prototype,"query",{get:function(){return new Jp(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),td.prototype.docChanges=function(t){t&&(hi("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),ri("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));var e=!(!t||!t.includeMetadataChanges);if(e&&this._snapshot.excludesMetadataChanges)throw new Qr(Ur.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(i,e,o){if(o.oldDocs.isEmpty()){var n,r=0;return o.docChanges.map(function(t){var e=new Yp(i,t.doc.key,t.doc,o.fromCache,o.mutatedKeys.has(t.doc.key));return xr(t.type===vh.Added,"Invalid event type for first snapshot"),xr(!n||o.query.docComparator(n,t.doc)<0,"Got added events in wrong order"),n=t.doc,{type:"added",doc:e,oldIndex:-1,newIndex:r++}})}var a=o.oldDocs;return o.docChanges.filter(function(t){return e||t.type!==vh.Metadata}).map(function(t){var e=new Yp(i,t.doc.key,t.doc,o.fromCache,o.mutatedKeys.has(t.doc.key)),n=-1,r=-1;return t.type!==vh.Added&&(xr(0<=(n=a.indexOf(t.doc.key)),"Index for document not found"),a=a.delete(t.doc.key)),t.type!==vh.Removed&&(r=(a=a.add(t.doc)).indexOf(t.doc.key)),{type:function(t){switch(t){case vh.Added:return"added";case vh.Modified:case vh.Metadata:return"modified";case vh.Removed:return"removed";default:return Lr("Unknown change type: "+t)}}(t.type),doc:e,oldIndex:n,newIndex:r}})}(this._firestore,e,this._snapshot),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges},td.prototype.isEqual=function(t){if(!(t instanceof td))throw li("isEqual","QuerySnapshot",1,t);return this._firestore===t._firestore&&this._originalQuery.isEqual(t._originalQuery)&&this._snapshot.isEqual(t._snapshot)},td.prototype.convertToDocumentImpl=function(t){return new Yp(this._firestore,t.key,t,this.metadata.fromCache,this._snapshot.mutatedKeys.has(t.key))},td);function td(t,e,n){this._firestore=t,this._originalQuery=e,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new jp(n.hasPendingWrites,n.fromCache)}["length","forEach","map"].concat("undefined"!=typeof Symbol?[Symbol.iterator]:[]).forEach(function(t){try{Object.defineProperty(Zp.prototype.docChanges,t,{get:function(){return function(){throw new Qr(Ur.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 ed,nd=(s(rd,ed=Jp),Object.defineProperty(rd.prototype,"id",{get:function(){return this._query.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(rd.prototype,"parent",{get:function(){var t=this._query.path.popLast();return t.isEmpty()?null:new Qp(new Bi(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(rd.prototype,"path",{get:function(){return this._query.path.canonicalString()},enumerable:!0,configurable:!0}),rd.prototype.doc=function(t){if(Zr("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=di.newId()),ti("CollectionReference.doc","non-empty string",1,t),""===t)throw new Qr(Ur.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=Pi.fromString(t);return Qp.forPath(this._query.path.child(e),this.firestore)},rd.prototype.add=function(t){Jr("CollectionReference.add",arguments,1),ti("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},rd);function rd(t,e){var n=ed.call(this,Hh.atPath(t),e)||this;if(t.length%2!=1)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+t.canonicalString()+" has "+t.length);return n}function id(t,e){if(void 0===e)return{merge:!1};if(hi(t,e,["merge","mergeFields"]),ri(t,"boolean","merge",e.merge),ii(t,"mergeFields","a string or a FieldPath",e.mergeFields,function(t){return"string"==typeof t||t instanceof Ff}),void 0!==e.mergeFields&&void 0!==e.merge)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid options passed to function "+t+'(): You cannot specify both "merge" and "mergeFields".');return e}function od(t,e){return void 0===e?{}:(hi(t,e,["serverTimestamps"]),oi(t,0,"serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function ad(t,e){ei(t,"object",1,e),e&&(hi(t,e,["source"]),oi(t,0,"source",e.source,["default","server","cache"]))}function sd(t,e,n){if(e instanceof Qp){if(e.firestore!==n)throw new Qr(Ur.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw li(t,"DocumentReference",1,e)}var ud=jr(xp,"Use firebase.firestore() instead."),cd=jr(Fp,"Use firebase.firestore().runTransaction() instead."),hd=jr(Bp,"Use firebase.firestore().batch() instead."),ld=jr(Qp,"Use firebase.firestore().doc() instead."),fd=jr(Gp),pd=jr(Yp),dd=jr(Jp),md=jr(Zp),yd=jr(nd,"Use firebase.firestore().collection() instead."),gd={Firestore:ud,GeoPoint:Gh,Timestamp:ro,Blob:Ti,Transaction:cd,WriteBatch:hd,DocumentReference:ld,DocumentSnapshot:fd,Query:dd,QueryDocumentSnapshot:pd,QuerySnapshot:md,CollectionReference:yd,FieldPath:Ff,FieldValue:dp,setLogLevel:xp.setLogLevel,CACHE_SIZE_UNLIMITED:Op};function vd(t){t.INTERNAL.registerService("firestore",function(t){return new xp(t)},function(t){xr(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}(gd))}var bd=(wd.prototype.addCallback=function(t){},wd.prototype.shutdown=function(){},wd);function wd(){}var Ed="ConnectivityMonitor",Sd=(Td.prototype.addCallback=function(t){this.callbacks.push(t)},Td.prototype.shutdown=function(){window.removeEventListener("online",this.networkAvailableListener),window.removeEventListener("offline",this.networkUnavailableListener)},Td.prototype.configureNetworkMonitoring=function(){window.addEventListener("online",this.networkAvailableListener),window.addEventListener("offline",this.networkUnavailableListener)},Td.prototype.onNetworkAvailable=function(){_r(Ed,"Network connectivity changed: AVAILABLE");for(var t=0,e=this.callbacks;t<e.length;t++)(0,e[t])(0)},Td.prototype.onNetworkUnavailable=function(){_r(Ed,"Network connectivity changed: UNAVAILABLE");for(var t=0,e=this.callbacks;t<e.length;t++)(0,e[t])(1)},Td.isAvailable=function(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener},Td);function Td(){var t=this;this.networkAvailableListener=function(){return t.onNetworkAvailable()},this.networkUnavailableListener=function(){return t.onNetworkUnavailable()},this.callbacks=[],this.configureNetworkMonitoring()}var Id=(Cd.prototype.onOpen=function(t){xr(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},Cd.prototype.onClose=function(t){xr(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},Cd.prototype.onMessage=function(t){xr(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},Cd.prototype.close=function(){this.closeFn()},Cd.prototype.send=function(t){this.sendFn(t)},Cd.prototype.callOnOpen=function(){xr(void 0!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},Cd.prototype.callOnClose=function(t){xr(void 0!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},Cd.prototype.callOnMessage=function(t){xr(void 0!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},Cd);function Cd(t){this.sendFn=t.sendFn,this.closeFn=t.closeFn}var Dd="Connection",Nd={BatchGetDocuments:"batchGet",Commit:"commit"},Ad="gl-js/ fire/"+Ar,kd=(Rd.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"]=Ad},Rd.prototype.invokeRPC=function(s,n,r){var u=this,c=this.makeUrl(s);return new Promise(function(i,o){var a=new Nr;a.listenOnce(Cr.COMPLETE,function(){try{switch(a.getLastErrorCode()){case Ir.NO_ERROR:var t=a.getResponseJson();_r(Dd,"XHR received:",JSON.stringify(t)),i(t);break;case Ir.TIMEOUT:_r(Dd,'RPC "'+s+'" timed out'),o(new Qr(Ur.DEADLINE_EXCEEDED,"Request time out"));break;case Ir.HTTP_ERROR:var e=a.getStatus();if(_r(Dd,'RPC "'+s+'" failed with status:',e,"response text:",a.getResponseText()),0<e){var n=a.getResponseJson().error;if(n&&n.status&&n.message){var r=function(t){var e=t.toLowerCase().replace("_","-");return 0<=Object.values(Ur).indexOf(e)?e:Ur.UNKNOWN}(n.status);o(new Qr(r,n.message))}else o(new Qr(Ur.UNKNOWN,"Server responded with status "+a.getStatus()))}else _r(Dd,'RPC "'+s+'" failed'),o(new Qr(Ur.UNAVAILABLE,"Connection failed."));break;default:Lr('RPC "'+s+'" failed with unanticipated webchannel error '+a.getLastErrorCode()+": "+a.getLastError()+", giving up.")}}finally{_r(Dd,'RPC "'+s+'" completed.')}});var t=JSON.stringify(n);_r(Dd,"XHR sending: ",c+" "+t);var e={"Content-Type":"text/plain"};u.modifyHeadersForRequest(e,r),a.send(c,"POST",t,e,15)})},Rd.prototype.invokeStreamingRPC=function(t,e,n){return this.invokeRPC(t,e,n)},Rd.prototype.openStream=function(t,e){var n=[this.baseUrl,"/","google.firestore.v1.Firestore","/",t,"/channel"],r=Tr(),i={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling};this.modifyHeadersForRequest(i.initMessageHeaders,e),"object"==typeof navigator&&"ReactNative"===navigator.product||(i.httpHeadersOverwriteParam="$httpHeaders");var o=n.join("");function a(t,e){s.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})}_r(Dd,"Creating WebChannel: "+o+" "+i);var s=r.createWebChannel(o,i),u=!1,c=!1,h=new Id({sendFn:function(t){c?_r(Dd,"Not sending because WebChannel is closed:",t):(u||(_r(Dd,"Opening WebChannel transport."),s.open(),u=!0),_r(Dd,"WebChannel sending:",t),s.send(t))},closeFn:function(){return s.close()}});return a(Dr.EventType.OPEN,function(){c||_r(Dd,"WebChannel transport opened.")}),a(Dr.EventType.CLOSE,function(){c||(c=!0,_r(Dd,"WebChannel transport closed"),h.callOnClose())}),a(Dr.EventType.ERROR,function(t){c||(c=!0,_r(Dd,"WebChannel transport errored:",t),h.callOnClose(new Qr(Ur.UNAVAILABLE,"The operation could not be completed")))}),a(Dr.EventType.MESSAGE,function(t){if(!c){var e=t.data[0];xr(!!e,"Got a webchannel message without data.");var n=e,r=n.error||n[0]&&n[0].error;if(r){_r(Dd,"WebChannel received error:",r);var i=r.status,o=function(t){var e=fh[t];if(void 0!==e)return gh(e)}(i),a=r.message;void 0===o&&(o=Ur.INTERNAL,a="Unknown error status: "+i+" with message "+r.message),c=!0,h.callOnClose(new Qr(o,a)),s.close()}else _r(Dd,"WebChannel received:",e),h.callOnMessage(e)}}),setTimeout(function(){h.callOnOpen()},0),h},Rd.prototype.makeUrl=function(t){var e=Nd[t];xr(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1"];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("")},Rd);function Rd(t){this.databaseId=t.databaseId;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host,this.forceLongPolling=t.forceLongPolling}var Md=(Object.defineProperty(_d.prototype,"document",{get:function(){return"undefined"!=typeof document?document:null},enumerable:!0,configurable:!0}),Object.defineProperty(_d.prototype,"window",{get:function(){return"undefined"!=typeof window?window:null},enumerable:!0,configurable:!0}),_d.prototype.loadConnection=function(t){return Promise.resolve(new kd(t))},_d.prototype.newConnectivityMonitor=function(){return Sd.isAvailable()?new Sd:new bd},_d.prototype.newSerializer=function(t){return new Kl(t,{useProto3Json:!0})},_d.prototype.formatJSON=function(t){return JSON.stringify(t)},_d.prototype.atob=function(t){return atob(t)},_d.prototype.btoa=function(t){return btoa(t)},_d);function _d(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}qr.setPlatform(new Md),vd(Od)}).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
|