text: /*!
   * @license Firebase v4.5.2
   * Build: rev-646dbb2
   * Terms: https://firebase.google.com/terms/
   */
  try{webpackJsonpFirebase([1],{113:function(t,e,n){n(114)},114:function(t,e,n){"use strict";function r(){return Kt}function i(t){Kt=t}function o(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(Kt<=Vt.DEBUG){var i=(new Date).toISOString(),o=n.map(s);console.log.apply(console,["Firestore ("+jt+") "+i+" ["+t+"]: "+e].concat(o))}}function a(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(Kt<=Vt.ERROR){var r=(new Date).toISOString(),i=e.map(s);console.error.apply(console,["Firestore ("+jt+") "+r+": "+t].concat(i))}}function s(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function u(t){var e="FIRESTORE ("+jt+") INTERNAL ASSERTION FAILED: "+t;throw a(e),Error(e)}function c(t,e){t||u(e)}function h(){return Qt.getPlatform().emptyByteString}function l(t,e){function n(){var t="This constructor is private.";throw e&&(t+=" ",t+=e),new Ht(Wt.INVALID_ARGUMENT,t)}n.prototype=t.prototype;for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}function f(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function p(t,e){return void 0!==t?t:e}function d(t,e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var r=parseInt(n,10);isNaN(r)||e(r,t[n])}}function y(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])}function m(t){c(null!=t&&"object"==typeof t,"isEmpty() expects object parameter.");for(var e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function g(t){c(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}function v(t,e,n){if(e.length!==n)throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() requires "+P(n,"argument")+", but was called with "+P(e.length,"argument")+".")}function b(t,e,n){if(e.length<n)throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() requires at least "+P(n,"argument")+", but was called with "+P(e.length,"argument")+".")}function w(t,e,n,r){if(e.length<n||e.length>r)throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+P(e.length,"argument")+".")}function I(t,e,n,r){if(!(e instanceof Array)||e.length<r)throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() requires its "+n+" argument to be an array with at least "+P(r,"element")+".")}function T(t,e,n,r){C(t,e,_(n)+" argument",r)}function E(t,e,n,r){void 0!==r&&T(t,e,n,r)}function S(t,e,n,r){C(t,e,n+" option",r)}function N(t,e,n,r){void 0!==r&&S(t,e,n,r)}function C(t,e,n,r){if(typeof r!==e||"object"===e&&!D(r)){var i=A(r);throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() requires its "+n+" to be of type "+e+", but it was: "+i)}}function D(t){return"object"==typeof t&&null!==t&&Object.getPrototypeOf(t)===Object.prototype}function A(t){if(void 0===t)return"undefined";if(null===t)return"null";if("string"==typeof t)return t.length>20&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";var e=k(t);return e?"a custom "+e+" object":"an object"}return"function"==typeof t?"a function":u("Unknown wrong type: "+typeof t)}function k(t){if(t.constructor){var e=/function\s+([^\s(]+)\s*\(/,n=e.exec(""+t.constructor);if(n&&n.length>1)return n[1]}return null}function R(t,e,n){if(void 0===n)throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+_(e)+" argument, but it was undefined.")}function O(t,e,n){y(e,function(e,r){if(n.indexOf(e)<0)throw new Ht(Wt.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function M(t,e,n,r){var i=A(r);return new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() requires its "+_(n)+" argument to be a "+e+", but it was: "+i)}function _(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function P(t,e){return t+" "+e+(1===t?"":"s")}function L(t,e){return t<e?-1:t>e?1:0}function x(t,e){return null!==t&&void 0!==t?!(!e||!t.equals(e)):t===e}function B(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(!t[n].equals(e[n]))return!1;return!0}function U(t){var e=t.length-1;return 0===t.length?"":"\0"===t.charAt(e)?t.substring(0,e):t.substring(0,e)+String.fromCharCode(t.charCodeAt(e)-1)}function F(t){return t+"\0"}function V(){if("undefined"==typeof Uint8Array)throw new Ht(Wt.UNIMPLEMENTED,"Uint8Arrays are not available in this environment.")}function q(){if(!Qt.getPlatform().base64Available)throw new Ht(Wt.UNIMPLEMENTED,"Blobs are unavailable in Firestore in this environment.")}function j(t,e){return t<e?-1:t>e?1:t===e?0:isNaN(t)?isNaN(e)?0:-1:1}function K(t,e){return t===e?0!==t||1/t==1/e:t!==t&&e!==e}function Q(t){return null===t||void 0===t}function G(t){return _e(t)&&t<=Me&&t>=Oe}function W(t,e,n){if(n.equals(ge.INSTANCE)){if(e!==Le.EQUAL)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new Be(t)}if(n.equals(Ie.NAN)){if(e!==Le.EQUAL)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new Ue(t)}return new xe(t,e,n)}function H(t){switch(t){case Wt.OK:return u("Treated status OK as error");case Wt.CANCELLED:case Wt.UNKNOWN:case Wt.DEADLINE_EXCEEDED:case Wt.RESOURCE_EXHAUSTED:case Wt.INTERNAL:case Wt.UNAVAILABLE:case Wt.UNAUTHENTICATED:return!1;case Wt.INVALID_ARGUMENT:case Wt.NOT_FOUND:case Wt.ALREADY_EXISTS:case Wt.PERMISSION_DENIED:case Wt.FAILED_PRECONDITION:case Wt.ABORTED:case Wt.OUT_OF_RANGE:case Wt.UNIMPLEMENTED:case Wt.DATA_LOSS:return!0;default:return u("Unknown status code: "+t)}}function z(t){var e=tn[t];if(void 0!==e)return X(e)}function X(t){switch(t){case tn.OK:return Wt.OK;case tn.CANCELLED:return Wt.CANCELLED;case tn.UNKNOWN:return Wt.UNKNOWN;case tn.DEADLINE_EXCEEDED:return Wt.DEADLINE_EXCEEDED;case tn.RESOURCE_EXHAUSTED:return Wt.RESOURCE_EXHAUSTED;case tn.INTERNAL:return Wt.INTERNAL;case tn.UNAVAILABLE:return Wt.UNAVAILABLE;case tn.UNAUTHENTICATED:return Wt.UNAUTHENTICATED;case tn.INVALID_ARGUMENT:return Wt.INVALID_ARGUMENT;case tn.NOT_FOUND:return Wt.NOT_FOUND;case tn.ALREADY_EXISTS:return Wt.ALREADY_EXISTS;case tn.PERMISSION_DENIED:return Wt.PERMISSION_DENIED;case tn.FAILED_PRECONDITION:return Wt.FAILED_PRECONDITION;case tn.ABORTED:return Wt.ABORTED;case tn.OUT_OF_RANGE:return Wt.OUT_OF_RANGE;case tn.UNIMPLEMENTED:return Wt.UNIMPLEMENTED;case tn.DATA_LOSS:return Wt.DATA_LOSS;default:return u("Unknown status code: "+t)}}function Y(t){if(void 0===t)return tn.OK;switch(t){case Wt.OK:return tn.OK;case Wt.CANCELLED:return tn.CANCELLED;case Wt.UNKNOWN:return tn.UNKNOWN;case Wt.DEADLINE_EXCEEDED:return tn.DEADLINE_EXCEEDED;case Wt.RESOURCE_EXHAUSTED:return tn.RESOURCE_EXHAUSTED;case Wt.INTERNAL:return tn.INTERNAL;case Wt.UNAVAILABLE:return tn.UNAVAILABLE;case Wt.UNAUTHENTICATED:return tn.UNAUTHENTICATED;case Wt.INVALID_ARGUMENT:return tn.INVALID_ARGUMENT;case Wt.NOT_FOUND:return tn.NOT_FOUND;case Wt.ALREADY_EXISTS:return tn.ALREADY_EXISTS;case Wt.PERMISSION_DENIED:return tn.PERMISSION_DENIED;case Wt.FAILED_PRECONDITION:return tn.FAILED_PRECONDITION;case Wt.ABORTED:return tn.ABORTED;case Wt.OUT_OF_RANGE:return tn.OUT_OF_RANGE;case Wt.UNIMPLEMENTED:return tn.UNIMPLEMENTED;case Wt.DATA_LOSS:return tn.DATA_LOSS;default:return u("Unknown status code: "+t)}}function J(t){switch(t){case 200:return Wt.OK;case 400:return Wt.INVALID_ARGUMENT;case 401:return Wt.UNAUTHENTICATED;case 403:return Wt.PERMISSION_DENIED;case 404:return Wt.NOT_FOUND;case 409:return Wt.ABORTED;case 416:return Wt.OUT_OF_RANGE;case 429:return Wt.RESOURCE_EXHAUSTED;case 499:return Wt.CANCELLED;case 500:return Wt.UNKNOWN;case 501:return Wt.UNIMPLEMENTED;case 503:return Wt.UNAVAILABLE;case 504:return Wt.DEADLINE_EXCEEDED;default:return t>=200&&t<300?Wt.OK:t>=400&&t<500?Wt.FAILED_PRECONDITION:t>=500&&t<600?Wt.INTERNAL:Wt.UNKNOWN}}function Z(){return ln}function $(){return fn}function tt(){return pn}function et(){return dn}function nt(t,e){e.length>0&&(t.resumeToken=e)}function rt(t,e){c(!Q(t),e+" is missing")}function it(t){return"number"==typeof t?t:"string"==typeof t?parseInt(t,10):u("can't parse "+t)}function ot(t,e,n){return e===n||!e&&n in t}function at(t){if(t.search(Ln)>=0)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(Pn.bind.apply(Pn,[void 0].concat(t.split("."))))}catch(e){throw new Ht(Wt.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}function st(t,e){var n=function(t){switch(t){case xn.Added:return 1;case xn.Modified:case xn.Metadata:return 2;case xn.Removed:return 0;default:return u("Unknown ChangeType: "+t)}};return n(t)-n(e)}function ut(t){for(var e="",n=0;n<t.length;n++)e.length>0&&(e=ht(e)),e=ct(t.get(n),e);return ht(e)}function ct(t,e){for(var n=e,r=t.length,i=0;i<r;i++){var o=t.charAt(i);switch(o){case"\0":n+=sr+cr;break;case sr:n+=sr+hr;break;default:n+=o}}return n}function ht(t){return t+sr+ur}function lt(t){var e=t.length;if(c(e>=2,"Invalid path "+t),2===e)return c(t.charAt(0)===sr&&t.charAt(1)===ur,"Non-empty path "+t+" had length 2"),re.EMPTY_PATH;for(var n=e-2,r=[],i="",o=0;o<e;){var a=t.indexOf(sr,o);switch((a<0||a>n)&&u('Invalid encoded resource path: "'+t+'"'),t.charAt(a+1)){case ur:var s=t.substring(o,a),h=void 0;0===i.length?h=s:(i+=s,h=i,i=""),r.push(h);break;case cr:i+=t.substring(o,a),i+="\0";break;case hr:i+=t.substring(o,a+1);break;default:u('Invalid encoded resource path: "'+t+'"')}o=a+2}return new re(r)}function ft(t,e){c(0===e,"Unexpected upgrade from version "+e),t.createObjectStore(pr.store,{keyPath:pr.keyPath}),t.createObjectStore(dr.store,{keyPath:dr.keyPath}),t.createObjectStore(br.store,{keyPath:br.keyPath}).createIndex(br.documentTargetsIndex,br.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(vr.store,{keyPath:vr.keyPath}).createIndex(vr.queryTargetsIndexName,vr.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(yr.store),t.createObjectStore(gr.store),t.createObjectStore(fr.store),t.createObjectStore(wr.store)}function pt(t){return new Gn(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){n(t.target.error)}})}function dt(t){return c("string"==typeof t,"Persisting non-string stream token not supported."),t}function yt(t){return vt(t,dr.store)}function mt(t){return vt(t,yr.store)}function gt(t){return vt(t,pr.store)}function vt(t,e){return t instanceof Sr?t.store(e):u("Invalid transaction object provided!")}function bt(t){return Tt(t,vr.store)}function wt(t){return Tt(t,wr.store)}function It(t){return Tt(t,br.store)}function Tt(t,e){return t instanceof Sr?t.store(e):u("Invalid transaction object provided!")}function Et(t){return t instanceof Sr?t.store(gr.store):u("Invalid transaction object provided!")}function St(t){return t.path.toArray()}function Nt(t){return void 0!==t.documents}function Ct(t){if(!t)return new oi;switch(t.type){case"google-auth":return new si(t.client);case"gapi":return new ci(t.client,t.sessionIndex||"0");case"provider":return t.client;default:throw new Ht(Wt.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}function Dt(t){return At(t,["next","error","complete"])}function At(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}function kt(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof Jt||t instanceof Xt||t instanceof bi||t instanceof li)}function Rt(t,e,n){if(!kt(n)||!D(n)){var r=A(n);throw"an object"===r?e.createError(t+" a custom object"):e.createError(t+" "+r)}}function Ot(t,e){if(e instanceof Pn)return e.t;if("string"==typeof e)return Mt(t,e);throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function Mt(t,e){try{return at(e).t}catch(e){var n=_t(e);throw new Ht(Wt.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. "+n)}}function _t(t){return t instanceof Error?t.message:""+t}function Pt(t,e){return void 0===e?{merge:!1}:(O(t,e,["merge"]),N(t,"boolean","merge",e.merge),e)}function Lt(t,e,n){if(e instanceof ki){if(e.firestore!==n)throw new Ht(Wt.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw M(t,"DocumentReference",1,e)}function xt(t,e){if(e.oldDocs.isEmpty()){var n,r=0;return e.docChanges.map(function(i){var o=new Ri(t,i.doc.key,i.doc,e.fromCache);return c(i.type===xn.Added,"Invalid event type for first snapshot"),c(!n||e.query.docComparator(n,i.doc)<0,"Got added events in wrong order"),n=i.doc,{type:"added",doc:o,oldIndex:-1,newIndex:r++}})}var i=e.oldDocs;return e.docChanges.map(function(n){var r=new Ri(t,n.doc.key,n.doc,e.fromCache),o=-1,a=-1;return n.type!==xn.Added&&(o=i.indexOf(n.doc.key),c(o>=0,"Index for document not found"),i=i.delete(n.doc.key)),n.type!==xn.Removed&&(i=i.add(n.doc),a=i.indexOf(n.doc.key)),{type:Bt(n.type),doc:r,oldIndex:o,newIndex:a}})}function Bt(t){switch(t){case xn.Added:return"added";case xn.Modified:case xn.Metadata:return"modified";case xn.Removed:return"removed";default:return u("Unknown change type: "+t)}}function Ut(t){t.INTERNAL.registerService("firestore",function(t){return new Ci(t)},g(ji))}function Ft(t){Ut(t)}Object.defineProperty(e,"__esModule",{value:!0});var Vt,qt=n(6),jt=qt.default.SDK_VERSION;!function(t){t[t.DEBUG=0]="DEBUG",t[t.ERROR=1]="ERROR",t[t.SILENT=2]="SILENT"}(Vt=Vt||(Vt={}));var Kt=Vt.ERROR,Qt=function(){function t(){}return t.setPlatform=function(e){t.platform&&u("Platform already defined"),t.platform=e},t.getPlatform=function(){return t.platform||u("Platform not set"),t.platform},t}(),Gt=this&&this.__extends||function(){var t=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])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Wt={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"},Ht=function(t){function e(e,n){var r=t.call(this,n)||this;return r.code=e,r.message=n,r.name="FirebaseError",r.toString=function(){return r.name+": [code="+r.code+"]: "+r.message},r}return Gt(e,t),e}(Error),zt=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return c(20===e.length,"Invalid auto ID: "+e),e},t}(),Xt=function(){function t(t){q(),this.e=t}return t.fromBase64String=function(e){v("Blob.fromBase64String",arguments,1),T("Blob.fromBase64String","string",1,e),q();try{return new t(Qt.getPlatform().atob(e))}catch(t){throw new Ht(Wt.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},t.fromUint8Array=function(e){if(v("Blob.fromUint8Array",arguments,1),V(),!(e instanceof Uint8Array))throw M("Blob.fromUint8Array","Uint8Array",1,e);return new t(Array.prototype.map.call(e,function(t){return String.fromCharCode(t)}).join(""))},t.prototype.toBase64=function(){return v("Blob.toBase64",arguments,0),q(),Qt.getPlatform().btoa(this.e)},t.prototype.toUint8Array=function(){v("Blob.toUint8Array",arguments,0),V();for(var t=new Uint8Array(this.e.length),e=0;e<this.e.length;e++)t[e]=this.e.charCodeAt(e);return t},t.prototype.toString=function(){return"Blob(base64: "+this.toBase64()+")"},t.prototype.n=function(t){return this.e===t.e},t.prototype.r=function(t){return L(this.e,t.e)},t}(),Yt=l(Xt,"Use Blob.fromUint8Array() or Blob.fromBase64String() instead."),Jt=function(){function t(t,e){if(v("GeoPoint",arguments,2),T("GeoPoint","number",1,t),T("GeoPoint","number",2,e),!isFinite(t)||t<-90||t>90)throw new Ht(Wt.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new Ht(Wt.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this.p=t,this.d=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this.p},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this.d},enumerable:!0,configurable:!0}),t.prototype.n=function(t){return this.p===t.p&&this.d===t.d},t.prototype.r=function(t){return L(this.p,t.p)||L(this.d,t.d)},t}(),Zt=function(){function t(t,e,n,r){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r}return t}(),$t="(default)",te=function(){function t(t,e){this.projectId=t,this.database=e||$t}return Object.defineProperty(t.prototype,"isDefaultDatabase",{get:function(){return this.database===$t},enumerable:!0,configurable:!0}),t.prototype.equals=function(e){return e instanceof t&&e.projectId===this.projectId&&e.database===this.database},t.prototype.compareTo=function(t){return L(this.projectId,t.projectId)||L(this.database,t.database)},t}(),ee=this&&this.__extends||function(){var t=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])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),ne=function(){function t(t,e,n){this.init(t,e,n)}return t.prototype.init=function(t,e,n){void 0===e?e=0:e>t.length&&u("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&u("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n},t.prototype.construct=function(t,e,n){var r=Object.create(Object.getPrototypeOf(this));return r.init(t,e,n),r},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.equals=function(e){return 0===t.comparator(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach(function(t){n.push(t)}):"string"==typeof e?n.push(e):u("Unknown parameter type for Path.child(): "+e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,c(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return c(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return c(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return c(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},t.prototype.get=function(t){return c(t<this.length,"Index out of range"),this.segments[this.offset+t]},t.prototype.isEmpty=function(){return 0===this.length},t.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},t.prototype.forEach=function(t){for(var e=this.offset,n=this.limit();e<n;e++)t(this.segments[e])},t.prototype.toArray=function(){return this.segments.slice(this.offset,this.limit())},t.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(i>o)return 1}return t.length<e.length?-1:t.length>e.length?1:0},t}(),re=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ee(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(t){if(t.indexOf("//")>=0)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(ne),ie=/^[_a-zA-Z][_a-zA-Z0-9]*$/,oe=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ee(e,t),e.isValidIdentifier=function(t){return ie.test(t)},e.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(t){for(var n=[],r="",i=0,o=function(){if(0===r.length)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},a=!1;i<t.length;){var s=t[i];if("\\"===s){if(i+1===t.length)throw new Ht(Wt.INVALID_ARGUMENT,"Path has trailing escape character: "+t);var u=t[i+1];if("\\"!==u&&"."!==u&&"`"!==u)throw new Ht(Wt.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);r+=u,i+=2}else"`"===s?(a=!a,i++):"."!==s||a?(r+=s,i++):(o(),i++)}if(o(),a)throw new Ht(Wt.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new e(n)},e.EMPTY_PATH=new e([]),e}(ne),ae=function(){function t(e){this.path=e,c(t.isDocumentKey(e),"Invalid DocumentKey with an odd number of segments: "+e.toArray().join("/"))}return t.prototype.equals=function(t){return null!==t&&0===re.comparator(this.path,t.path)},t.prototype.toString=function(){return""+this.path},t.comparator=function(t,e){return re.comparator(t.path,e.path)},t.isDocumentKey=function(t){return t.length%2==0},t.fromSegments=function(e){return new t(new re(e.slice()))},t.fromPathString=function(e){return new t(re.fromString(e))},t.EMPTY=new t(new re([])),t}(),se=function(){function t(t,e,n,r){this.key=t,this.version=e,this.data=n,this.hasLocalMutations=r.hasLocalMutations}return t.prototype.field=function(t){return this.data.field(t)},t.prototype.fieldValue=function(t){var e=this.field(t);return e?e.value():void 0},t.prototype.value=function(){return this.data.value()},t.prototype.equals=function(e){return e instanceof t&&this.key.equals(e.key)&&this.version.equals(e.version)&&this.data.equals(e.data)&&this.hasLocalMutations===e.hasLocalMutations},t.prototype.toString=function(){return"Document("+this.key+", "+this.version+", "+this.data+", {hasLocalMutations: "+this.hasLocalMutations+"})"},t.compareByKey=function(t,e){return ae.comparator(t.key,e.key)},t.compareByField=function(t,e,n){var r=e.field(t),i=n.field(t);return void 0!==r&&void 0!==i?r.compareTo(i):u("Trying to compare documents on fields that don't exist")},t}(),ue=function(){function t(t,e){this.key=t,this.version=e}return t.prototype.toString=function(){return"NoDocument("+this.key+", "+this.version+")"},t.prototype.equals=function(t){return t&&t.version.equals(this.version)&&t.key.equals(this.key)},t.compareByKey=function(t,e){return ae.comparator(t.key,e.key)},t}(),ce=function(){function t(t,e){this.comparator=t,this.root=e||le.EMPTY}return t.prototype.insert=function(e,n){return new t(this.comparator,this.root.insert(e,n,this.comparator).copy(null,null,le.BLACK,null,null))},t.prototype.remove=function(e){return new t(this.comparator,this.root.remove(e,this.comparator).copy(null,null,le.BLACK,null,null))},t.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:n>0&&(e=e.right)}return null},t.prototype.getPredecessorKey=function(t){for(var e=this.root,n=null;!e.isEmpty();){var r=this.comparator(t,e.key);if(0===r){if(e.left.isEmpty())return n?n.key:null;for(e=e.left;!e.right.isEmpty();)e=e.right;return e.key}r<0?e=e.left:r>0&&(n=e,e=e.right)}throw u("Attempted to find predecessor key for a nonexistent key.  What gives?")},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.isEmpty();){var r=this.comparator(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal(function(e,n){return t(e,n),!1})},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(t){return new he(this.root,null,this.comparator,!1,t)},t.prototype.getIteratorFrom=function(t,e){return new he(this.root,t,this.comparator,!1,e)},t.prototype.getReverseIterator=function(t){return new he(this.root,null,this.comparator,!0,t)},t.prototype.getReverseIteratorFrom=function(t,e){return new he(this.root,t,this.comparator,!0,e)},t}(),he=function(){function t(t,e,n,r,i){this.resultGenerator=i||null,this.isReverse=r,this.nodeStack=[];for(var o=1;!t.isEmpty();)if(o=e?n(t.key,e):1,r&&(o*=-1),o<0)t=this.isReverse?t.left:t.right;else{if(0===o){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){c(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t,e=this.nodeStack.pop();if(t=this.resultGenerator?this.resultGenerator(e.key,e.value):{key:e.key,value:e.value},this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return this.resultGenerator?this.resultGenerator(t.key,t.value):{key:t.key,value:t.value}},t}(),le=function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:t.EMPTY,this.right=null!=o?o:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,i=n(t,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===i?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n)),r.fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()},t.prototype.remove=function(e,n){var r,i=this;if(n(e,i.key)<0)i.left.isEmpty()||i.left.isRed()||i.left.left.isRed()||(i=i.moveRedLeft()),i=i.copy(null,null,null,i.left.remove(e,n),null);else{if(i.left.isRed()&&(i=i.rotateRight()),i.right.isEmpty()||i.right.isRed()||i.right.left.isRed()||(i=i.moveRedRight()),0===n(e,i.key)){if(i.right.isEmpty())return t.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.removeMin())}i=i.copy(null,null,null,null,i.right.remove(e,n))}return i.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw u("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw u("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw u("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),fe=function(){function t(){this.size=0}return t.prototype.copy=function(t,e,n,r,i){return this},t.prototype.insert=function(t,e,n){return new le(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();le.EMPTY=new fe;var pe,de=this&&this.__extends||function(){var t=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])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.NullValue=0]="NullValue",t[t.BooleanValue=1]="BooleanValue",t[t.NumberValue=2]="NumberValue",t[t.TimestampValue=3]="TimestampValue",t[t.StringValue=4]="StringValue",t[t.BlobValue=5]="BlobValue",t[t.RefValue=6]="RefValue",t[t.GeoPointValue=7]="GeoPointValue",t[t.ArrayValue=8]="ArrayValue",t[t.ObjectValue=9]="ObjectValue"}(pe=pe||(pe={}));var ye,me=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":""+t},t.prototype.defaultCompareTo=function(t){return c(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),L(this.typeOrder,t.typeOrder)},t}(),ge=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=pe.NullValue,e.internalValue=null,e}return de(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(me),ve=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.BooleanValue,n}return de(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(this,t):this.defaultCompareTo(t)},e.of=function(t){return t?e.TRUE:e.FALSE},e.TRUE=new e(!0),e.FALSE=new e(!1),e}(me),be=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.NumberValue,n}return de(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?j(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(me),we=function(t){function e(e){return t.call(this,e)||this}return de(e,t),e.prototype.equals=function(t){return t instanceof e&&K(this.internalValue,t.internalValue)},e}(be),Ie=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return de(e,t),e.prototype.equals=function(t){return t instanceof e&&K(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(be),Te=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.StringValue,n}return de(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(me),Ee=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.TimestampValue,n}return de(e,t),e.prototype.value=function(){return this.internalValue.toDate()},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.equals(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.compareTo(t.internalValue):t instanceof Se?-1:this.defaultCompareTo(t)},e}(me),Se=function(t){function e(e){var n=t.call(this)||this;return n.localWriteTime=e,n.typeOrder=pe.TimestampValue,n}return de(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e&&this.localWriteTime.equals(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime.compareTo(t.localWriteTime):t instanceof Ee?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return"<ServerTimestamp localTime="+this.localWriteTime+">"},e}(me),Ne=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.BlobValue,n}return de(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(me),Ce=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=pe.RefValue,r}return de(e,t),e.prototype.value=function(){return this.key},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.databaseId.equals(t.databaseId)},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:ae.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(me),De=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.GeoPointValue,n}return de(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(me),Ae=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.ObjectValue,n}return de(e,t),e.prototype.value=function(){var t={};return this.internalValue.inorderTraversal(function(e,n){t[e]=n.value()}),t},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.equals=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext();if(i.key!==o.key||!i.value.equals(o.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext(),a=L(i.key,o.key)||i.value.compareTo(o.value);if(a)return a}return L(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(t,n){if(c(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),n);var r=this.child(t.firstSegment());r instanceof e||(r=e.EMPTY);var i=r.set(t.popFirst(),n);return this.setChild(t.firstSegment(),i)},e.prototype.delete=function(t){if(c(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.internalValue.remove(t.firstSegment()));var n=this.child(t.firstSegment());if(n instanceof e){var r=n.delete(t.popFirst());return new e(this.internalValue.insert(t.firstSegment(),r))}return this},e.prototype.contains=function(t){return void 0!==this.field(t)},e.prototype.field=function(t){c(!t.isEmpty(),"Can't get field of empty path");var n=this;return t.forEach(function(t){n=n instanceof e?n.internalValue.get(t)||void 0:void 0}),n},e.prototype.toString=function(){return JSON.stringify(this.value())},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new ce(L)),e}(me),ke=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.ArrayValue,n}return de(e,t),e.prototype.value=function(){return this.internalValue.map(function(t){return t.value()})},e.prototype.forEach=function(t){this.internalValue.forEach(t)},e.prototype.equals=function(t){if(t instanceof e){if(this.internalValue.length!==t.internalValue.length)return!1;for(var n=0;n<this.internalValue.length;n++)if(!this.internalValue[n].equals(t.internalValue[n]))return!1;return!0}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=Math.min(this.internalValue.length,t.internalValue.length),r=0;r<n;r++){var i=this.internalValue[r].compareTo(t.internalValue[r]);if(i)return i}return L(this.internalValue.length,t.internalValue.length)}return this.defaultCompareTo(t)},e.prototype.toString=function(){return JSON.stringify(this.value())},e}(me),Re=Number,Oe=Re.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),Me=Re.MAX_SAFE_INTEGER||Math.pow(2,53)-1,_e=Re.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},Pe=function(){function t(t,e,n,r,i,o){void 0===e&&(e=[]),void 0===n&&(n=[]),void 0===r&&(r=null),void 0===i&&(i=null),void 0===o&&(o=null),this.path=t,this.explicitOrderBy=e,this.filters=n,this.limit=r,this.startAt=i,this.endAt=o,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}return t.atPath=function(e){return new t(e)},Object.defineProperty(t.prototype,"orderBy",{get:function(){if(null===this.memoizedOrderBy){var t=this.getInequalityFilterField(),e=this.getFirstOrderByField();if(null!==t&&null===e)t.isKeyField()?this.memoizedOrderBy=[je]:this.memoizedOrderBy=[new qe(t),je];else{c(null===t||null!==e&&t.equals(e),"First orderBy should match inequality field."),this.memoizedOrderBy=[];for(var n=!1,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=this.explicitOrderBy.length>0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:Fe.ASCENDING;this.memoizedOrderBy.push(a===Fe.ASCENDING?je:Ke)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(e){c(null==this.getInequalityFilterField()||!(e instanceof xe)||!e.isInequality()||e.field.equals(this.getInequalityFilterField()),"Query must only have one inequality field."),c(!ae.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){c(!ae.isDocumentKey(this.path),"No ordering allowed for document query"),c(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();t+="|f:";for(var e=0,n=this.filters;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+=",";Q(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},t.prototype.toString=function(){var t="Query("+this.path.canonicalString();return this.filters.length>0&&(t+=", filters: ["+this.filters.join(", ")+"]"),Q(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.equals=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].equals(t.orderBy[e]))return!1;if(this.filters.length!==t.filters.length)return!1;for(var e=0;e<this.filters.length;e++)if(!this.filters[e].equals(t.filters[e]))return!1;return!!this.path.equals(t.path)&&!(null!==this.startAt?!this.startAt.equals(t.startAt):null!==t.startAt)&&(null!==this.endAt?this.endAt.equals(t.endAt):null===t.endAt)},t.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 c(n,"orderBy used that doesn't compare on key field"),0},t.prototype.matches=function(t){return this.matchesAncestor(t)&&this.matchesOrderBy(t)&&this.matchesFilters(t)&&this.matchesBounds(t)},t.prototype.hasLimit=function(){return!Q(this.limit)},t.prototype.getFirstOrderByField=function(){return this.explicitOrderBy.length>0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t<e.length;t++){var n=e[t];if(n instanceof xe&&n.isInequality())return n.field}return null},t.prototype.isDocumentQuery=function(){return ae.isDocumentKey(this.path)&&0===this.filters.length},t.prototype.matchesAncestor=function(t){var e=t.key.path;return ae.isDocumentKey(this.path)?this.path.equals(e):this.path.isPrefixOf(e)&&this.path.length===e.length-1},t.prototype.matchesOrderBy=function(t){for(var e=0,n=this.explicitOrderBy;e<n.length;e++){var r=n[e];if(!r.field.isKeyField()&&void 0===t.field(r.field))return!1}return!0},t.prototype.matchesFilters=function(t){for(var e=0,n=this.filters;e<n.length;e++)if(!n[e].matches(t))return!1;return!0},t.prototype.matchesBounds=function(t){return!(this.startAt&&!this.startAt.sortsBeforeDocument(this.orderBy,t)||this.endAt&&this.endAt.sortsBeforeDocument(this.orderBy,t))},t.prototype.assertValidBound=function(t){c(t.position.length<=this.orderBy.length,"Bound is longer than orderBy")},t}(),Le=function(){function t(t){this.name=t}return t.fromString=function(e){switch(e){case"<":return t.LESS_THAN;case"<=":return t.LESS_THAN_OR_EQUAL;case"==":return t.EQUAL;case">=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;default:return u("Unknown relation: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.equals=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t}(),xe=function(){function t(t,e,n){this.field=t,this.op=e,this.value=n}return t.prototype.matches=function(t){if(this.field.isKeyField()){c(this.value instanceof Ce,"Comparing on key, but filter value not a RefValue");var e=this.value,n=ae.comparator(t.key,e.key);return this.matchesComparison(n)}var r=t.field(this.field);return void 0!==r&&this.matchesValue(r)},t.prototype.matchesValue=function(t){return this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},t.prototype.matchesComparison=function(t){switch(this.op){case Le.LESS_THAN:return t<0;case Le.LESS_THAN_OR_EQUAL:return t<=0;case Le.EQUAL:return 0===t;case Le.GREATER_THAN:return t>0;case Le.GREATER_THAN_OR_EQUAL:return t>=0;default:return u("Unknown relation op"+this.op)}},t.prototype.isInequality=function(){return this.op!==Le.EQUAL},t.prototype.canonicalId=function(){return this.field.canonicalString()+""+this.op+this.value},t.prototype.equals=function(e){return e instanceof t&&this.op.equals(e.op)&&this.field.equals(e.field)&&this.value.equals(e.value)},t.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},t}(),Be=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&null===e.value()},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},t.prototype.toString=function(){return this.field.canonicalString()+" IS null"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Ue=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field).value();return"number"==typeof e&&isNaN(e)},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Fe=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),Ve=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e<n.length;e++)t+=""+n[e];return t},t.prototype.sortsBeforeDocument=function(t,e){c(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())c(o instanceof Ce,"Bound has a non-key value where the key path is being used."),n=ae.comparator(o.key,e.key);else{var a=e.field(i.field);c(void 0!==a,"Field should exist since document matched the orderBy already."),n=o.compareTo(a)}if(i.dir===Fe.DESCENDING&&(n*=-1),0!==n)break}return this.before?n<=0:n<0},t.prototype.equals=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];return n.equals(r)}return!0},t}(),qe=function(){function t(t,e){this.field=t,void 0===e&&(e=Fe.ASCENDING),this.dir=e,this.isKeyOrderBy=t.isKeyField()}return t.prototype.compare=function(t,e){var n=this.isKeyOrderBy?se.compareByKey(t,e):se.compareByField(this.field,t,e);switch(this.dir){case Fe.ASCENDING:return n;case Fe.DESCENDING:return-1*n;default:return u("Unknown direction: "+this.dir)}},t.prototype.canonicalId=function(){return this.field.canonicalString()+""+this.dir},t.prototype.toString=function(){return this.field.canonicalString()+" ("+this.dir+")"},t.prototype.equals=function(t){return this.dir===t.dir&&this.field.equals(t.field)},t}(),je=new qe(oe.keyField(),Fe.ASCENDING),Ke=new qe(oe.keyField(),Fe.DESCENDING),Qe=RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/),Ge=function(){function t(t,e){this.seconds=t,this.nanos=e,c(e>=0,"timestamp nanoseconds out of range: "+e),c(e<1e9,"timestamp nanoseconds out of range"+e),c(t>=-62135596800,"timestamp seconds out of range: "+t),c(t<253402300800,"timestamp seconds out of range"+t)}return t.now=function(){return t.fromEpochMilliseconds(Date.now())},t.fromDate=function(e){return t.fromEpochMilliseconds(e.getTime())},t.fromEpochMilliseconds=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.fromISOString=function(e){var n=0,r=Qe.exec(e);if(c(!!r,"invalid timestamp: "+e),r[1]){var i=r[1];i=(i+"000000000").substr(0,9),n=parseInt(i,10)}var o=new Date(e);return new t(Math.floor(o.getTime()/1e3),n)},t.prototype.toDate=function(){return new Date(this.toEpochMilliseconds())},t.prototype.toEpochMilliseconds=function(){return 1e3*this.seconds+this.nanos/1e6},t.prototype.compareTo=function(t){return this.seconds===t.seconds?L(this.nanos,t.nanos):L(this.seconds,t.seconds)},t.prototype.equals=function(t){return t.seconds===this.seconds&&t.nanos===this.nanos},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanos="+this.nanos+")"},t}(),We=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new Ge(n,e%1e6*1e3))},t.fromTimestamp=function(e){return new t(e)},t.forDeletedDoc=function(){return t.MIN},t.prototype.compareTo=function(t){return this.timestamp.compareTo(t.timestamp)},t.prototype.equals=function(t){return this.timestamp.equals(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanos/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new Ge(0,0)),t}();!function(t){t[t.Listen=0]="Listen",t[t.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",t[t.LimboResolution=2]="LimboResolution"}(ye=ye||(ye={}));var He,ze=function(){function t(t,e,n,r,i){void 0===r&&(r=We.MIN),void 0===i&&(i=h()),this.query=t,this.targetId=e,this.purpose=n,this.snapshotVersion=r,this.resumeToken=i}return t.prototype.update=function(e){return new t(this.query,this.targetId,this.purpose,e.snapshotVersion,e.resumeToken)},t.prototype.equals=function(t){return this.targetId===t.targetId&&this.purpose===t.purpose&&this.snapshotVersion.equals(t.snapshotVersion)&&this.resumeToken===t.resumeToken&&this.query.equals(t.query)},t}(),Xe=this&&this.__extends||function(){var t=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])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ye=function(){function t(t){this.fields=t}return t.prototype.equals=function(t){return B(this.fields,t.fields)},t}(),Je=function(){function t(){}return t.prototype.equals=function(e){return e instanceof t},t.instance=new t,t}(),Ze=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.equals=function(t){return this.field.equals(t.field)&&this.transform.equals(t.transform)},t}(),$e=function(){function t(t,e){this.version=t,this.transformResults=e}return t}();!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(He=He||(He={}));var tn,en=function(){function t(t,e){this.updateTime=t,this.exists=e,c(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof se&&t.version.equals(this.updateTime):void 0!==this.exists?this.exists?t instanceof se:null===t||t instanceof ue:(c(this.isNone,"Precondition should be empty"),!0)},t.prototype.equals=function(t){return x(this.updateTime,t.updateTime)&&this.exists===t.exists},t.NONE=new t,t}(),nn=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&c(t.key.equals(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof se?t.version:We.MIN},t}(),rn=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.value=n,i.precondition=r,i.type=He.Set,i}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by SetMutation.");var n=nn.getPostMutationVersion(t);return new se(this.key,n,this.value,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=nn.getPostMutationVersion(t);return new se(this.key,n,this.value,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.value.equals(t.value)&&this.precondition.equals(t.precondition)},e}(nn),on=function(t){function e(e,n,r,i){var o=t.call(this)||this;return o.key=e,o.data=n,o.fieldMask=r,o.precondition=i,o.type=He.Patch,o}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return t;var n=nn.getPostMutationVersion(t),r=this.patchDocument(t);return new se(this.key,n,r,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=nn.getPostMutationVersion(t),r=this.patchDocument(t);return new se(this.key,n,r,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.fieldMask.equals(t.fieldMask)&&this.precondition.equals(t.precondition)},e.prototype.patchDocument=function(t){var e;return e=t instanceof se?t.data:Ae.EMPTY,this.patchObject(e)},e.prototype.patchObject=function(t){for(var e=0,n=this.fieldMask.fields;e<n.length;e++){var r=n[e],i=this.data.field(r);t=void 0!==i?t.set(r,i):t.delete(r)}return t},e}(nn),an=function(t){function e(e,n){var r=t.call(this)||this;return r.key=e,r.fieldTransforms=n,r.type=He.Transform,r.precondition=en.exists(!0),r}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),c(null!=e.transformResults,"Transform results missing for TransformMutation.");var n=e.transformResults;if(!this.precondition.isValidFor(t))return t;var r=this.requireDocument(t),i=this.transformObject(r.data,n);return new se(this.key,r.version,i,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=this.requireDocument(t),r=this.localTransformResults(e),i=this.transformObject(n.data,r);return new se(this.key,n.version,i,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&B(this.fieldTransforms,t.fieldTransforms)&&this.precondition.equals(t.precondition)},e.prototype.requireDocument=function(t){c(t instanceof se,"Unknown MaybeDocument type "+t);var e=t;return c(e.key.equals(this.key),"Can only transform a document with the same key"),e},e.prototype.localTransformResults=function(t){for(var e=[],n=0,r=this.fieldTransforms;n<r.length;n++){var i=r[n],o=i.transform;if(!(o instanceof Je))return u("Encountered unknown transform: "+o);e.push(new Se(t))}return e},e.prototype.transformObject=function(t,e){c(e.length===this.fieldTransforms.length,"TransformResults length mismatch.");for(var n=0;n<this.fieldTransforms.length;n++){var r=this.fieldTransforms[n],i=r.transform,o=r.field;if(!(i instanceof Je))return u("Encountered unknown transform: "+i);t=t.set(o,e[n])}return t},e}(nn),sn=function(t){function e(e,n){var r=t.call(this)||this;return r.key=e,r.precondition=n,r.type=He.Delete,r}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){return this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by DeleteMutation."),new ue(this.key,We.MIN)},e.prototype.applyToLocalView=function(t,e){return this.verifyKeyMatches(t),this.precondition.isValidFor(t)?(t&&c(t.key.equals(this.key),"Can only apply mutation to document with same key"),new ue(this.key,We.forDeletedDoc())):t},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.precondition.equals(t.precondition)},e}(nn),un=function(){function t(t){this.count=t}return t.prototype.equals=function(t){return t&&t.count===this.count},t}();!function(t){t[t.OK=0]="OK",t[t.CANCELLED=1]="CANCELLED",t[t.UNKNOWN=2]="UNKNOWN",t[t.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",t[t.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",t[t.NOT_FOUND=5]="NOT_FOUND",t[t.ALREADY_EXISTS=6]="ALREADY_EXISTS",t[t.PERMISSION_DENIED=7]="PERMISSION_DENIED",t[t.UNAUTHENTICATED=16]="UNAUTHENTICATED",t[t.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",t[t.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",t[t.ABORTED=10]="ABORTED",t[t.OUT_OF_RANGE=11]="OUT_OF_RANGE",t[t.UNIMPLEMENTED=12]="UNIMPLEMENTED",t[t.INTERNAL=13]="INTERNAL",t[t.UNAVAILABLE=14]="UNAVAILABLE",t[t.DATA_LOSS=15]="DATA_LOSS"}(tn||(tn={}));var cn,hn=function(){function t(t){this.comparator=t,this.data=new ce(this.comparator)}return t.fromMapKeys=function(e){var n=new t(e.comparator);return e.forEach(function(t){n=n.add(t)}),n},t.prototype.has=function(t){return null!==this.data.get(t)},t.prototype.first=function(){return this.data.minKey()},t.prototype.last=function(){return this.data.maxKey()},Object.defineProperty(t.prototype,"size",{get:function(){return this.data.size},enumerable:!0,configurable:!0}),t.prototype.indexOf=function(t){return this.data.indexOf(t)},t.prototype.forEach=function(t){this.data.inorderTraversal(function(e,n){return t(e),!1})},t.prototype.forEachInRange=function(t,e){for(var n=this.data.getIteratorFrom(t[0]);n.hasNext();){var r=n.getNext();if(this.comparator(r.key,t[1])>=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=function(t){var e=this;return t.forEach(function(t){e=e.add(t)}),e},t.prototype.equals=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.getIterator(),r=e.data.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(0!==this.comparator(i,o))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){return t.push(e)}),"SortedSet("+t+")"},t.prototype.copy=function(e){var n=new t(this.comparator);return n.data=e,n},t}(),ln=new ce(ae.comparator),fn=new ce(ae.comparator),pn=new ce(ae.comparator),dn=new hn(ae.comparator),yn=function(){function t(t,e,n){this.snapshotVersion=t,this.targetChanges=e,this.documentUpdates=n}return t.prototype.addDocumentUpdate=function(t){this.documentUpdates=this.documentUpdates.insert(t.key,t)},t.prototype.handleExistenceFilterMismatch=function(t){this.targetChanges[t]={mapping:new vn,snapshotVersion:We.MIN,currentStatusUpdate:cn.MarkNotCurrent,resumeToken:h()}},t}();!function(t){t[t.None=0]="None",t[t.MarkNotCurrent=1]="MarkNotCurrent",t[t.MarkCurrent=2]="MarkCurrent"}(cn=cn||(cn={}));var mn,gn=et(),vn=function(){function t(){this.docs=gn}return Object.defineProperty(t.prototype,"documents",{get:function(){return this.docs},enumerable:!0,configurable:!0}),t.prototype.add=function(t){this.docs=this.docs.add(t)},t.prototype.delete=function(t){this.docs=this.docs.delete(t)},t.prototype.equals=function(t){return null!==t&&this.docs.equals(t.docs)},t}(),bn=function(){function t(){this.addedDocuments=gn,this.removedDocuments=gn}return t.prototype.applyToKeySet=function(t){var e=t;return this.addedDocuments.forEach(function(t){return e=e.add(t)}),this.removedDocuments.forEach(function(t){return e=e.delete(t)}),e},t.prototype.add=function(t){this.addedDocuments=this.addedDocuments.add(t),this.removedDocuments=this.removedDocuments.delete(t)},t.prototype.delete=function(t){this.addedDocuments=this.addedDocuments.delete(t),this.removedDocuments=this.removedDocuments.add(t)},t.prototype.equals=function(t){return null!==t&&this.addedDocuments.equals(t.addedDocuments)&&this.removedDocuments.equals(t.removedDocuments)},t}(),wn=function(){function t(t,e,n,r){this.updatedTargetIds=t,this.removedTargetIds=e,this.key=n,this.newDoc=r}return t}(),In=function(){function t(t,e){this.targetId=t,this.existenceFilter=e}return t}();!function(t){t[t.NoChange=0]="NoChange",t[t.Added=1]="Added",t[t.Removed=2]="Removed",t[t.Current=3]="Current",t[t.Reset=4]="Reset"}(mn=mn||(mn={}));var Tn=function(){function t(t,e,n,r){void 0===n&&(n=h()),void 0===r&&(r=null),this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r}return t}(),En=function(){function t(t,e,n){this.snapshotVersion=t,this.listenTargets=e,this.existenceFilters={},this.targetChanges={},this.documentUpdates=Z(),this.frozen=!1,this.pendingTargetResponses=g(n)}return t.prototype.add=function(t){c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t instanceof wn?this.addDocumentChange(t):t instanceof Tn?this.addTargetChange(t):t instanceof In?this.addExistenceFilterChange(t):u("Unknown watch change: "+t)},t.prototype.addChanges=function(t){var e=this;c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t.forEach(function(t){return e.add(t)})},t.prototype.createRemoteEvent=function(){var t=this,e=this.targetChanges;return d(this.targetChanges,function(n){t.isActiveTarget(n)||delete e[n]}),this.frozen=!0,new yn(this.snapshotVersion,e,this.documentUpdates)},t.prototype.ensureTargetChange=function(t){var e=this.targetChanges[t];return e||(e={currentStatusUpdate:cn.None,snapshotVersion:this.snapshotVersion,mapping:new bn,resumeToken:h()},this.targetChanges[t]=e),e},t.prototype.isActiveTarget=function(t){return!f(this.pendingTargetResponses,t)&&f(this.listenTargets,t)},t.prototype.addDocumentChange=function(t){for(var e=!1,n=0,r=t.updatedTargetIds;n<r.length;n++){var i=r[n];if(this.isActiveTarget(i)){var o=this.ensureTargetChange(i);o.mapping.add(t.key),e=!0}}for(var a=0,s=t.removedTargetIds;a<s.length;a++){var i=s[a];if(this.isActiveTarget(i)){var o=this.ensureTargetChange(i);o.mapping.delete(t.key),e=!0}}t.newDoc&&e&&(this.documentUpdates=this.documentUpdates.insert(t.key,t.newDoc))},t.prototype.addTargetChange=function(t){var e=this;t.targetIds.forEach(function(n){var r=e.ensureTargetChange(n);switch(t.state){case mn.NoChange:e.isActiveTarget(n)&&nt(r,t.resumeToken);break;case mn.Added:e.recordTargetResponse(n),f(e.pendingTargetResponses,n)||(r.mapping=new bn,r.currentStatusUpdate=cn.None,delete e.existenceFilters[n]),nt(r,t.resumeToken);break;case mn.Removed:e.recordTargetResponse(n),c(!t.cause,"WatchChangeAggregator does not handle errored targets");break;case mn.Current:e.isActiveTarget(n)&&(r.currentStatusUpdate=cn.MarkCurrent,nt(r,t.resumeToken));break;case mn.Reset:e.isActiveTarget(n)&&(r.mapping=new vn,nt(r,t.resumeToken));break;default:u("Unknown target watch change state: "+t.state)}})},t.prototype.recordTargetResponse=function(t){var e=(this.pendingTargetResponses[t]||0)-1;0===e?delete this.pendingTargetResponses[t]:this.pendingTargetResponses[t]=e},t.prototype.addExistenceFilterChange=function(t){this.isActiveTarget(t.targetId)&&(this.existenceFilters[t.targetId]=t.existenceFilter)},t}(),Sn=function(){var t={};return t[Fe.ASCENDING.name]="ASCENDING",t[Fe.DESCENDING.name]="DESCENDING",t}(),Nn=function(){var t={};return t[Le.LESS_THAN.name]="LESS_THAN",t[Le.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",t[Le.GREATER_THAN.name]="GREATER_THAN",t[Le.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",t[Le.EQUAL.name]="EQUAL",t}(),Cn=function(){function t(t,e){this.databaseId=t,this.options=e}return t.prototype.emptyByteString=function(){return this.options.useProto3Json?"":new Uint8Array(0)},t.prototype.unsafeCastProtoByteString=function(t){return t},t.prototype.fromRpcStatus=function(t){var e=void 0===t.code?Wt.UNKNOWN:X(t.code);return new Ht(e,t.message||"")},t.prototype.toTimestamp=function(t){return{seconds:t.seconds,nanos:t.nanos}},t.prototype.fromTimestamp=function(t){if("string"==typeof t)return Ge.fromISOString(t);c(!!t,"Cannot deserialize null or undefined timestamp.");var e=it(t.seconds||"0"),n=t.nanos||0;return new Ge(e,n)},t.prototype.toBytes=function(t){return this.options.useProto3Json?t.toBase64():this.unsafeCastProtoByteString(t.toUint8Array())},t.prototype.fromBlob=function(t){return"string"==typeof t?(c(this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Xt.fromBase64String(t)):(c(!this.options.useProto3Json,"Expected bytes to be passed in as string, but got something else instead."),Xt.fromUint8Array(t))},t.prototype.toVersion=function(t){return this.toTimestamp(t.toTimestamp())},t.prototype.fromVersion=function(t){return c(!!t,"Trying to deserialize version that isn't set"),We.fromTimestamp(this.fromTimestamp(t))},t.prototype.toResourceName=function(t,e){return this.fullyQualifiedPrefixPath(t).child("documents").child(e).canonicalString()},t.prototype.fromResourceName=function(t){var e=re.fromString(t);return c(this.isValidResourceName(e),"Tried to deserialize invalid key "+e),e},t.prototype.toName=function(t){return this.toResourceName(this.databaseId,t.path)},t.prototype.fromName=function(t){var e=this.fromResourceName(t);return c(e.get(1)===this.databaseId.projectId,"Tried to deserialize key from different project: "+e.get(1)+" vs "+this.databaseId.projectId),c(!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 ae(this.extractLocalPathFromResourceName(e))},t.prototype.toQueryPath=function(t){return 0===t.length?this.encodedDatabaseId:this.toResourceName(this.databaseId,t)},t.prototype.fromQueryPath=function(t){var e=this.fromResourceName(t);return 4===e.length?re.EMPTY_PATH:this.extractLocalPathFromResourceName(e)},Object.defineProperty(t.prototype,"encodedDatabaseId",{get:function(){return new re(["projects",this.databaseId.projectId,"databases",this.databaseId.database]).canonicalString()},enumerable:!0,configurable:!0}),t.prototype.fullyQualifiedPrefixPath=function(t){return new re(["projects",t.projectId,"databases",t.database])},t.prototype.extractLocalPathFromResourceName=function(t){return c(t.length>4&&"documents"===t.get(4),"tried to deserialize invalid key "+t),t.popFirst(5)},t.prototype.isValidResourceName=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.toValue=function(t){if(t instanceof ge)return{nullValue:"NULL_VALUE"};if(t instanceof ve)return{booleanValue:t.value()};if(t instanceof we)return{integerValue:""+t.value()};if(t instanceof Ie){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 Te?{stringValue:t.value()}:t instanceof Ae?{mapValue:this.toMapValue(t)}:t instanceof ke?{arrayValue:this.toArrayValue(t)}:t instanceof Ee?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof De?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof Ne?{bytesValue:this.toBytes(t.value())}:t instanceof Ce?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:u("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this,n=t.value_type;if(ot(t,n,"nullValue"))return ge.INSTANCE;if(ot(t,n,"booleanValue"))return ve.of(t.booleanValue);if(ot(t,n,"integerValue"))return new we(it(t.integerValue));if(ot(t,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return Ie.NAN;if("Infinity"===t.doubleValue)return Ie.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return Ie.NEGATIVE_INFINITY}return new Ie(t.doubleValue)}if(ot(t,n,"stringValue"))return new Te(t.stringValue);if(ot(t,n,"mapValue"))return this.fromFields(t.mapValue.fields||{});if(ot(t,n,"arrayValue")){rt(t.arrayValue,"arrayValue");var r=t.arrayValue.values||[];return new ke(r.map(function(t){return e.fromValue(t)}))}if(ot(t,n,"timestampValue"))return rt(t.timestampValue,"timestampValue"),new Ee(this.fromTimestamp(t.timestampValue));if(ot(t,n,"geoPointValue")){rt(t.geoPointValue,"geoPointValue");var i=t.geoPointValue.latitude||0,o=t.geoPointValue.longitude||0;return new De(new Jt(i,o))}if(ot(t,n,"bytesValue")){rt(t.bytesValue,"bytesValue");var a=this.fromBlob(t.bytesValue);return new Ne(a)}if(ot(t,n,"referenceValue")){rt(t.referenceValue,"referenceValue");var s=this.fromResourceName(t.referenceValue),c=new te(s.get(1),s.get(3)),h=new ae(this.extractLocalPathFromResourceName(s));return new Ce(c,h)}return u("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return c(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t){return new se(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasLocalMutations:!1})},t.prototype.toFields=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.toValue(r)}),n},t.prototype.fromFields=function(t){var e=this,n=t,r=Ae.EMPTY;return y(n,function(t,n){r=r.set(new oe([t]),e.fromValue(n))}),r},t.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},t.prototype.fromFound=function(t){c(!!t.found,"Tried to deserialize a found document from a missing document."),rt(t.found.name,"doc.found.name"),rt(t.found.updateTime,"doc.found.updateTime");var e=this.fromName(t.found.name),n=this.fromVersion(t.found.updateTime),r=this.fromFields(t.found.fields||{});return new se(e,n,r,{hasLocalMutations:!1})},t.prototype.fromMissing=function(t){c(!!t.missing,"Tried to deserialize a missing document from a found document."),c(!!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 ue(e,n)},t.prototype.fromMaybeDocument=function(t){var e=t.result_type;return ot(t,e,"found")?this.fromFound(t):ot(t,e,"missing")?this.fromMissing(t):u("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case mn.Added:return"ADD";case mn.Current:return"CURRENT";case mn.NoChange:return"NO_CHANGE";case mn.Removed:return"REMOVE";case mn.Reset:return"RESET";default:return u("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof In)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof wn){if(t.newDoc instanceof se){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 ue){var e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof Tn){var n=void 0;return t.cause&&(n={code:Y(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return u("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=t.change_type;if(ot(t,n,"targetChange")){rt(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 Tn(r,i,o,s||null)}else if(ot(t,n,"documentChange")){rt(t.documentChange,"documentChange"),rt(t.documentChange.document,"documentChange.name"),rt(t.documentChange.document.name,"documentChange.document.name"),rt(t.documentChange.document.updateTime,"documentChange.document.updateTime");var c=t.documentChange,h=this.fromName(c.document.name),l=this.fromVersion(c.document.updateTime),f=this.fromFields(c.document.fields||{}),p=new se(h,l,f,{hasLocalMutations:!1}),d=c.targetIds||[],y=c.removedTargetIds||[];e=new wn(d,y,p.key,p)}else if(ot(t,n,"documentDelete")){rt(t.documentDelete,"documentDelete"),rt(t.documentDelete.document,"documentDelete.document");var m=t.documentDelete,h=this.fromName(m.document),l=m.readTime?this.fromVersion(m.readTime):We.forDeletedDoc(),p=new ue(h,l),y=m.removedTargetIds||[];e=new wn([],y,p.key,p)}else if(ot(t,n,"documentRemove")){rt(t.documentRemove,"documentRemove"),rt(t.documentRemove.document,"documentRemove");var g=t.documentRemove,h=this.fromName(g.document),y=g.removedTargetIds||[];e=new wn([],y,h,null)}else{if(!ot(t,n,"filter"))return u("Unknown change type "+JSON.stringify(t));rt(t.filter,"filter"),rt(t.filter.targetId,"filter.targetId");var v=t.filter,b=v.count||0,w=new un(b),I=v.targetId;e=new In(I,w)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?mn.NoChange:"ADD"===t?mn.Added:"REMOVE"===t?mn.Removed:"CURRENT"===t?mn.Current:"RESET"===t?mn.Reset:u("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!ot(t,t.response_type,"targetChange"))return We.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?We.MIN:e.readTime?this.fromVersion(e.readTime):We.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof rn)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof sn)e={delete:this.toName(t.key)};else if(t instanceof on)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof an))return u("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map(function(t){return n.toFieldTransform(t)})}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):en.NONE;if(t.update){rt(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 on(r,i,o,n)}return new rn(r,i,n)}if(t.delete){var r=this.fromName(t.delete);return new sn(r,n)}if(t.transform){var r=this.fromName(t.transform.document),a=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return c(!0===n.exists,'Transforms only support precondition "exists == true"'),new an(r,a)}return u("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return c(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:u("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?en.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?en.exists(t.exists):en.NONE},t.prototype.fromWriteResult=function(t){var e=this,n=t.updateTime?this.fromVersion(t.updateTime):null,r=null;return t.transformResults&&(r=t.transformResults.map(function(t){return e.fromValue(t)})),new $e(n,r)},t.prototype.fromWriteResults=function(t){var e=this;return(t||[]).map(function(t){return e.fromWriteResult(t)})},t.prototype.toFieldTransform=function(t){return c(t.transform instanceof Je,"Unknown transform: "+t.transform),{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"}},t.prototype.fromFieldTransform=function(t){c("REQUEST_TIME"===t.setToServerValue,"Unknown transform proto: "+JSON.stringify(t));var e=oe.fromServerFormat(t.fieldPath);return new Ze(e,Je.instance)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;c(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return Pe.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}};if(t.path.isEmpty())e.parent=this.toQueryPath(re.EMPTY_PATH);else{var n=t.path;c(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.toLimit(t.limit);return void 0!==o&&(e.structuredQuery.limit=o),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0;if(r>0){c(1===r,"StructuredQuery.from with more than one collection is not supported.");var i=n.from[0];e=e.child(i.collectionId)}var o=[];n.where&&(o=this.fromFilter(n.where));var a=[];n.orderBy&&(a=this.fromOrder(n.orderBy));var s=null;n.limit&&(s=n.limit);var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var h=null;return n.endAt&&(h=this.fromCursor(n.endAt)),new Pe(e,a,o,s,u,h)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case ye.Listen:return null;case ye.ExistenceFilterMismatch:return"existence-filter-mismatch";case ye.LimboResolution:return"limbo-document";default:return u("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)},e.targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(t){return t instanceof xe?e.toRelationFilter(t):e.toUnaryFilter(t)});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromRelationFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):u("Unknown filter: "+JSON.stringify(t)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},t.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},t.prototype.toLimit=function(t){if(!Q(t))return t},t.prototype.toCursor=function(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},t.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new Ve(r,n)},t.prototype.toDirection=function(t){return Sn[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return Fe.ASCENDING;case"DESCENDING":return Fe.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return Nn[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return Le.EQUAL;case"GREATER_THAN":return Le.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return Le.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return Le.LESS_THAN;case"LESS_THAN_OR_EQUAL":return Le.LESS_THAN_OR_EQUAL;case"OPERATOR_UNSPECIFIED":return u("Unspecified relation");default:return u("Unknown relation")}},t.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return oe.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new qe(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.toRelationFilter=function(t){return t instanceof xe?{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromRelationFilter=function(t){return new xe(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},t.prototype.toUnaryFilter=function(t){return t instanceof Ue?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}}:t instanceof Be?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return new Ue(e);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return new Be(n);case"OPERATOR_UNSPECIFIED":return u("Unspecified filter");default:return u("Unknown filter")}},t.prototype.toDocumentMask=function(t){return{fieldPaths:t.fields.map(function(t){return t.canonicalString()})}},t.prototype.fromDocumentMask=function(t){var e=t.fieldPaths||[],n=e.map(function(t){return oe.fromServerFormat(t)});return new Ye(n)},t}(),Dn=n(115),An=function(){function t(t){this.wrappedOnOpen=null,this.wrappedOnClose=null,this.wrappedOnMessage=null,this.sendFn=t.sendFn,this.closeFn=t.closeFn}return t.prototype.onOpen=function(t){c(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},t.prototype.onClose=function(t){c(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},t.prototype.onMessage=function(t){c(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},t.prototype.close=function(){this.closeFn()},t.prototype.send=function(t){this.sendFn(t)},t.prototype.callOnOpen=function(){c(null!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},t.prototype.callOnClose=function(t){c(null!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},t.prototype.callOnMessage=function(t){c(null!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},t}(),kn="Connection",Rn="gl-js/ fire/"+jt,On=function(){function t(t){this.databaseId=t.databaseId,this.pool=new Dn.XhrIoPool;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host}return t.prototype.modifyHeadersForRequest=function(t,e){if(e)for(var n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n]);t["X-Goog-Api-Client"]=Rn,t["google-cloud-resource-prefix"]="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},t.prototype.invoke=function(t,e,n){var r=this,i=this.makeUrl(t);return new Promise(function(s,c){r.pool.getObject(function(h){h.listenOnce(Dn.EventType.COMPLETE,function(){try{switch(h.getLastErrorCode()){case Dn.ErrorCode.NO_ERROR:var e=h.getResponseJson();o(kn,"XHR received:",JSON.stringify(e)),s(e);break;case Dn.ErrorCode.TIMEOUT:a('RPC "'+t+'" timed out, retrying.'),c(new Ht(Wt.DEADLINE_EXCEEDED,"Request time out"));break;case Dn.ErrorCode.HTTP_ERROR:var n=h.getStatus();a('RPC "'+t+'" failed with status:',n,"response text:",h.getResponseText()),n>0?c(new Ht(J(n),"Server responded with status "+h.getStatusText())):(a(kn,'RPC "'+t+'" failed, retrying.'),c(new Ht(Wt.UNAVAILABLE,"Connection failed.")));break;default:u('RPC "'+t+'" failed with unanticipated webchannel error '+h.getLastErrorCode()+": "+h.getLastError()+", giving up.")}}finally{o(kn,'RPC "'+t+'" completed.'),r.pool.releaseObject(h)}});var l=JSON.stringify(e);o(kn,"XHR sending: ",i+" "+l);var f={"Content-Type":"text/plain"};r.modifyHeadersForRequest(f,n),h.send(i,"POST",l,f,15)})})},t.prototype.openStream=function(e,n){var r=t.RPC_STREAM_SERVICE_MAPPING[e],i=t.RPC_STREAM_NAME_MAPPING[e];r&&i||u("Unknown RPC name: "+e);var a=[this.baseUrl,"/",r,"/",i,"/channel"],s=Object(Dn.createWebChannelTransport)(),h={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(h.initMessageHeaders,n);var l=a.join("");o(kn,"Creating WebChannel: "+l+" "+h);var f=s.createWebChannel(l,h),p=!1,d=!1,y=new An({sendFn:function(t){d?o(kn,"Not sending because WebChannel is closed:",t):(p||(o(kn,"Opening WebChannel transport."),f.open(),p=!0),o(kn,"WebChannel sending:",t),f.send(t))},closeFn:function(){return f.close()}}),m=function(t,e){f.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})};return m(Dn.WebChannel.EventType.OPEN,function(){d||o(kn,"WebChannel transport opened.")}),m(Dn.WebChannel.EventType.CLOSE,function(){d||(d=!0,o(kn,"WebChannel transport closed"),y.callOnClose())}),m(Dn.WebChannel.EventType.ERROR,function(t){d||(d=!0,o(kn,"WebChannel transport errored:",t),y.callOnClose(new Ht(Wt.UNAVAILABLE,"The operation could not be completed")))}),m(Dn.WebChannel.EventType.MESSAGE,function(t){if(!d){var e=t.data[0];c(!!e,"Got a webchannel message without data.");var n=e.error||e[0]&&e[0].error;if(n){o(kn,"WebChannel received error:",n);var r=n.status,i=z(r),a=n.message;void 0===i&&(i=Wt.INTERNAL,a="Unknown error status: "+r+" with message "+n.message),d=!0,y.callOnClose(new Ht(i,a)),f.close()}else o(kn,"WebChannel received:",e),y.callOnMessage(e)}}),setTimeout(function(){y.callOnOpen()},0),y},t.prototype.makeUrl=function(t){var e=[this.baseUrl,"/","v1beta1"];return e.push("/projects/"),e.push(this.databaseId.projectId),e.push("/databases/"),e.push(this.databaseId.database),e.push("/documents"),e.push(":"),e.push(t),e.join("")},t.RPC_STREAM_SERVICE_MAPPING={Write:"google.firestore.v1beta1.Firestore",Listen:"google.firestore.v1beta1.Firestore"},t.RPC_STREAM_NAME_MAPPING={Write:"Write",Listen:"Listen"},t}(),Mn=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return t.prototype.loadConnection=function(t){return Promise.resolve(new On(t))},t.prototype.newSerializer=function(t){return new Cn(t,{useProto3Json:!0})},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();Qt.setPlatform(new Mn);var _n,Pn=function(){function t(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];I("FieldPath",t,"fieldNames",1);for(var n=0;n<t.length;++n)if(T("FieldPath","string",n,t[n]),0===t[n].length)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this.t=new oe(t)}return t.documentId=function(){return t.y},t.y=new t(oe.keyField().canonicalString()),t}(),Ln=RegExp("[~\\*/\\[\\]]");!function(t){t[t.Unknown=0]="Unknown",t[t.Healthy=1]="Healthy",t[t.Failed=2]="Failed"}(_n=_n||(_n={}));var xn;!function(t){t[t.Added=0]="Added",t[t.Removed=1]="Removed",t[t.Modified=2]="Modified",t[t.Metadata=3]="Metadata"}(xn=xn||(xn={}));var Bn;!function(t){t[t.Local=0]="Local",t[t.Synced=1]="Synced"}(Bn=Bn||(Bn={}));var Un,Fn=function(){function t(){this.changeMap=new ce(ae.comparator)}return t.prototype.track=function(t){var e=t.doc.key,n=this.changeMap.get(e);if(!n)return void(this.changeMap=this.changeMap.insert(e,t));t.type!==xn.Added&&n.type===xn.Metadata?this.changeMap=this.changeMap.insert(e,t):t.type===xn.Metadata&&n.type!==xn.Removed?this.changeMap=this.changeMap.insert(e,{type:n.type,doc:t.doc}):t.type===xn.Modified&&n.type===xn.Modified?this.changeMap=this.changeMap.insert(e,{type:xn.Modified,doc:t.doc}):t.type===xn.Modified&&n.type===xn.Added?this.changeMap=this.changeMap.insert(e,{type:xn.Added,doc:t.doc}):t.type===xn.Removed&&n.type===xn.Added?this.changeMap=this.changeMap.remove(e):t.type===xn.Removed&&n.type===xn.Modified?this.changeMap=this.changeMap.insert(e,{type:xn.Removed,doc:n.doc}):t.type===xn.Added&&n.type===xn.Removed?this.changeMap=this.changeMap.insert(e,{type:xn.Modified,doc:t.doc}):u("unsupported combination of changes: "+JSON.stringify(t)+" after "+JSON.stringify(n))},t.prototype.getChanges=function(){var t=[];return this.changeMap.inorderTraversal(function(e,n){t.push(n)}),t},t}(),Vn=function(){function t(t){this.comparator=t?function(e,n){return t(e,n)||ae.comparator(e.key,n.key)}:function(t,e){return ae.comparator(t.key,e.key)},this.keyedMap=$(),this.sortedSet=new ce(this.comparator)}return t.emptySet=function(e){return new t(e.comparator)},t.prototype.has=function(t){return null!=this.keyedMap.get(t)},t.prototype.get=function(t){return this.keyedMap.get(t)},t.prototype.first=function(){return this.sortedSet.minKey()},t.prototype.last=function(){return this.sortedSet.maxKey()},t.prototype.isEmpty=function(){return this.sortedSet.isEmpty()},t.prototype.prevDoc=function(t){c(this.has(t),"Trying to get a previous document to non-existing key: "+t);var e=this.keyedMap.get(t);return this.sortedSet.getPredecessorKey(e)},t.prototype.indexOf=function(t){var e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1},Object.defineProperty(t.prototype,"size",{get:function(){return this.sortedSet.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t){this.sortedSet.inorderTraversal(function(e,n){return t(e),!1})},t.prototype.add=function(t){var e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))},t.prototype.delete=function(t){var e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this},t.prototype.equals=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(!i.equals(o))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){t.push(""+e)}),0===t.length?"DocumentSet ()":"DocumentSet (\n  "+t.join("  \n")+"\n)"},t.prototype.copy=function(e,n){var r=new t;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=n,r},t}(),qn=function(){function t(t){this.mapKeyFn=t,this.inner={}}return t.prototype.get=function(t){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0!==n)for(var r=0,i=n;r<i.length;r++){var o=i[r],a=o[0],s=o[1];if(a.equals(t))return s}},t.prototype.has=function(t){return void 0!==this.get(t)},t.prototype.set=function(t,e){var n=this.mapKeyFn(t),r=this.inner[n];if(void 0===r)return void(this.inner[n]=[[t,e]]);for(var i=0;i<r.length;i++)if(r[i][0].equals(t))return void(r[i]=[t,e]);r.push([t,e])},t.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].equals(t))return 1===n.length?delete this.inner[e]:n.splice(r,1),!0;return!1},t.prototype.forEach=function(t){y(this.inner,function(e,n){for(var r=0,i=n;r<i.length;r++){var o=i[r],a=o[0],s=o[1];t(a,s)}})},t.prototype.isEmpty=function(){return m(this.inner)},t}(),jn=function(){function t(){this.listeners=[]}return t}(),Kn=function(){function t(t){this.syncEngine=t,this.queries=new qn(function(t){return t.canonicalId()}),this.onlineState=_n.Unknown,this.syncEngine.subscribe(this.onChange.bind(this),this.onError.bind(this))}return t.prototype.listen=function(t){var e=t.query,n=!1,r=this.queries.get(e);return r||(n=!0,r=new jn,this.queries.set(e,r)),r.listeners.push(t),t.onOnlineStateChanged(this.onlineState),r.viewSnap&&t.onViewSnapshot(r.viewSnap),n?this.syncEngine.listen(e).then(function(t){return r.targetId=t,t}):Promise.resolve(r.targetId)},t.prototype.unlisten=function(t){var e=t.query,n=!1,r=this.queries.get(e);if(r){var i=r.listeners.indexOf(t);i>=0&&(r.listeners.splice(i,1),n=0===r.listeners.length)}return n?(this.queries.delete(e),this.syncEngine.unlisten(e)):Promise.resolve()},t.prototype.onChange=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}}},t.prototype.onError=function(t,e){var n=this.queries.get(t);if(n)for(var r=0,i=n.listeners;r<i.length;r++){var o=i[r];o.onError(e)}this.queries.delete(t)},t.prototype.onOnlineStateChanged=function(t){this.onlineState=t,this.queries.forEach(function(e,n){for(var r=0,i=n.listeners;r<i.length;r++)i[r].onOnlineStateChanged(t)})},t}(),Qn=function(){function t(t,e,n){this.query=t,this.queryObserver=e,this.raisedInitialEvent=!1,this.onlineState=_n.Unknown,this.options=n||{}}return t.prototype.onViewSnapshot=function(t){if(c(t.docChanges.length>0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeDocumentMetadataChanges){for(var e=[],n=0,r=t.docChanges;n<r.length;n++){var i=r[n];i.type!==xn.Metadata&&e.push(i)}t={query:t.query,docs:t.docs,oldDocs:t.oldDocs,docChanges:e,fromCache:t.fromCache,hasPendingWrites:t.hasPendingWrites,syncStateChanged:t.syncStateChanged}}this.raisedInitialEvent?this.shouldRaiseEvent(t)&&this.queryObserver.next(t):this.shouldRaiseInitialEvent(t,this.onlineState)&&this.raiseInitialEvent(t),this.snap=t},t.prototype.onError=function(t){this.queryObserver.error(t)},t.prototype.onOnlineStateChanged=function(t){this.onlineState=t,this.snap&&!this.raisedInitialEvent&&this.shouldRaiseInitialEvent(this.snap,t)&&this.raiseInitialEvent(this.snap)},t.prototype.shouldRaiseInitialEvent=function(t,e){if(c(!this.raisedInitialEvent,"Determining whether to raise first event but already had first event"),!t.fromCache)return!0;var n=e!==_n.Failed;return this.options.waitForSyncWhenOnline&&n?(c(t.fromCache,"Waiting for sync, but snapshot is not from cache"),!1):!t.docs.isEmpty()||e===_n.Failed},t.prototype.shouldRaiseEvent=function(t){if(t.docChanges.length>0)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeQueryMetadataChanges},t.prototype.raiseInitialEvent=function(e){c(!this.raisedInitialEvent,"Trying to raise initial events for second time"),e={query:e.query,docs:e.docs,oldDocs:Vn.emptySet(e.docs),docChanges:t.getInitialViewChanges(e),fromCache:e.fromCache,hasPendingWrites:e.hasPendingWrites,syncStateChanged:!0},this.raisedInitialEvent=!0,this.queryObserver.next(e)},t.getInitialViewChanges=function(t){var e=[];return t.docs.forEach(function(t){e.push({type:xn.Added,doc:t})}),e},t}(),Gn=function(){function t(t){var e=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=null,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)})}return t.prototype.catch=function(t){return this.next(void 0,t)},t.prototype.next=function(e,n){var r=this;return this.callbackAttached&&u("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(e,this.result):new t(function(t,i){r.nextCallback=function(n){r.wrapSuccess(e,n).next(t,i)},r.catchCallback=function(e){r.wrapFailure(n,e).next(t,i)}})},t.prototype.toPromise=function(){var t=this;return new Promise(function(e,n){t.next(e,n)})},t.prototype.wrapUserFunction=function(e){try{var n=e();return n instanceof t?n:t.resolve(n)}catch(e){return t.reject(e)}},t.prototype.wrapSuccess=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.resolve(n)},t.prototype.wrapFailure=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.reject(n)},t.resolve=function(e){return new t(function(t,n){t(e)})},t.reject=function(e){return new t(function(t,n){n(e)})},t.waitFor=function(e){return e.reduce(function(t,e,n){return t.next(function(){return e})},t.resolve())},t.map=function(e){var n=[],r=!0,i=t.resolve(null);return e.reduce(function(t,e){return t.next(function(t){return r||n.push(t),r=!1,e})},i).next(function(t){return n.push(t),n})},t}(),Wn=function(){function t(){this.isEager=!0,this.sources=[],this.potentialGarbage=et()}return t.prototype.addGarbageSource=function(t){this.sources.push(t),t.setGarbageCollector(this)},t.prototype.removeGarbageSource=function(t){this.sources.splice(this.sources.indexOf(t),1),t.setGarbageCollector(null)},t.prototype.addPotentialGarbageKey=function(t){this.potentialGarbage=this.potentialGarbage.add(t)},t.prototype.collectGarbage=function(t){var e=this,n=[],r=et();return this.potentialGarbage.forEach(function(i){var o=e.documentHasAnyReferences(t,i);n.push(o.next(function(t){return t||(r=r.add(i)),Gn.resolve()}))}),this.potentialGarbage=et(),Gn.waitFor(n).next(function(){return r})},t.prototype.documentHasAnyReferences=function(t,e){var n=Gn.resolve(!1);return this.sources.map(function(n){return function(){return n.containsKey(t,e)}}).reduce(function(t,e){return t.next(function(t){return t?Gn.resolve(!0):e()})},n)},t}(),Hn=function(){function t(t,e,n){this.query=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e){for(var n=et(),r=et(),i=0,o=e.docChanges;i<o.length;i++){var a=o[i];switch(a.type){case xn.Added:n=n.add(a.doc.key);break;case xn.Removed:r=r.add(a.doc.key)}}return new t(e.query,n,r)},t}(),zn=function(){function t(){this.refsByKey=new hn(Xn.compareByKey),this.refsByTarget=new hn(Xn.compareByTargetId),this.garbageCollector=null}return t.prototype.isEmpty=function(){return this.refsByKey.isEmpty()},t.prototype.addReference=function(t,e){var n=new Xn(t,e);this.refsByKey=this.refsByKey.add(n),this.refsByTarget=this.refsByTarget.add(n)},t.prototype.addReferences=function(t,e){var n=this;t.forEach(function(t){return n.addReference(t,e)})},t.prototype.removeReference=function(t,e){this.removeRef(new Xn(t,e))},t.prototype.removeReferences=function(t,e){var n=this;t.forEach(function(t){return n.removeReference(t,e)})},t.prototype.removeReferencesForId=function(t){var e=this,n=ae.EMPTY,r=new Xn(n,t),i=new Xn(n,t+1);this.refsByTarget.forEachInRange([r,i],function(t){e.removeRef(t)})},t.prototype.removeAllReferences=function(){var t=this;this.refsByKey.forEach(function(e){return t.removeRef(e)})},t.prototype.removeRef=function(t){this.refsByKey=this.refsByKey.delete(t),this.refsByTarget=this.refsByTarget.delete(t),null!==this.garbageCollector&&this.garbageCollector.addPotentialGarbageKey(t.key)},t.prototype.referencesForId=function(t){var e=ae.EMPTY,n=new Xn(e,t),r=new Xn(e,t+1),i=et();return this.refsByTarget.forEachInRange([n,r],function(t){i=i.add(t.key)}),i},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){var n=new Xn(e,0),r=this.refsByKey.firstAfterOrEqual(n);return Gn.resolve(null!==r&&e.equals(r.key))},t}(),Xn=function(){function t(t,e){this.key=t,this.targetOrBatchId=e}return t.compareByKey=function(t,e){return ae.comparator(t.key,e.key)||L(t.targetOrBatchId,e.targetOrBatchId)},t.compareByTargetId=function(t,e){return L(t.targetOrBatchId,e.targetOrBatchId)||ae.comparator(t.key,e.key)},t}(),Yn=1;!function(t){t[t.LocalStore=0]="LocalStore",t[t.SyncEngine=1]="SyncEngine"}(Un||(Un={}));var Jn,Zn=function(){function t(t,e){void 0===e&&(e=0),this.generatorId=t;var n=e>>Yn<<Yn,r=e-n;this.previousId=r>=t?n|this.generatorId:(n|this.generatorId)-(1<<Yn)}return t.prototype.next=function(){return this.previousId+=1<<Yn,this.previousId},t.forLocalStore=function(e){return void 0===e&&(e=0),new t(Un.LocalStore,e)},t.forSyncEngine=function(){return new t(Un.SyncEngine)},t}(),$n=function(){function t(t){this.key=t}return t}(),tr=function(){function t(t){this.key=t}return t}(),er=function(){function t(t,e){this.query=t,this.syncedDocuments=e,this.syncState=null,this.current=!1,this.limboDocuments=et(),this.mutatedKeys=et(),this.documentSet=new Vn(t.docComparator.bind(t))}return t.prototype.computeDocChanges=function(t,e){var n=this,r=e?e.changeSet:new Fn,i=e?e.documentSet:this.documentSet,o=e?e.mutatedKeys:this.mutatedKeys,a=i,s=!1,u=this.query.hasLimit()&&i.size===this.query.limit?i.last():null;if(t.inorderTraversal(function(t,e){var h=i.get(t),l=e instanceof se?e:null;if(l&&(c(t.equals(l.key),"Mismatching keys found in document changes: "+t+" != "+l.key),l=n.query.matches(l)?l:null),l?(a=a.add(l),o=l.hasLocalMutations?o.add(t):o.delete(t)):(a=a.delete(t),o=o.delete(t)),h&&l){var f=h.data.equals(l.data);f&&h.hasLocalMutations===l.hasLocalMutations||(f?r.track({type:xn.Metadata,doc:l}):r.track({type:xn.Modified,doc:l}),u&&n.query.docComparator(l,u)>0&&(s=!0))}else!h&&l?r.track({type:xn.Added,doc:l}):h&&!l&&(r.track({type:xn.Removed,doc:h}),u&&(s=!0))}),this.query.hasLimit())for(;a.size>this.query.limit;){var h=a.last();a=a.delete(h.key),r.track({type:xn.Removed,doc:h})}return c(!s||!e,"View was refilled using docs that themselves needed refilling."),{documentSet:a,changeSet:r,needsRefill:s,mutatedKeys:o}},t.prototype.applyChanges=function(t,e){var n=this;c(!t.needsRefill,"Cannot apply changes that need a refill");var r=this.documentSet;this.documentSet=t.documentSet,this.mutatedKeys=t.mutatedKeys;var i=t.changeSet.getChanges();i.sort(function(t,e){return st(t.type,e.type)||n.query.docComparator(t.doc,e.doc)});var o=this.applyTargetChange(e),a=0===this.limboDocuments.size&&this.current,s=a?Bn.Synced:Bn.Local,u=s!==this.syncState;return this.syncState=s,0!==i.length||u?{snapshot:{query:this.query,docs:t.documentSet,oldDocs:r,docChanges:i,fromCache:s===Bn.Local,syncStateChanged:u,hasPendingWrites:!t.mutatedKeys.isEmpty()},limboChanges:o}:{limboChanges:o}},t.prototype.shouldBeInLimbo=function(t){return!this.syncedDocuments.has(t)&&!!this.documentSet.has(t)&&!this.documentSet.get(t).hasLocalMutations},t.prototype.applyTargetChange=function(t){var e=this;if(t){var n=t.mapping;switch(n instanceof vn?this.syncedDocuments=n.documents:n instanceof bn&&(this.syncedDocuments=n.applyToKeySet(this.syncedDocuments)),t.currentStatusUpdate){case cn.MarkCurrent:this.current=!0;break;case cn.MarkNotCurrent:this.current=!1;break;case cn.None:break;default:u("Unknown current status update: "+t.currentStatusUpdate)}}var r=this.limboDocuments;this.limboDocuments=et(),this.current&&this.documentSet.forEach(function(t){e.shouldBeInLimbo(t.key)&&(e.limboDocuments=e.limboDocuments.add(t.key))});var i=[];return r.forEach(function(t){e.limboDocuments.has(t)||i.push(new tr(t))}),this.limboDocuments.forEach(function(t){r.has(t)||i.push(new $n(t))}),i},t}(),nr=function(){function t(t,e,n,r){this.query=t,this.targetId=e,this.resumeToken=n,this.view=r}return t}(),rr=function(){function t(t,e,n){this.localStore=t,this.remoteStore=e,this.currentUser=n,this.viewHandler=null,this.errorHandler=null,this.queryViewsByQuery=new qn(function(t){return t.canonicalId()}),this.queryViewsByTarget={},this.limboTargetsByKey=new ce(ae.comparator),this.limboKeysByTarget={},this.limboDocumentRefs=new zn,this.limboCollector=new Wn,this.mutationUserCallbacks={},this.targetIdGenerator=Zn.forSyncEngine()}return t.prototype.subscribe=function(t,e){c(null!==t&&null!==e,"View and error handlers cannot be null"),c(null===this.viewHandler&&null===this.errorHandler,"SyncEngine already has a subscriber."),this.viewHandler=t,this.errorHandler=e,this.limboCollector.addGarbageSource(this.limboDocumentRefs)},t.prototype.listen=function(t){var e=this;return this.assertSubscribed("listen()"),c(!this.queryViewsByQuery.has(t),"We already listen to the query: "+t),this.localStore.allocateQuery(t).then(function(n){return e.localStore.executeQuery(t).then(function(r){return e.localStore.remoteDocumentKeys(n.targetId).then(function(i){var o=new er(t,i),a=o.computeDocChanges(r),s=o.applyChanges(a);c(0===s.limboChanges.length,"View returned limbo docs before target ack from the server."),c(!!s.snapshot,"applyChanges for new view should always return a snapshot");var u=new nr(t,n.targetId,n.resumeToken,o);e.queryViewsByQuery.set(t,u),e.queryViewsByTarget[n.targetId]=u,e.viewHandler([s.snapshot]),e.remoteStore.listen(n)})}).then(function(){return n.targetId})})},t.prototype.unlisten=function(t){var e=this;this.assertSubscribed("unlisten()");var n=this.queryViewsByQuery.get(t);return c(!!n,"Trying to unlisten on query not found:"+t),this.localStore.releaseQuery(t).then(function(){return e.remoteStore.unlisten(n.targetId),e.removeAndCleanupQuery(n).then(function(){return e.localStore.collectGarbage()})})},t.prototype.write=function(t,e){var n=this;return this.assertSubscribed("write()"),this.localStore.localWrite(t).then(function(t){return n.addMutationCallback(t.batchId,e),n.emitNewSnapsAndNotifyLocalStore(t.changes)}).then(function(){return n.remoteStore.fillWritePipeline()})},t.prototype.wrapUpdateFunctionError=function(t){return t},t.prototype.runTransaction=function(t,e){var n=this;void 0===e&&(e=5),c(e>=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!Q(e)&&e.catch&&e.then?e.catch(function(t){return Promise.reject(n.wrapUpdateFunctionError(t))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(t){return Promise.reject(n.wrapUpdateFunctionError(t))}}().then(function(i){return r.commit().then(function(){return i}).catch(function(r){return 0===e?Promise.reject(r):n.runTransaction(t,e-1)})})},t.prototype.applyRemoteEvent=function(t){var e=this;return this.assertSubscribed("applyRemoteEvent()"),d(t.targetChanges,function(n,r){var i=e.limboKeysByTarget[n];i&&r.currentStatusUpdate===cn.MarkCurrent&&!t.documentUpdates.get(i)&&t.addDocumentUpdate(new ue(i,t.snapshotVersion))}),this.localStore.applyRemoteEvent(t).then(function(n){return e.emitNewSnapsAndNotifyLocalStore(n,t)})},t.prototype.rejectListen=function(t,e){var n=this;this.assertSubscribed("rejectListens()");var r=this.limboKeysByTarget[t];if(r){this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboKeysByTarget[t];var i=new ce(ae.comparator);i=i.insert(r,new ue(r,We.forDeletedDoc()));var o=new yn(We.MIN,{},i);return this.applyRemoteEvent(o)}var a=this.queryViewsByTarget[t];return c(!!a,"Unknown targetId: "+t),this.localStore.releaseQuery(a.query).then(function(){return n.removeAndCleanupQuery(a).then(function(){n.errorHandler(a.query,e)})})},t.prototype.applySuccessfulWrite=function(t){var e=this;return this.assertSubscribed("applySuccessfulWrite()"),this.processUserCallback(t.batch.batchId,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(t){return n.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new ce(L)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(c(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){return this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.limboDocumentRefs.removeReferencesForId(t.targetId),this.gcLimboDocuments()},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n<r.length;n++){var i=r[n];i instanceof $n?(this.limboDocumentRefs.addReference(i.key,t),this.trackLimboChange(i)):i instanceof tr?(o("SyncEngine","Document no longer in limbo: "+i.key),this.limboDocumentRefs.removeReference(i.key,t)):u("Unknown limbo change: "+JSON.stringify(i))}return this.gcLimboDocuments()},t.prototype.trackLimboChange=function(t){var e=t.key;if(!this.limboTargetsByKey.get(e)){o("SyncEngine","New document in limbo: "+e);var n=this.targetIdGenerator.next(),r=Pe.atPath(e.path);this.limboKeysByTarget[n]=e,this.remoteStore.listen(new ze(r,n,ye.Listen)),this.limboTargetsByKey=this.limboTargetsByKey.insert(e,n)}},t.prototype.gcLimboDocuments=function(){var t=this;return this.limboCollector.collectGarbage(null).next(function(e){e.forEach(function(e){var n=t.limboTargetsByKey.get(e);null!==n&&(t.remoteStore.unlisten(n),t.limboTargetsByKey=t.limboTargetsByKey.remove(e),delete t.limboKeysByTarget[n])})}).toPromise()},t.prototype.currentLimboDocs=function(){return this.limboTargetsByKey},t.prototype.emitNewSnapsAndNotifyLocalStore=function(t,e){var n=this,r=[],i=[],o=[];return this.queryViewsByQuery.forEach(function(a,s){o.push(Promise.resolve().then(function(){var e=s.view.computeDocChanges(t);return e.needsRefill?n.localStore.executeQuery(s.query).then(function(t){return s.view.computeDocChanges(t,e)}):e}).then(function(t){var o=e&&e.targetChanges[s.targetId],a=s.view.applyChanges(t,o);return n.updateTrackedLimbos(s.targetId,a.limboChanges).then(function(){if(a.snapshot){r.push(a.snapshot);var t=Hn.fromSnapshot(a.snapshot);i.push(t)}})}))}),Promise.all(o).then(function(){return n.viewHandler(r),n.localStore.notifyLocalViewChanges(i)}).then(function(){return n.localStore.collectGarbage()})},t.prototype.assertSubscribed=function(t){c(null!==this.viewHandler&&null!==this.errorHandler,"Trying to call "+t+" before calling subscribe().")},t.prototype.handleUserChange=function(t){var e=this;return this.currentUser=t,this.localStore.handleUserChange(t).then(function(t){return e.emitNewSnapsAndNotifyLocalStore(t)}).then(function(){return e.remoteStore.handleUserChange(t)})},t}(),ir=-1,or=function(){function t(t,e,n){this.batchId=t,this.localWriteTime=e,this.mutations=n}return t.prototype.applyToRemoteDocument=function(t,e,n){e&&c(e.key.equals(t),"applyToRemoteDocument: key "+t+" should match maybeDoc key\n        "+e.key);var r=n.mutationResults;c(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.equals(t)){var a=r[i];e=o.applyToRemoteDocument(e,a)}}return e},t.prototype.applyToLocalView=function(t,e){e&&c(e.key.equals(t),"applyToLocalDocument: key "+t+" should match maybeDoc key\n        "+e.key);for(var n=0;n<this.mutations.length;n++){var r=this.mutations[n];r.key.equals(t)&&(e=r.applyToLocalView(e,this.localWriteTime))}return e},t.prototype.keys=function(){for(var t=et(),e=0,n=this.mutations;e<n.length;e++){var r=n[e];t=t.add(r.key)}return t},t.prototype.equals=function(t){return this.batchId===t.batchId&&B(this.mutations,t.mutations)},t.prototype.isTombstone=function(){return 0===this.mutations.length},t.prototype.toTombstone=function(){return new t(this.batchId,this.localWriteTime,[])},t}(),ar=function(){function t(t,e,n,r,i){this.batch=t,this.commitVersion=e,this.mutationResults=n,this.streamToken=r,this.docVersions=i}return t.from=function(e,n,r,i){c(e.mutations.length===r.length,"Mutations sent "+e.mutations.length+" must equal results received "+r.length);for(var o=tt(),a=e.mutations,s=0;s<a.length;s++){var u=r[s].version;null===u&&(u=n),o=o.insert(a[s].key,u)}return new t(e,n,r,i,o)},t}(),sr="",ur="",cr="",hr="",lr=function(){function t(t,e){this.seconds=t,this.nanos=e}return t}(),fr=function(){function t(t,e){this.ownerId=t,this.leaseTimestampMs=e}return t.store="owner",t}(),pr=function(){function t(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}return t.store="mutationQueues",t.keyPath="userId",t}(),dr=function(){function t(t,e,n,r){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.mutations=r}return t.store="mutations",t.keyPath=["userId","batchId"],t}(),yr=function(){function t(){}return t.prefixForUser=function(t){return[t]},t.prefixForPath=function(t,e){return[t,ut(e)]},t.key=function(t,e,n){return[t,ut(e),n]},t.store="documentMutations",t.PLACEHOLDER=new t,t}(),mr=function(){function t(t,e){this.path=t,this.readTime=e}return t}(),gr=function(){function t(t,e){this.noDocument=t,this.document=e}return t.store="remoteDocuments",t}(),vr=function(){function t(t,e,n,r,i,o){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.query=o}return t.store="targets",t.keyPath="targetId",t.queryTargetsIndexName="queryTargetsIndex",t.queryTargetsKeyPath=["canonicalId","targetId"],t}(),br=function(){function t(t,e){this.targetId=t,this.path=e}return t.store="targetDocuments",t.keyPath=["targetId","path"],t.documentTargetsIndex="documentTargetsIndex",t.documentTargetsKeyPath=["path","targetId"],t}(),wr=function(){function t(t,e,n){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n}return t.key="targetGlobalKey",t.store="targetGlobal",t}(),Ir=[pr.store,dr.store,yr.store,gr.store,vr.store,fr.store,wr.store,br.store],Tr=function(){function t(t){this.db=t}return t.openOrCreate=function(e,n,r){return c(t.isAvailable(),"IndexedDB not supported in current environment."),o("SimpleDb","Opening database:",e),new Gn(function(i,a){var s=window.indexedDB.open(e,n);s.onsuccess=function(e){var n=e.target.result;i(new t(n))},s.onerror=function(t){a(t.target.error)},s.onupgradeneeded=function(t){o("SimpleDb",'Database "'+e+'" requires upgrade from version:',t.oldVersion);var n=t.target.result;r(n,t.oldVersion)}}).toPromise()},t.delete=function(t){return o("SimpleDb","Removing database:",t),pt(window.indexedDB.deleteDatabase(t)).toPromise()},t.isAvailable=function(){if("undefined"==typeof window||null==window.indexedDB)return!1;var t=window.navigator.userAgent;return!(t.indexOf("MSIE ")>0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0)},t.prototype.runTransaction=function(t,e,n){var r=new Sr(this.db,t,e),i=n(r).catch(function(t){return r.abort(),Gn.reject(t)}).toPromise();return r.completionPromise.then(function(){return i})},t.prototype.close=function(){this.db.close()},t}(),Er=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return pt(this.dbCursor.delete())},t}(),Sr=function(){function t(t,e,n){var r=this;this.aborted=!1,this.transaction=t.transaction(n,e),this.completionPromise=new Promise(function(t,e){r.transaction.onabort=r.transaction.oncomplete=function(e){t()},r.transaction.onerror=function(t){e(t.target.error)}})}return t.prototype.abort=function(){this.aborted||(o("SimpleDb","Aborting transaction."),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return c(!!e,"Object store not part of transaction: "+t),new Nr(e)},t}(),Nr=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(o("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(o("SimpleDb","PUT",this.store.name,"<auto-key>",t),n=this.store.put(t)),pt(n)},t.prototype.get=function(t){var e=this;return pt(this.store.get(t)).next(function(n){return void 0===n&&(n=null),o("SimpleDb","GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return o("SimpleDb","DELETE",this.store.name,t),pt(this.store.delete(t))},t.prototype.loadAll=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.iterateCursor(n,function(t,e){r.push(e)}).next(function(){return r})},t.prototype.deleteAll=function(t,e){o("SimpleDb","DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},t.prototype.iterateCursor=function(t,e){var n=[];return new Gn(function(r,i){t.onerror=function(t){i(t.target.error)},t.onsuccess=function(t){var i=t.target.result;if(!i)return void r();var o=new Er(i),a=e(i.primaryKey,i.value,o);a instanceof Gn&&n.push(a),o.isDone?r():null===o.skipToKey?i.continue():i.continue(o.skipToKey)}}).next(function(){return Gn.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(c(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}(),Cr=function(){function t(t,e){this.userId=t,this.serializer=e,this.garbageCollector=null}return t.forUser=function(e,n){return c(""!==e.uid,"UserID must not be an empty string."),new t(e.isUnauthenticated()?"":e.uid,n)},t.prototype.start=function(e){var n=this;return t.loadNextBatchIdFromDb(e).next(function(t){return n.nextBatchId=t,gt(e).get(n.userId)}).next(function(t){return t||(t=new pr(n.userId,ir,"")),n.metadata=t,n.metadata.lastAcknowledgedBatchId>=n.nextBatchId?n.checkEmpty(e).next(function(t){return c(t,"Reset nextBatchID is only possible when the queue is empty"),n.metadata.lastAcknowledgedBatchId=ir,gt(e).put(n.metadata)}):Gn.resolve()})},t.loadNextBatchIdFromDb=function(t){var e=ir;return yt(t).iterate({reverse:!0},function(t,n,r){var i=t[0];if(t[1]>e&&(e=n.batchId),""===i)r.done();else{var o=U(i);r.skip([o])}}).next(function(){return e+1})},t.prototype.checkEmpty=function(t){var e=!0,n=IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).iterate({range:n},function(t,n,r){e=!1,r.done()}).next(function(){return e})},t.prototype.getNextBatchId=function(t){return Gn.resolve(this.nextBatchId)},t.prototype.getHighestAcknowledgedBatchId=function(t){return Gn.resolve(this.metadata.lastAcknowledgedBatchId)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;return c(r>this.metadata.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),this.metadata.lastAcknowledgedBatchId=r,this.metadata.lastStreamToken=dt(n),gt(t).put(this.metadata)},t.prototype.getLastStreamToken=function(t){return Gn.resolve(this.metadata.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.metadata.lastStreamToken=dt(e),gt(t).put(this.metadata)},t.prototype.addMutationBatch=function(t,e,n){var r=this,i=this.nextBatchId;this.nextBatchId++;var o=new or(i,e,n),a=this.serializer.toDbMutationBatch(this.userId,o);return yt(t).put(a).next(function(){for(var e=[],o=0,a=n;o<a.length;o++){var s=a[o],u=(ut(s.key.path),yr.key(r.userId,s.key.path,i));mt(t).put(u,yr.PLACEHOLDER)}return Gn.waitFor(e)}).next(function(){return o})},t.prototype.lookupMutationBatch=function(t,e){var n=this;return yt(t).get(this.keyForBatchId(e)).next(function(t){return t?n.serializer.fromDbMutationBatch(t):null})},t.prototype.getNextMutationBatchAfterBatchId=function(t,e){var n=this,r=IDBKeyRange.lowerBound(this.keyForBatchId(e+1)),i=null;return yt(t).iterate({range:r},function(t,r,o){r.userId===n.userId&&(c(r.batchId>e,"Should have found mutation after "+e),i=n.serializer.fromDbMutationBatch(r)),o.done()}).next(function(){return i})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound(this.keyForBatchId(ir),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).loadAll(n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesThroughBatchId=function(t,e){var n=this,r=IDBKeyRange.bound(this.keyForBatchId(ir),this.keyForBatchId(e));return yt(t).loadAll(r).next(function(t){return t.map(function(t){return n.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=yr.prefixForPath(this.userId,e.path),i=IDBKeyRange.lowerBound(r),o=[];return mt(t).iterate({range:i},function(r,i,a){var s=r[0],c=r[1],h=r[2],l=lt(c);if(s!==n.userId||!e.path.equals(l))return void a.done();var f=n.keyForBatchId(h);return yt(t).get(f).next(function(t){null===t&&u("Dangling document-mutation reference found: "+r+" which points to "+f),o.push(n.serializer.fromDbMutationBatch(t))})}).next(function(){return o})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;c(!e.isDocumentQuery(),"Document queries shouldn't go down this path");var r=e.path,i=r.length+1,o=yr.prefixForPath(this.userId,r),a=(o[1],IDBKeyRange.lowerBound(o)),s=new hn(L);return mt(t).iterate({range:a},function(t,e,o){var a=t[0],u=t[1],c=t[2],h=lt(u);if(a!==n.userId||!r.isPrefixOf(h))return void o.done();h.length===i&&(s=s.add(c))}).next(function(){var e=[],r=[];return s.forEach(function(i){var o=n.keyForBatchId(i);r.push(yt(t).get(o).next(function(t){null===t&&u("Dangling document-mutation reference found, which points to "+o),e.push(n.serializer.fromDbMutationBatch(t))}))}),Gn.waitFor(r).next(function(){return e})})},t.prototype.removeMutationBatches=function(t,e){for(var n=yt(t),r=mt(t),i=[],o=this,a=0,s=e;a<s.length;a++){var u=s[a];!function(t){var e=IDBKeyRange.only(o.keyForBatchId(t.batchId)),a=0,s=n.iterate({range:e},function(t,e,n){return a++,n.delete()});i.push(s.next(function(){c(1===a,"Dangling document-mutation reference found: Missing batch "+t.batchId)}));for(var u=0,h=t.mutations;u<h.length;u++){var l=h[u],f=yr.key(o.userId,l.key.path,t.batchId);i.push(r.delete(f)),null!==o.garbageCollector&&o.garbageCollector.addPotentialGarbageKey(l.key)}}(u)}return Gn.waitFor(i)},t.prototype.performConsistencyCheck=function(t){var e=this;return this.checkEmpty(t).next(function(n){if(!n)return Gn.resolve();var r=IDBKeyRange.lowerBound(yr.prefixForUser(e.userId)),i=[];return mt(t).iterate({range:r},function(t,n,r){if(t[0]!==e.userId)return void r.done();var o=lt(t[1]);i.push(o)}).next(function(){c(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map(function(t){return t.canonicalString()}))})})},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){var n=this,r=yr.prefixForPath(this.userId,e.path),i=r[1],o=IDBKeyRange.lowerBound(r),a=!1;return mt(t).iterate({range:o,keysOnly:!0},function(t,e,r){var o=t[0],s=t[1];t[2],o===n.userId&&s===i&&(a=!0),r.done()}).next(function(){return a})},t.prototype.keyForBatchId=function(t){return[this.userId,t]},t}(),Dr=function(){function t(t){this.serializer=t,this.lastRemoteSnapshotVersion=We.MIN,this.metadata=new wr(0,0,We.MIN.toTimestamp()),this.garbageCollector=null}return t.prototype.start=function(t){var e=this;return wt(t).get(wr.key).next(function(t){if(null!==t){e.metadata=t;var n=t.lastRemoteSnapshotVersion;e.lastRemoteSnapshotVersion=We.fromTimestamp(new Ge(n.seconds,n.nanos))}return Gn.resolve()})},t.prototype.getHighestTargetId=function(){return this.metadata.highestTargetId},t.prototype.getLastRemoteSnapshotVersion=function(){return this.lastRemoteSnapshotVersion},t.prototype.setLastRemoteSnapshotVersion=function(t,e){return this.lastRemoteSnapshotVersion=e,this.metadata.lastRemoteSnapshotVersion=e.toTimestamp(),wt(t).put(wr.key,this.metadata)},t.prototype.addQueryData=function(t,e){var n=this,r=e.targetId,i=bt(t).put(this.serializer.toDbTarget(e));return r>this.metadata.highestTargetId?(this.metadata.highestTargetId=r,i.next(function(){return wt(t).put(wr.key,n.metadata)})):i},t.prototype.removeQueryData=function(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){bt(t).delete(e.targetId)})},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),i=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),o=null;return bt(t).iterate({range:i,index:vr.queryTargetsIndexName},function(t,r,i){var a=n.serializer.fromDbTarget(r);e.equals(a.query)&&(o=a,i.done())}).next(function(){return o})},t.prototype.addMatchingKeys=function(t,e,n){var r=[],i=It(t);return e.forEach(function(t){var e=ut(t.path);r.push(i.put(new br(n,e)))}),Gn.waitFor(r)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,i=[],o=It(t);return e.forEach(function(t){var e=ut(t.path);i.push(o.delete([n,e])),null!==r.garbageCollector&&r.garbageCollector.addPotentialGarbageKey(t)}),Gn.waitFor(i)},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=It(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return this.notifyGCForRemovedKeys(t,r).next(function(){return n.delete(r)})},t.prototype.notifyGCForRemovedKeys=function(t,e){var n=this,r=It(t);return null!==this.garbageCollector&&this.garbageCollector.isEager?r.iterate({range:e,keysOnly:!0},function(t,e,r){var i=lt(t[1]),o=new ae(i);c(null!==n.garbageCollector,"GarbageCollector for query cache set to null during key removal."),n.garbageCollector.addPotentialGarbageKey(o)}):Gn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=It(t),i=et();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=lt(t[1]),o=new ae(r);i=i.add(o)}).next(function(){return i})},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){c(null!==t,"Persistence Transaction cannot be null for query cache containsKey");var n=ut(e.path),r=IDBKeyRange.bound([n],[F(n)],!1,!0),i=0;return It(t).iterate({index:br.documentTargetsIndex,keysOnly:!0,range:r},function(t,e,n){i++,n.done()}).next(function(){return i>0})},t}(),Ar=function(){function t(t){this.serializer=t}return t.prototype.addEntry=function(t,e){return Et(t).put(St(e.key),this.serializer.toDbRemoteDocument(e))},t.prototype.removeEntry=function(t,e){return Et(t).delete(St(e))},t.prototype.getEntry=function(t,e){var n=this;return Et(t).get(St(e)).next(function(t){return t?n.serializer.fromDbRemoteDocument(t):null})},t.prototype.getDocumentsMatchingQuery=function(t,e){var n=this,r=$(),i=e.path.toArray(),o=IDBKeyRange.lowerBound(i);return Et(t).iterate({range:o},function(t,i,o){var a=n.serializer.fromDbRemoteDocument(i);e.path.isPrefixOf(a.key.path)?a instanceof se&&e.matches(a)&&(r=r.insert(a.key,a)):o.done()}).next(function(){return r})},t}(),kr=function(){function t(t){this.remoteSerializer=t}return t.prototype.fromDbRemoteDocument=function(t){if(t.document)return this.remoteSerializer.fromDocument(t.document);if(t.noDocument){var e=ae.fromSegments(t.noDocument.path),n=t.noDocument.readTime,r=new Ge(n.seconds,n.nanos);return new ue(e,We.fromTimestamp(r))}return u("Unexpected DbRemoteDocument")},t.prototype.toDbRemoteDocument=function(t){if(t instanceof se){var e=this.remoteSerializer.toDocument(t);return new gr(null,e)}var n=t.key.path.toArray(),r=t.version.toTimestamp(),i=new lr(r.seconds,r.nanos);return new gr(new mr(n,i),null)},t.prototype.toDbMutationBatch=function(t,e){var n=this,r=e.mutations.map(function(t){return n.remoteSerializer.toMutation(t)});return new dr(t,e.batchId,e.localWriteTime.toEpochMilliseconds(),r)},t.prototype.fromDbMutationBatch=function(t){var e=this,n=t.mutations.map(function(t){return e.remoteSerializer.fromMutation(t)}),r=Ge.fromEpochMilliseconds(t.localWriteTimeMs);return new or(t.batchId,r,n)},t.prototype.fromDbTarget=function(t){var e,n=new Ge(t.readTime.seconds,t.readTime.nanos),r=We.fromTimestamp(n);return e=Nt(t.query)?this.remoteSerializer.fromDocumentsTarget(t.query):this.remoteSerializer.fromQueryTarget(t.query),new ze(e,t.targetId,ye.Listen,r,t.resumeToken)},t.prototype.toDbTarget=function(t){c(ye.Listen===t.purpose,"Only queries with purpose "+ye.Listen+" may be stored, got "+t.purpose);var e,n=t.snapshotVersion.toTimestamp(),r=new lr(n.seconds,n.nanos);e=t.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(t.query):this.remoteSerializer.toQueryTarget(t.query),c("string"==typeof t.resumeToken,"Persisting non-string resume token not supported.");var i=t.resumeToken;return new vr(t.targetId,t.query.canonicalId(),r,i,0,e)},t}(),Rr="There is another tab open with offline persistence enabled. Only one such tab is allowed at a time. The other tab must be closed or persistence must be disabled.",Or=function(){function t(e,n){this.ownerId=this.generateOwnerId(),this.dbName=e+t.MAIN_DATABASE,this.serializer=new kr(n),this.localStoragePrefix=e}return t.prototype.start=function(){var e=this;return t.isAvailable()?(c(!this.started,"IndexedDbPersistence double-started!"),this.started=!0,Tr.openOrCreate(this.dbName,1,ft).then(function(t){e.simpleDb=t}).then(function(){return e.tryAcquireOwnerLease()}).then(function(){e.scheduleOwnerLeaseRefreshes(),e.attachWindowUnloadHook()})):(this.persistenceError=new Ht(Wt.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."),Promise.reject(this.persistenceError))},t.prototype.shutdown=function(){var t=this;return c(this.started,"IndexedDbPersistence shutdown without start!"),this.started=!1,this.detachWindowUnloadHook(),this.stopOwnerLeaseRefreshes(),this.releaseOwnerLease().then(function(){t.simpleDb.close()})},t.prototype.getMutationQueue=function(t){return Cr.forUser(t,this.serializer)},t.prototype.getQueryCache=function(){return new Dr(this.serializer)},t.prototype.getRemoteDocumentCache=function(){return new Ar(this.serializer)},t.prototype.runTransaction=function(t,e){var n=this;return this.persistenceError?Promise.reject(this.persistenceError):(o("IndexedDbPersistence","Starting transaction:",t),this.simpleDb.runTransaction("readwrite",Ir,function(t){return n.ensureOwnerLease(t).next(function(){return e(t)})}))},t.isAvailable=function(){return Tr.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.tryAcquireOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[fr.store],function(e){var n=e.store(fr.store);return n.get("owner").next(function(e){if(t.validOwner(e))return o("IndexedDbPersistence","Valid owner already. Failing. Current owner:",e),t.persistenceError=new Ht(Wt.FAILED_PRECONDITION,Rr),Gn.reject(t.persistenceError);var r=new fr(t.ownerId,Date.now());return o("IndexedDbPersistence","No valid owner. Acquiring owner lease. Current owner:",e,"New owner:",r),n.put("owner",r)})})},t.prototype.releaseOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[fr.store],function(e){var n=e.store(fr.store);return n.get("owner").next(function(e){return null!==e&&e.ownerId===t.ownerId?(o("IndexedDbPersistence","Releasing owner lease."),n.delete("owner")):Gn.resolve()})})},t.prototype.ensureOwnerLease=function(t){var e=this;return t.store(fr.store).get("owner").next(function(t){return null===t||t.ownerId!==e.ownerId?(e.persistenceError=new Ht(Wt.FAILED_PRECONDITION,Rr),Gn.reject(e.persistenceError)):Gn.resolve()})},t.prototype.validOwner=function(t){var e=Date.now(),n=e-5e3,r=e;return!(null===t||t.leaseTimestampMs<n||(t.leaseTimestampMs>r?(a("Persistence owner-lease is in the future. Discarding.",t),1):t.ownerId===this.getZombiedOwnerId()))},t.prototype.scheduleOwnerLeaseRefreshes=function(){var t=this;this.ownerLeaseRefreshHandle=setInterval(function(){t.runTransaction("Refresh owner timestamp",function(e){return e.store(fr.store).put("owner",new fr(t.ownerId,Date.now()))}).catch(function(e){a(e),t.stopOwnerLeaseRefreshes()})},4e3)},t.prototype.stopOwnerLeaseRefreshes=function(){this.ownerLeaseRefreshHandle&&(clearInterval(this.ownerLeaseRefreshHandle),this.ownerLeaseRefreshHandle=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;this.windowUnloadHandler=function(){t.setZombiedOwnerId(t.ownerId),t.shutdown()},window.addEventListener("unload",this.windowUnloadHandler)},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.getZombiedOwnerId=function(){try{var t=window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());return o("IndexedDbPersistence","Zombied ownerID from LocalStorage:",t),t}catch(t){return a("IndexedDbPersistence","Failed to get zombie owner id.",t),null}},t.prototype.setZombiedOwnerId=function(t){try{null===t?window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey()):window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(),t)}catch(t){a("IndexedDbPersistence","Failed to set zombie owner id.",t)}},t.prototype.zombiedOwnerLocalStorageKey=function(){return this.localStoragePrefix+"zombiedOwnerId"},t.prototype.generateOwnerId=function(){return zt.newId()},t.MAIN_DATABASE="main",t}(),Mr=function(){function t(t,e){this.remoteDocumentCache=t,this.mutationQueue=e}return t.prototype.getDocument=function(t,e){var n=this;return this.remoteDocumentCache.getEntry(t,e).next(function(r){return n.computeLocalDocument(t,e,r)})},t.prototype.getDocuments=function(t,e){var n=this,r=[],i=Z();return e.forEach(function(e){r.push(n.getDocument(t,e).next(function(t){t||(t=new ue(e,We.forDeletedDoc())),i=i.insert(e,t)}))}),Gn.waitFor(r).next(function(){return i})},t.prototype.getDocumentsMatchingQuery=function(t,e){return ae.isDocumentKey(e.path)?this.getDocumentsMatchingDocumentQuery(t,e.path):this.getDocumentsMatchingCollectionQuery(t,e)},t.prototype.getDocumentsMatchingDocumentQuery=function(t,e){return this.getDocument(t,new ae(e)).next(function(t){var e=$();return t instanceof se&&(e=e.insert(t.key,t)),e})},t.prototype.getDocumentsMatchingCollectionQuery=function(t,e){var n,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(t,e).next(function(e){return r.computeLocalDocuments(t,e)}).next(function(i){return n=i,r.mutationQueue.getAllMutationBatchesAffectingQuery(t,e)}).next(function(e){for(var i=et(),o=0,a=e;o<a.length;o++)for(var s=a[o],u=0,c=s.mutations;u<c.length;u++){var h=c[u];n.get(h.key)||(i=i.add(h.key))}var l=[];return i.forEach(function(e){l.push(r.getDocument(t,e).next(function(t){t instanceof se&&(n=n.insert(t.key,t))}))}),Gn.waitFor(l)}).next(function(){return n.forEach(function(t,r){e.matches(r)||(n=n.remove(t))}),n})},t.prototype.computeLocalDocument=function(t,e,n){return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(t,e).next(function(t){for(var r=0,i=t;r<i.length;r++){var o=i[r];n=o.applyToLocalView(e,n)}return n})},t.prototype.computeLocalDocuments=function(t,e){var n=this,r=[];return e.forEach(function(i,o){r.push(n.computeLocalDocument(t,i,o).next(function(t){t instanceof se?e=e.insert(t.key,t):t instanceof ue?e=e.remove(t.key):u("Unknown MaybeDocument: "+t)}))}),Gn.waitFor(r).next(function(){return e})},t}(),_r=function(){function t(t){this.remoteDocumentCache=t,this.changes=Z()}return t.prototype.addEntry=function(t){var e=this.assertChanges();this.changes=e.insert(t.key,t)},t.prototype.getEntry=function(t,e){var n=this.assertChanges(),r=n.get(e);return r?Gn.resolve(r):this.remoteDocumentCache.getEntry(t,e)},t.prototype.apply=function(t){var e=this,n=this.assertChanges(),r=[];return n.forEach(function(n,i){r.push(e.remoteDocumentCache.addEntry(t,i))}),this.changes=null,Gn.waitFor(r)},t.prototype.assertChanges=function(){return c(null!==this.changes,"Changes have already been applied."),this.changes},t}(),Pr=function(){function t(t,e,n){this.persistence=t,this.garbageCollector=n,this.localViewReferences=new zn,this.targetIds={},this.targetIdGenerator=Zn.forLocalStore(),this.heldBatchResults=[],this.mutationQueue=t.getMutationQueue(e),this.remoteDocuments=t.getRemoteDocumentCache(),this.queryCache=t.getQueryCache(),this.localDocuments=new Mr(this.remoteDocuments,this.mutationQueue),this.garbageCollector.addGarbageSource(this.localViewReferences),this.garbageCollector.addGarbageSource(this.queryCache),this.garbageCollector.addGarbageSource(this.mutationQueue)}return t.prototype.start=function(){var t=this;return this.persistence.runTransaction("Start LocalStore",function(e){return t.startMutationQueue(e).next(function(){return t.startQueryCache(e)})})},t.prototype.handleUserChange=function(t){var e=this;return this.persistence.runTransaction("Handle user change",function(n){var r;return e.mutationQueue.getAllMutationBatches(n).next(function(i){return r=i,e.garbageCollector.removeGarbageSource(e.mutationQueue),e.mutationQueue=e.persistence.getMutationQueue(t),e.garbageCollector.addGarbageSource(e.mutationQueue),e.startMutationQueue(n)}).next(function(){return e.localDocuments=new Mr(e.remoteDocuments,e.mutationQueue),e.mutationQueue.getAllMutationBatches(n)}).next(function(t){for(var i=et(),o=0,a=[r,t];o<a.length;o++)for(var s=a[o],u=0,c=s;u<c.length;u++)for(var h=c[u],l=0,f=h.mutations;l<f.length;l++){var p=f[l];i=i.add(p.key)}return e.localDocuments.getDocuments(n,i)})})},t.prototype.startQueryCache=function(t){var e=this;return this.queryCache.start(t).next(function(){var t=e.queryCache.getHighestTargetId();e.targetIdGenerator=Zn.forLocalStore(t)})},t.prototype.startMutationQueue=function(t){var e=this;return this.mutationQueue.start(t).next(function(){return e.heldBatchResults=[],e.mutationQueue.getHighestAcknowledgedBatchId(t)}).next(function(n){return n!==ir?e.mutationQueue.getAllMutationBatchesThroughBatchId(t,n):Gn.resolve([])}).next(function(n){return n.length>0?e.mutationQueue.removeMutationBatches(t,n):Gn.resolve()})},t.prototype.localWrite=function(t){var e=this;return this.persistence.runTransaction("Locally write mutations",function(n){var r,i=Ge.now();return e.mutationQueue.addMutationBatch(n,i,t).next(function(t){r=t;var i=r.keys();return e.localDocuments.getDocuments(n,i)}).next(function(t){return{batchId:r.batchId,changes:t}})})},t.prototype.acknowledgeBatch=function(t){var e=this;return this.persistence.runTransaction("Acknowledge batch",function(n){var r;return e.mutationQueue.acknowledgeBatch(n,t.batch,t.streamToken).next(function(){if(e.shouldHoldBatchResult(t.commitVersion))return e.heldBatchResults.push(t),r=et(),Gn.resolve();var i=new _r(e.remoteDocuments);return e.releaseBatchResults(n,[t],i).next(function(t){return r=t,i.apply(n)})}).next(function(){return e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,r)})})},t.prototype.rejectBatch=function(t){var e=this;return this.persistence.runTransaction("Reject batch",function(n){var r,i;return e.mutationQueue.lookupMutationBatch(n,t).next(function(i){return c(null!=i,"Attempt to reject nonexistent batch!"),r=i,e.mutationQueue.getHighestAcknowledgedBatchId(n).next(function(e){return c(t>e,"Acknowledged batches can't be rejected."),r})}).next(function(){return e.removeMutationBatch(n,r)}).next(function(t){return i=t,e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,i)})})},t.prototype.getLastStreamToken=function(){var t=this;return this.persistence.runTransaction("Get last stream token",function(e){return t.mutationQueue.getLastStreamToken(e)})},t.prototype.setLastStreamToken=function(t){var e=this;return this.persistence.runTransaction("Set last stream token",function(n){return e.mutationQueue.setLastStreamToken(n,t)})},t.prototype.getLastRemoteSnapshotVersion=function(){return this.queryCache.getLastRemoteSnapshotVersion()},t.prototype.applyRemoteEvent=function(t){var e=this,n=new _r(this.remoteDocuments);return this.persistence.runTransaction("Apply remote event",function(r){var i=[];d(t.targetChanges,function(t,n){var o=e.targetIds[t];if(o){var a=n.mapping;if(a)if(a instanceof vn)i.push(e.queryCache.removeMatchingKeysForTargetId(r,t).next(function(){return e.queryCache.addMatchingKeys(r,a.documents,t)}));else{if(!(a instanceof bn))return u("Unknown mapping type: "+JSON.stringify(a));i.push(e.queryCache.removeMatchingKeys(r,a.removedDocuments,t).next(function(){return e.queryCache.addMatchingKeys(r,a.addedDocuments,t)}))}var s=n.resumeToken;s.length>0&&(o=o.update({resumeToken:s,snapshotVersion:n.snapshotVersion}),e.targetIds[t]=o,i.push(e.queryCache.addQueryData(r,o)))}});var a=et();t.documentUpdates.forEach(function(t,s){a=a.add(t),i.push(n.getEntry(r,t).next(function(r){null==r||s.version.equals(We.MIN)||s.version.compareTo(r.version)>=0?n.addEntry(s):o("LocalStore","Ignoring outdated watch update for ",t,". Current version:",r.version," Watch version:",s.version),e.garbageCollector.addPotentialGarbageKey(t)}))});var s=e.queryCache.getLastRemoteSnapshotVersion(),h=t.snapshotVersion;h.equals(We.MIN)||(c(h.compareTo(s)>=0,"Watch stream reverted to previous snapshot?? "+h+" < "+s),i.push(e.queryCache.setLastRemoteSnapshotVersion(r,h)));var l;return Gn.waitFor(i).next(function(){return e.releaseHeldBatchResults(r,n)}).next(function(t){return l=t,n.apply(r)}).next(function(){return e.localDocuments.getDocuments(r,a.unionWith(l))})})},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("Notify local view changes",function(n){for(var r=[],i=0,o=t;i<o.length;i++){var a=o[i];!function(t){r.push(e.queryCache.getQueryData(n,t.query).next(function(n){c(null!==n,"Local view changes contain unallocated query.");var r=n.targetId;e.localViewReferences.addReferences(t.addedKeys,r),e.localViewReferences.removeReferences(t.removedKeys,r)}))}(a)}return Gn.waitFor(r)})},t.prototype.nextMutationBatch=function(t){var e=this;return this.persistence.runTransaction("Get next mutation batch",function(n){return void 0===t&&(t=ir),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)})},t.prototype.readDocument=function(t){var e=this;return this.persistence.runTransaction("read document",function(n){return e.localDocuments.getDocument(n,t)})},t.prototype.allocateQuery=function(t){var e=this;return this.persistence.runTransaction("Allocate query",function(n){var r;return e.queryCache.getQueryData(n,t).next(function(i){if(i)return r=i,Gn.resolve();var o=e.targetIdGenerator.next();return r=new ze(t,o,ye.Listen),e.queryCache.addQueryData(n,r)}).next(function(){return c(!e.targetIds[r.targetId],"Tried to allocate an already allocated query: "+t),e.targetIds[r.targetId]=r,r})})},t.prototype.releaseQuery=function(t){var e=this;return this.persistence.runTransaction("Release query",function(n){return e.queryCache.getQueryData(n,t).next(function(r){return c(null!=r,"Tried to release nonexistent query: "+t),e.localViewReferences.removeReferencesForId(r.targetId),delete e.targetIds[r.targetId],e.garbageCollector.isEager?e.queryCache.removeQueryData(n,r):Gn.resolve()}).next(function(){if(m(e.targetIds)){var t=new _r(e.remoteDocuments);return e.releaseHeldBatchResults(n,t).next(function(){t.apply(n)})}return Gn.resolve()})})},t.prototype.executeQuery=function(t){var e=this;return this.persistence.runTransaction("Execute query",function(n){return e.localDocuments.getDocumentsMatchingQuery(n,t)})},t.prototype.remoteDocumentKeys=function(t){var e=this;return this.persistence.runTransaction("Remote document keys",function(n){return e.queryCache.getMatchingKeysForTargetId(n,t)})},t.prototype.collectGarbage=function(){var t=this;return this.persistence.runTransaction("Garbage collection",function(e){return t.garbageCollector.collectGarbage(e).next(function(n){var r=[];return n.forEach(function(n){r.push(t.remoteDocuments.removeEntry(e,n))}),Gn.waitFor(r)})})},t.prototype.releaseHeldBatchResults=function(t,e){for(var n=[],r=0,i=this.heldBatchResults;r<i.length;r++){var o=i[r];if(!this.isRemoteUpToVersion(o.commitVersion))break;n.push(o)}return 0===n.length?Gn.resolve(et()):(this.heldBatchResults.splice(0,n.length),this.releaseBatchResults(t,n,e))},t.prototype.isRemoteUpToVersion=function(t){var e=this.queryCache.getLastRemoteSnapshotVersion();return t.compareTo(e)<=0||m(this.targetIds)},t.prototype.shouldHoldBatchResult=function(t){return!this.isRemoteUpToVersion(t)||this.heldBatchResults.length>0},t.prototype.releaseBatchResults=function(t,e,n){for(var r=this,i=Gn.resolve(),o=0,a=e;o<a.length;o++){var s=a[o];!function(e){i=i.next(function(){return r.applyWriteToRemoteDocuments(t,e,n)})}(s)}return i.next(function(){return r.removeMutationBatches(t,e.map(function(t){return t.batch}))})},t.prototype.removeMutationBatch=function(t,e){return this.removeMutationBatches(t,[e])},t.prototype.removeMutationBatches=function(t,e){for(var n=et(),r=0,i=e;r<i.length;r++)for(var o=i[r],a=0,s=o.mutations;a<s.length;a++){var u=s[a],c=u.key;n=n.add(c)}return this.mutationQueue.removeMutationBatches(t,e).next(function(){return n})},t.prototype.applyWriteToRemoteDocuments=function(t,e,n){var r=e.batch,i=r.keys(),o=Gn.resolve();return i.forEach(function(i){o=o.next(function(){return n.getEntry(t,i)}).next(function(t){var o=t,a=e.docVersions.get(i);c(null!==a,"ackVersions should contain every doc in the write."),(!o||o.version.compareTo(a)<0)&&(o=r.applyToRemoteDocument(i,o,e),o?n.addEntry(o):c(!t,"Mutation batch "+r+" applied to document "+t+" resulted in null"))})}),o},t}(),Lr=function(){function t(){this.mutationQueue=[],this.nextBatchId=1,this.highestAcknowledgedBatchId=ir,this.lastStreamToken=h(),this.garbageCollector=null,this.batchesByDocumentKey=new hn(Xn.compareByKey)}return t.prototype.start=function(t){return 0===this.mutationQueue.length&&(this.nextBatchId=1,this.highestAcknowledgedBatchId=ir),c(this.highestAcknowledgedBatchId<this.nextBatchId,"highestAcknowledgedBatchId must be less than the nextBatchId"),Gn.resolve()},t.prototype.checkEmpty=function(t){return Gn.resolve(0===this.mutationQueue.length)},t.prototype.getNextBatchId=function(t){return Gn.resolve(this.nextBatchId)},t.prototype.getHighestAcknowledgedBatchId=function(t){return Gn.resolve(this.highestAcknowledgedBatchId)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;c(r>this.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var i=this.indexOfExistingBatchId(r,"acknowledged"),o=this.mutationQueue[i];return c(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),c(!o.isTombstone(),"Can't acknowledge a previously removed batch"),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,Gn.resolve()},t.prototype.getLastStreamToken=function(t){return Gn.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,Gn.resolve()},t.prototype.addMutationBatch=function(t,e,n){c(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;this.nextBatchId++,this.mutationQueue.length>0&&c(this.mutationQueue[this.mutationQueue.length-1].batchId<r,"Mutation batchIDs must be monotonically increasing order");var i=new or(r,e,n);this.mutationQueue.push(i);for(var o=0,a=n;o<a.length;o++){var s=a[o];this.batchesByDocumentKey=this.batchesByDocumentKey.add(new Xn(s.key,r))}return Gn.resolve(i)},t.prototype.lookupMutationBatch=function(t,e){return Gn.resolve(this.findMutationBatch(e))},t.prototype.getNextMutationBatchAfterBatchId=function(t,e){var n=this.mutationQueue.length;e=Math.max(e+1,this.highestAcknowledgedBatchId);for(var r=this.indexOfBatchId(e),i=r<0?0:r;i<n;i++){var o=this.mutationQueue[i];if(!o.isTombstone())return Gn.resolve(o)}return Gn.resolve(null)},t.prototype.getAllMutationBatches=function(t){return Gn.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length))},t.prototype.getAllMutationBatchesThroughBatchId=function(t,e){var n=this.mutationQueue.length,r=this.indexOfBatchId(e);return r<0?r=0:r>=n?r=n:r++,Gn.resolve(this.getAllLiveMutationBatchesBeforeIndex(r))},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new Xn(e,0),i=new Xn(e,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([r,i],function(t){c(e.equals(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);c(null!==r,"Batches in the index must exist in the main table"),o.push(r)}),Gn.resolve(o)},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this,r=e.path,i=r.length+1,o=r;ae.isDocumentKey(o)||(o=o.child(""));var a=new Xn(new ae(o),0),s=new hn(L);this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!r.isPrefixOf(e)&&(e.length===i&&(s=s.add(t.targetOrBatchId)),!0)},a);var u=[];return s.forEach(function(t){var e=n.findMutationBatch(t);null!==e&&u.push(e)}),Gn.resolve(u)},t.prototype.removeMutationBatches=function(t,e){var n=e.length;c(n>0,"Should not remove mutations when none exist.");var r=e[0].batchId,i=this.mutationQueue.length,o=this.indexOfExistingBatchId(r,"removed");c(this.mutationQueue[o].batchId===r,"Removed batches must exist in the queue");for(var a=1,s=o+1;a<n&&s<i;){var u=this.mutationQueue[s];u.isTombstone()?s++:(c(u.batchId===e[a].batchId,"Removed batches must be contiguous in the queue"),a++,s++)}if(0===o){for(;s<i;s++){var u=this.mutationQueue[s];if(!u.isTombstone())break}var h=s-o;this.mutationQueue.splice(o,h)}else for(var l=o;l<s;l++)this.mutationQueue[l]=this.mutationQueue[l].toTombstone();for(var f=this.batchesByDocumentKey,p=0,d=e;p<d.length;p++)for(var u=d[p],y=u.batchId,m=0,g=u.mutations;m<g.length;m++){var v=g[m],b=v.key;null!==this.garbageCollector&&this.garbageCollector.addPotentialGarbageKey(b);var w=new Xn(b,y);f=f.delete(w)}return this.batchesByDocumentKey=f,Gn.resolve()},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){var n=new Xn(e,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return Gn.resolve(e.equals(r&&r.key))},t.prototype.performConsistencyCheck=function(t){return 0===this.mutationQueue.length&&c(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),Gn.resolve()},t.prototype.getAllLiveMutationBatchesBeforeIndex=function(t){for(var e=[],n=0;n<t;n++){var r=this.mutationQueue[n];r.isTombstone()||e.push(r)}return e},t.prototype.indexOfExistingBatchId=function(t,e){var n=this.indexOfBatchId(t);return c(n>=0&&n<this.mutationQueue.length,"Batches must exist to be "+e),n},t.prototype.indexOfBatchId=function(t){return 0===this.mutationQueue.length?0:t-this.mutationQueue[0].batchId},t.prototype.findMutationBatch=function(t){var e=this.indexOfBatchId(t);if(e<0||e>=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return c(n.batchId===t,"If found batch must match"),n.isTombstone()?null:n},t}(),xr=function(){function t(){this.queries=new qn(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=We.MIN,this.highestTargetId=0,this.references=new zn}return t.prototype.start=function(t){return Gn.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(){return this.lastRemoteSnapshotVersion},t.prototype.getHighestTargetId=function(){return this.highestTargetId},t.prototype.setLastRemoteSnapshotVersion=function(t,e){return this.lastRemoteSnapshotVersion=e,Gn.resolve()},t.prototype.addQueryData=function(t,e){this.queries.set(e.query,e);var n=e.targetId;return n>this.highestTargetId&&(this.highestTargetId=n),Gn.resolve()},t.prototype.removeQueryData=function(t,e){return this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),Gn.resolve()},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return Gn.resolve(n)},t.prototype.addMatchingKeys=function(t,e,n){return this.references.addReferences(e,n),Gn.resolve()},t.prototype.removeMatchingKeys=function(t,e,n){return this.references.removeReferences(e,n),Gn.resolve()},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),Gn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return Gn.resolve(n)},t.prototype.setGarbageCollector=function(t){this.references.setGarbageCollector(t)},t.prototype.containsKey=function(t,e){return this.references.containsKey(t,e)},t}(),Br=function(){function t(){this.docs=Z()}return t.prototype.addEntry=function(t,e){return this.docs=this.docs.insert(e.key,e),Gn.resolve()},t.prototype.removeEntry=function(t,e){return this.docs=this.docs.remove(e),Gn.resolve()},t.prototype.getEntry=function(t,e){return Gn.resolve(this.docs.get(e))},t.prototype.getDocumentsMatchingQuery=function(t,e){for(var n=$(),r=new ae(e.path.child("")),i=this.docs.getIteratorFrom(r);i.hasNext();){var o=i.getNext(),a=o.key,s=o.value;if(!e.path.isPrefixOf(a.path))break;s instanceof se&&e.matches(s)&&(n=n.insert(s.key,s))}return Gn.resolve(n)},t}(),Ur=function(){function t(){this.mutationQueues={},this.remoteDocumentCache=new Br,this.queryCache=new xr,this.started=!1}return t.prototype.start=function(){return c(!this.started,"MemoryPersistence double-started!"),this.started=!0,Promise.resolve()},t.prototype.shutdown=function(){return c(this.started,"MemoryPersistence shutdown without start!"),this.started=!1,Promise.resolve()},t.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new Lr,this.mutationQueues[t.toKey()]=e),e},t.prototype.getQueryCache=function(){return this.queryCache},t.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},t.prototype.runTransaction=function(t,e){return o("MemoryPersistence","Starting transaction:",t),e(new Fr).toPromise()},t}(),Fr=function(){function t(){}return t}(),Vr=function(){function t(){this.isEager=!1}return t.prototype.addGarbageSource=function(t){},t.prototype.removeGarbageSource=function(t){},t.prototype.addPotentialGarbageKey=function(t){},t.prototype.collectGarbage=function(t){return Gn.resolve(et())},t}(),qr=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t}(),jr=function(){function t(t,e,n){this.initialDelayMs=t,this.backoffFactor=e,this.maxDelayMs=n,this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndWait=function(){var t=new qr,e=this.currentBaseMs+this.jitterDelayMs();return this.currentBaseMs>0&&o("ExponentialBackoff","Backing off for "+e+" ms (base delay: "+this.currentBaseMs+" ms)"),setTimeout(function(){t.resolve()},e),this.currentBaseMs*=this.backoffFactor,this.currentBaseMs<this.initialDelayMs&&(this.currentBaseMs=this.initialDelayMs),this.currentBaseMs>this.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs),t.promise},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}(),Kr=this&&this.__extends||function(){var t=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])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.Initial=0]="Initial",t[t.Auth=1]="Auth",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff",t[t.Stopped=5]="Stopped"}(Jn||(Jn={}));var Qr,Gr=1e3,Wr=6e4,Hr=1.5,zr=function(){function t(t,e,n,r,i){this.queue=t,this.connection=e,this.credentialsProvider=n,this.stream=null,this.listener=null,this.backoff=new jr(i||Gr,Hr,Wr),this.state=Jn.Initial,this.listener=r}return t.prototype.isStarted=function(){return this.state===Jn.Backoff||this.state===Jn.Auth||this.state===Jn.Open},t.prototype.isOpen=function(){return this.state===Jn.Open},t.prototype.start=function(){if(this.state===Jn.Error)return void this.performBackoff();c(this.state===Jn.Initial,"Already started"),this.auth()},t.prototype.stop=function(){this.state=Jn.Stopped,this.listener=null,null!==this.stream&&(this.stream.close(),this.stream=null)},t.prototype.inhibitBackoff=function(){c(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=Jn.Initial,this.backoff.reset()},t.prototype.auth=function(){var t=this;c(this.state===Jn.Initial,"Must be in initial state to auth"),this.state=Jn.Auth,this.credentialsProvider.getToken(!1).then(function(e){t.startStream(e)},function(e){t.queue.schedule(function(){if(t.state!==Jn.Stopped){var n=new Ht(Wt.UNKNOWN,"Fetching auth token failed: "+e.message);return t.handleStreamClose(n)}return Promise.resolve()})})},t.prototype.startStream=function(t){var e=this;if(this.state!==Jn.Stopped){c(this.state===Jn.Auth,"Trying to start stream in a non-auth state");var n=function(t){e.queue.schedule(function(){return e.state!==Jn.Stopped?t():Promise.resolve()})};null!==this.listener&&(this.stream=this.startRpc(t),this.stream.onOpen(function(){n(function(){return c(e.state===Jn.Auth,"Expected stream to be in state auth, but was "+e.state),e.state=Jn.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t)})}))}},t.prototype.performBackoff=function(){var t=this;c(this.state===Jn.Error,"Should only perform backoff in an error case"),this.state=Jn.Backoff,this.backoff.backoffAndWait().then(function(){t.queue.schedule(function(){return t.state===Jn.Stopped?Promise.resolve():(t.state=Jn.Initial,t.start(),c(t.isStarted(),"PersistentStream should have started"),Promise.resolve())})})},t.prototype.handleStreamClose=function(t){return c(this.isStarted(),"Can't handle server close on non-started stream"),o("PersistentStream","close with error: "+t),this.stream=null,this.state=Jn.Error,t&&t.code===Wt.RESOURCE_EXHAUSTED&&(o("PersistentStream","Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()),this.listener.onClose(t)},t}(),Xr=function(t){function e(e,n,r,i,o,a,s){var u=t.call(this,n,r,i,a,s)||this;return u.databaseInfo=e,u.serializer=o,u}return Kr(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.stream.send(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.stream.send(e)},e}(zr),Yr=function(t){function e(e,n,r,i,o,a,s){var u=t.call(this,n,r,i,a,s)||this;return u.databaseInfo=e,u.serializer=o,u.k=!1,u}return Kr(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.k},enumerable:!0,configurable:!0}),e.prototype.start=function(){this.k=!1,t.prototype.start.call(this)},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(c(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.k){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return c(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.k=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){c(this.isOpen(),"Writing handshake requires an opened stream"),c(!this.k,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.stream.send(t)},e.prototype.writeMutations=function(t){var e=this;c(this.isOpen(),"Writing mutations requires an opened stream"),c(this.k,"Handshake must be complete before writing mutations"),c(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map(function(t){return e.serializer.toMutation(t)})};this.stream.send(n)},e}(zr),Jr=function(){function t(t,e,n,r,i,o){this.databaseInfo=t,this.queue=e,this.connection=n,this.credentials=r,this.serializer=i,this.initialBackoffDelay=o}return t.prototype.newPersistentWriteStream=function(t){return new Yr(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,t,this.initialBackoffDelay)},t.prototype.newPersistentWatchStream=function(t){return new Xr(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,t,this.initialBackoffDelay)},t.prototype.commit=function(t){var e=this,n={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.prototype.lookup=function(t){var e=this,n={documents:t.map(function(t){return e.serializer.toName(t)})};return this.invokeRPC("batchGet",n).then(function(n){var r=Z();n.forEach(function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)});var i=[];return t.forEach(function(t){var e=r.get(t);c(!!e,"Missing entity in write response for "+t),i.push(e)}),i})},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken(!1).then(function(r){return n.connection.invoke(t,e,r)})},t}(),Zr=function(){function t(t){this.datastore=t,this.readVersions=tt(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e=t.version;t instanceof ue&&(e=We.forDeletedDoc());var n=this.readVersions.get(t.key);if(null!==n){if(!e.equals(n))throw new Ht(Wt.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.lookup=function(t){var e=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(t).then(function(t){return t.forEach(function(t){return e.recordVersion(t)}),t})},t.prototype.write=function(t){if(this.committed)throw new Ht(Wt.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(t)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return e?en.updateTime(e):en.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.equals(We.forDeletedDoc()))throw new Ht(Wt.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?en.updateTime(e):en.exists(!0)},t.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,e){this.write(e.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new sn(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,We.forDeletedDoc())},t.prototype.commit=function(){var t=this,e=this.readVersions;return this.mutations.forEach(function(t){e=e.remove(t.key)}),e.isEmpty()?this.datastore.commit(this.mutations).then(function(){t.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},t}(),$r=function(){function t(t,e,n,r,i){this.databaseInfo=t,this.asyncQueue=e,this.localStore=n,this.datastore=r,this.onlineStateHandler=i,this.pendingWrites=[],this.lastBatchSeen=ir,this.listenTargets={},this.pendingTargetResponses={},this.accumulatedWatchChanges=[],this.watchStream=null,this.writeStream=null,this.watchStreamOnlineState=_n.Unknown,this.watchStreamFailures=0}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.setOnlineStateToHealthy=function(){this.updateAndBroadcastOnlineState(_n.Healthy)},t.prototype.setOnlineStateToUnknown=function(){this.watchStreamFailures=0,this.updateAndBroadcastOnlineState(_n.Unknown)},t.prototype.updateOnlineStateAfterFailure=function(){this.watchStreamOnlineState===_n.Healthy?this.setOnlineStateToUnknown():++this.watchStreamFailures>=2&&this.updateAndBroadcastOnlineState(_n.Failed)},t.prototype.updateAndBroadcastOnlineState=function(t){var e=this.watchStreamOnlineState!==t;this.watchStreamOnlineState=t,e&&this.onlineStateHandler(t)},t.prototype.isNetworkEnabled=function(){return c(null==this.watchStream==(null==this.writeStream),"WatchStream and WriteStream should both be null or non-null"),null!=this.watchStream},t.prototype.enableNetwork=function(){var t=this;return c(null==this.watchStream,"enableNetwork() called with non-null watchStream."),c(null==this.writeStream,"enableNetwork() called with non-null writeStream."),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)}),this.localStore.getLastStreamToken().then(function(e){return t.writeStream.lastStreamToken=e,t.shouldStartWatchStream()&&t.startWatchStream(),t.updateAndBroadcastOnlineState(_n.Unknown),t.fillWritePipeline()})},t.prototype.disableNetwork=function(){return this.updateAndBroadcastOnlineState(_n.Failed),this.watchStream.stop(),this.writeStream.stop(),this.cleanUpWatchStreamState(),this.cleanUpWriteStreamState(),this.writeStream=null,this.watchStream=null,Promise.resolve()},t.prototype.shutdown=function(){return o("RemoteStore","RemoteStore shutting down."),this.disableNetwork(),Promise.resolve(void 0)},t.prototype.listen=function(t){c(!f(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.isNetworkEnabled()&&this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){c(f(this.listenTargets,t),"unlisten called without assigned target ID!"),this.listenTargets[t],delete this.listenTargets[t],this.isNetworkEnabled()&&this.watchStream.isOpen()&&this.sendUnwatchRequest(t)},t.prototype.sendWatchRequest=function(t){this.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.recordPendingTargetRequest=function(t){this.pendingTargetResponses[t]=(this.pendingTargetResponses[t]||0)+1},t.prototype.startWatchStream=function(){c(this.shouldStartWatchStream(),"startWriteStream() called when shouldStartWatchStream() is false."),this.watchStream.start()},t.prototype.shouldStartWatchStream=function(){return this.isNetworkEnabled()&&!this.watchStream.isStarted()&&!m(this.listenTargets)},t.prototype.cleanUpWatchStreamState=function(){this.accumulatedWatchChanges=[],this.pendingTargetResponses={}},t.prototype.onWatchStreamOpen=function(){var t=this;return d(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),Promise.resolve()},t.prototype.onWatchStreamClose=function(t){return c(this.isNetworkEnabled(),"onWatchStreamClose() should only be called when the network is enabled"),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.updateOnlineStateAfterFailure(),this.startWatchStream()):this.setOnlineStateToUnknown(),Promise.resolve()},t.prototype.onWatchStreamChange=function(t,e){if(this.setOnlineStateToHealthy(),t instanceof Tn&&t.state===mn.Removed&&t.cause)return this.handleTargetError(t);if(this.accumulatedWatchChanges.push(t),!e.equals(We.MIN)&&e.compareTo(this.localStore.getLastRemoteSnapshotVersion())>=0){var n=this.accumulatedWatchChanges;return this.accumulatedWatchChanges=[],this.handleWatchChangeBatch(e,n)}return Promise.resolve()},t.prototype.handleWatchChangeBatch=function(t,e){var n=this,r=new En(t,this.listenTargets,this.pendingTargetResponses);r.addChanges(e);var i=r.createRemoteEvent();this.pendingTargetResponses=r.pendingTargetResponses;var o=[];return d(r.existenceFilters,function(e,r){var a=n.listenTargets[e];if(a){var s=a.query;if(s.isDocumentQuery())if(0===r.count){var u=new ae(s.path),h=new ue(u,t);i.addDocumentUpdate(h)}else c(1===r.count,"Single document existence filter with count: "+r.count);else{var l=n.localStore.remoteDocumentKeys(e).then(function(t){if(i.targetChanges[e]){var o=i.targetChanges[e].mapping;null!==o&&(o instanceof bn?t=o.applyToKeySet(t):(c(o instanceof vn,"Expected either reset or update mapping but got something else: "+o),t=o.documents))}if(t.size!==r.count){i.handleExistenceFilterMismatch(e);var u=new ze(s,e,a.purpose);n.listenTargets[e]=u,n.sendUnwatchRequest(e);var h=new ze(s,e,ye.ExistenceFilterMismatch);n.sendWatchRequest(h)}});o.push(l)}}}),Promise.all(o).then(function(){return d(i.targetChanges,function(t,e){if(e.resumeToken.length>0){var r=n.listenTargets[t];r&&(n.listenTargets[t]=r.update({resumeToken:e.resumeToken,snapshotVersion:e.snapshotVersion}))}}),n.syncEngine.applyRemoteEvent(i)})},t.prototype.handleTargetError=function(t){var e=this;c(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach(function(t){r=r.then(function(){return f(e.listenTargets,t)?(delete e.listenTargets[t],e.syncEngine.rejectListen(t,n)):Promise.resolve()})}),r},t.prototype.cleanUpWriteStreamState=function(){this.lastBatchSeen=ir,this.pendingWrites=[]},t.prototype.fillWritePipeline=function(){var t=this;return this.canWriteMutations()?this.localStore.nextMutationBatch(this.lastBatchSeen).then(function(e){return null===e?Promise.resolve():(t.commit(e),t.fillWritePipeline())}):Promise.resolve()},t.prototype.canWriteMutations=function(){return this.isNetworkEnabled()&&this.pendingWrites.length<10},t.prototype.outstandingWrites=function(){return this.pendingWrites.length},t.prototype.commit=function(t){c(this.canWriteMutations(),"commit called when batches can't be written"),this.lastBatchSeen=t.batchId,this.pendingWrites.push(t),this.shouldStartWriteStream()?this.startWriteStream():this.isNetworkEnabled()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.isNetworkEnabled()&&!this.writeStream.isStarted()&&this.pendingWrites.length>0},t.prototype.startWriteStream=function(){c(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},t.prototype.onWriteStreamOpen=function(){return this.writeStream.writeHandshake(),Promise.resolve()},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.pendingWrites;e<n.length;e++){var r=n[e];t.writeStream.writeMutations(r.mutations)}})},t.prototype.onMutationResult=function(t,e){var n=this;c(this.pendingWrites.length>0,"Got result for empty pending writes");var r=this.pendingWrites.shift(),i=ar.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){var e=this;if(c(this.isNetworkEnabled(),"onWriteStreamClose() should only be called when the network is enabled"),this.pendingWrites.length>0){c(!!t,"We have pending writes, but the write stream closed without an error");var n=void 0;return n=this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t),n.then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})}return Promise.resolve()},t.prototype.handleHandshakeError=function(t){return H(t.code)||t.code===Wt.ABORTED?(o("RemoteStore","RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=h(),this.localStore.setLastStreamToken(h())):Promise.resolve()},t.prototype.handleWriteError=function(t){var e=this;if(H(t.code)){var n=this.pendingWrites.shift();return this.writeStream.inhibitBackoff(),this.syncEngine.rejectFailedWrite(n.batchId,t).then(function(){return e.fillWritePipeline()})}return Promise.resolve()},t.prototype.createTransaction=function(){return new Zr(this.datastore)},t.prototype.handleUserChange=function(t){return o("RemoteStore","RemoteStore changing users: uid=",t.uid),this.disableNetwork(),this.enableNetwork()},t}(),ti=function(){function t(t,e,n,r){this.platform=t,this.databaseInfo=e,this.credentials=n,this.asyncQueue=r}return t.prototype.start=function(t){var e=this,n=new qr,r=new qr,i=!1;return this.credentials.setUserChangeListener(function(o){i?e.asyncQueue.schedule(function(){return e.handleUserChange(o)}):(i=!0,e.initializePersistence(t,r).then(function(){return e.initializeRest(o)}).then(n.resolve,n.reject))}),this.asyncQueue.schedule(function(){return n.promise}),r.promise},t.prototype.enableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.enableNetwork()})},t.prototype.initializePersistence=function(t,e){var n=this;return t?this.startIndexedDbPersistence().then(e.resolve).catch(function(t){return e.reject(t),n.canFallback(t)?(console.warn("Error enabling offline storage. Falling back to storage disabled: "+t),n.startMemoryPersistence()):Promise.reject(t)}):(e.resolve(),this.startMemoryPersistence())},t.prototype.canFallback=function(t){return t.code===Wt.FAILED_PRECONDITION||t.code===Wt.UNIMPLEMENTED},t.prototype.startIndexedDbPersistence=function(){this.garbageCollector=new Vr;var t=Or.buildStoragePrefix(this.databaseInfo),e=new Cn(this.databaseInfo.databaseId,{useProto3Json:!0});return this.persistence=new Or(t,e),this.persistence.start()},t.prototype.startMemoryPersistence=function(){return this.garbageCollector=new Wn,this.persistence=new Ur,this.persistence.start()},t.prototype.initializeRest=function(t){var e=this;return this.platform.loadConnection(this.databaseInfo).then(function(n){e.localStore=new Pr(e.persistence,t,e.garbageCollector);var r=e.platform.newSerializer(e.databaseInfo.databaseId),i=new Jr(e.databaseInfo,e.asyncQueue,n,e.credentials,r),o=function(t){e.eventMgr.onOnlineStateChanged(t)};return e.remoteStore=new $r(e.databaseInfo,e.asyncQueue,e.localStore,i,o),e.syncEngine=new rr(e.localStore,e.remoteStore,t),e.remoteStore.syncEngine=e.syncEngine,e.eventMgr=new Kn(e.syncEngine),e.localStore.start()}).then(function(){return e.remoteStore.start()})},t.prototype.handleUserChange=function(t){return this.asyncQueue.verifyOperationInProgress(),o("FirestoreClient","User Changed: "+t.uid),this.syncEngine.handleUserChange(t)},t.prototype.disableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.disableNetwork()})},t.prototype.shutdown=function(){var t=this;return this.asyncQueue.schedule(function(){return t.credentials.removeUserChangeListener(),t.remoteStore.shutdown()}).then(function(){return t.persistence.shutdown()})},t.prototype.listen=function(t,e,n){var r=this,i=new Qn(t,e,n);return this.asyncQueue.schedule(function(){return r.eventMgr.listen(i)}),i},t.prototype.unlisten=function(t){var e=this;this.asyncQueue.schedule(function(){return e.eventMgr.unlisten(t)})},t.prototype.write=function(t){var e=this,n=new qr;return this.asyncQueue.schedule(function(){return e.syncEngine.write(t,n)}),n.promise},t.prototype.databaseId=function(){return this.databaseInfo.databaseId},t.prototype.transaction=function(t){var e=this;return this.asyncQueue.schedule(function(){return Promise.resolve()}).then(function(){return e.syncEngine.runTransaction(t)})},t}(),ei=function(){function t(t){this.observer=t,this.muted=!1}return t.prototype.next=function(t){this.scheduleEvent(this.observer.next,t)},t.prototype.error=function(t){this.scheduleEvent(this.observer.error,t)},t.prototype.mute=function(){this.muted=!0},t.prototype.scheduleEvent=function(t,e){var n=this;this.muted||setTimeout(function(){n.muted||t(e)},0)},t}(),ni=function(){function t(){this.tail=Promise.resolve(),this.delayedOpCount=0,this.operationInProgress=!1}return t.prototype.schedule=function(t,e){var n=this;if(this.failure&&u("AsyncQueue is already failed: "+this.failure.message),(e||0)>0){this.delayedOpCount++;var r=new qr;return setTimeout(function(){n.scheduleInternal(function(){return t().then(function(t){r.resolve(t)})}),n.delayedOpCount--},e),r.promise}return this.scheduleInternal(t)},t.prototype.scheduleInternal=function(t){var e=this;return this.tail=this.tail.then(function(){return e.operationInProgress=!0,t().catch(function(t){throw e.failure=t,e.operationInProgress=!1,a("INTERNAL UNHANDLED ERROR: ",t.stack||t.message),t}).then(function(){e.operationInProgress=!1})}),this.tail},t.prototype.verifyOperationInProgress=function(){c(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(){return c(0===this.delayedOpCount,"draining doesn't handle delayed ops."),this.schedule(function(){return Promise.resolve(void 0)})},t}(),ri=function(){function t(t){this.uid=t}return t.prototype.isUnauthenticated=function(){return null==this.uid},t.prototype.toKey=function(){return this.isUnauthenticated()?"anonymous-user":"uid:"+this.uid},t.prototype.equals=function(t){return t.uid===this.uid},t.UNAUTHENTICATED=new t(null),t.GOOGLE_CREDENTIALS=new t("google-credentials-uid"),t.FIRST_PARTY=new t("first-party-uid"),t}(),ii=function(){function t(t,e){this.user=e,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+t}}return t}(),oi=function(){function t(){this.userListener=null}return t.prototype.getToken=function(t){return Promise.resolve(null)},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,t(ri.UNAUTHENTICATED)},t.prototype.removeUserChangeListener=function(){c(null!==this.userListener,"removeUserChangeListener() when no listener registered"),this.userListener=null},t}(),ai=function(){function t(t){var e=this;this.app=t,this.tokenListener=null,this.userCounter=0,this.userListener=null,this.tokenListener=function(){var t=e.getUser();e.currentUser&&t.equals(e.currentUser)||(e.currentUser=t,e.userCounter++,e.userListener&&e.userListener(e.currentUser))},this.userCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return t.prototype.getToken=function(t){var e=this;c(null!=this.tokenListener,"getToken cannot be called after listener removed.");var n=this.userCounter;return this.app.INTERNAL.getToken(t).then(function(t){if(e.userCounter!==n)throw new Ht(Wt.ABORTED,"getToken aborted due to uid change.");return t?(c("string"==typeof t.accessToken,"Invalid tokenData returned from getToken():"+t),new ii(t.accessToken,e.currentUser)):null})},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,this.currentUser&&t(this.currentUser)},t.prototype.removeUserChangeListener=function(){c(null!=this.tokenListener,"removeUserChangeListener() called twice"),c(null!==this.userListener,"removeUserChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.userListener=null},t.prototype.getUser=function(){"function"!=typeof this.app.INTERNAL.getUid&&u("This version of the Firestore SDK requires at least version 3.7.0 of firebase.js.");var t=this.app.INTERNAL.getUid();return c(null===t||"string"==typeof t,"Received invalid UID: "+t),new ri(t)},t}(),si=function(){function t(t){this.authClient=t}return t.prototype.getToken=function(t){var e=this;return new Promise(function(t,n){e.authClient.getAccessToken(function(e,r){e?n(e):t(new ii(r,ri.GOOGLE_CREDENTIALS))})})},t.prototype.setUserChangeListener=function(t){t(ri.GOOGLE_CREDENTIALS)},t.prototype.removeUserChangeListener=function(){},t}(),ui=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,this.type="FirstParty",this.user=ri.FIRST_PARTY,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return Object.defineProperty(t.prototype,"authHeaders",{get:function(){return{Authorization:this.gapi.auth.getAuthHeaderValueForFirstParty([]),"X-Goog-AuthUser":this.sessionIndex}},enumerable:!0,configurable:!0}),t}(),ci=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return t.prototype.getToken=function(t){return Promise.resolve(new ui(this.gapi,this.sessionIndex))},t.prototype.setUserChangeListener=function(t){t(ri.FIRST_PARTY)},t.prototype.removeUserChangeListener=function(){},t}(),hi=this&&this.__extends||function(){var t=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])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),li=function(){function t(){}return t.delete=function(){return fi.instance},t.serverTimestamp=function(){return pi.instance},t}(),fi=function(t){function e(){return t.call(this)||this}return hi(e,t),e.instance=new e,e}(li),pi=function(t){function e(){return t.call(this)||this}return hi(e,t),e.instance=new e,e}(li),di=l(li,"Use FieldValue.<field>() instead."),yi=/^__.*__$/,mi=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new on(t,this.data,this.fieldMask,e)):n.push(new rn(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new an(t,this.fieldTransforms)),n},t}(),gi=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[new on(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new an(t,this.fieldTransforms)),n},t}();!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.QueryValue=2]="QueryValue"}(Qr||(Qr={}));var vi=function(){function t(t,e,n,r,i){this.dataSource=t,this.methodName=e,this.path=n,void 0===r&&this.validatePath(),this.fieldTransforms=r||[],this.fieldMask=i||[]}return t.prototype.childContext=function(e){var n;n="number"==typeof e?null:null==this.path?null:this.path.child(e);var r=new t(this.dataSource,this.methodName,n,this.fieldTransforms,this.fieldMask);return"string"==typeof e?r.validatePathSegment(e):"object"==typeof e&&e instanceof oe&&r.validatePath(),r},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path+")";return new Ht(Wt.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t<this.path.length;t++)this.validatePathSegment(this.path.get(t))},t.prototype.validatePathSegment=function(t){if(this.isWrite()&&yi.test(t))throw this.createError("Document fields cannot begin and end with __")},t.prototype.isWrite=function(){return this.dataSource===Qr.Set||this.dataSource===Qr.Update},t}(),bi=function(){function t(t,e){this.databaseId=t,this.key=e}return t}(),wi=function(){function t(t){this.preConverter=t}return t.prototype.parseSetData=function(t,e,n){var r=this,i=new vi(Qr.Set,t,oe.EMPTY_PATH);Rt("Data must be an object, but it was:",i,e);var o=void 0!==n.merge&&n.merge,a=Ae.EMPTY;y(e,function(t,e){var n=new Pn(t).t,o=i.childContext(n);e=r.runPreConverter(e,o);var s=r.parseData(e,o);s&&(a=a.set(n,s))});var s=o?new Ye(i.fieldMask):null;return new mi(a,s,i.fieldTransforms)},t.prototype.parseUpdateData=function(t,e){var n=this,r=new vi(Qr.Update,t,oe.EMPTY_PATH);Rt("Data must be an object, but it was:",r,e);var i=[],o=Ae.EMPTY;y(e,function(e,a){var s=Mt(t,e),u=r.childContext(s);if((a=n.runPreConverter(a,u))instanceof fi)i.push(s);else{var c=n.parseData(a,u);null!=c&&(i.push(s),o=o.set(s,c))}});var a=new Ye(i);return new gi(o,a,r.fieldTransforms)},t.prototype.parseUpdateVarargs=function(t,e,n,r){var i=new vi(Qr.Update,t,oe.EMPTY_PATH),o=[Ot(t,e)],a=[n];if(r.length%2!=0)throw new Ht(Wt.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(Ot(t,r[s])),a.push(r[s+1]);for(var u=[],c=Ae.EMPTY,s=0;s<o.length;++s){var h=o[s],l=i.childContext(h),f=this.runPreConverter(a[s],l);if(f instanceof fi)u.push(h);else{var p=this.parseData(f,l);null!=p&&(u.push(h),c=c.set(h,p))}}var d=new Ye(u);return new gi(c,d,i.fieldTransforms)},t.prototype.parseQueryValue=function(t,e){var n=new vi(Qr.QueryValue,t,oe.EMPTY_PATH),r=this.parseData(e,n);return c(null!=r,"Parsed data should not be null."),c(0===n.fieldTransforms.length,"Field transforms should have been disallowed."),r},t.prototype.runPreConverter=function(t,e){try{return this.preConverter(t)}catch(t){var n=_t(t);throw e.createError(n)}},t.prototype.parseData=function(t,e){if((t=this.runPreConverter(t,e))instanceof Array){if(!e.path)throw e.createError("Nested arrays are not supported");return e.fieldMask.push(e.path),this.parseArray(t,e)}return kt(t)?(Rt("Unsupported field value:",e,t),this.parseObject(t,e)):(e.path&&e.fieldMask.push(e.path),this.parseScalarValue(t,e))},t.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.childContext(r));null==s&&(s=ge.INSTANCE),n.push(s),r++}return new ke(n)},t.prototype.parseObject=function(t,e){var n=this,r=new ce(L);return y(t,function(t,i){var o=n.parseData(i,e.childContext(t));null!=o&&(r=r.insert(t,o))}),new Ae(r)},t.prototype.parseScalarValue=function(t,e){if(null===t)return ge.INSTANCE;if("number"==typeof t)return G(t)?new we(t):new Ie(t);if("boolean"==typeof t)return ve.of(t);if("string"==typeof t)return new Te(t);if(t instanceof Date)return new Ee(Ge.fromDate(t));if(t instanceof Jt)return new De(t);if(t instanceof Xt)return new Ne(t);if(t instanceof bi)return new Ce(t.databaseId,t.key);if(t instanceof li){if(t instanceof fi)throw e.dataSource!==Qr.Update?e.createError("FieldValue.delete() can only be used with update()"):(c(null==e.path||e.path.length>0,"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"));if(t instanceof pi){if(e.dataSource!==Qr.Set&&e.dataSource!==Qr.Update)throw e.createError("FieldValue.serverTimestamp() can only be used with set() and update()");if(null===e.path)throw e.createError("FieldValue.serverTimestamp() is not currently supported inside arrays");return e.fieldTransforms.push(new Ze(e.path,Je.instance)),null}return u("Unknown FieldValue type: "+t)}throw e.createError("Unsupported field value: "+A(t))},t}(),Ii=this&&this.__extends||function(){var t=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])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ti="firestore.googleapis.com",Ei=!0,Si=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new Ht(Wt.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Ti,this.ssl=Ei}else S("settings","string","host",t.host),this.host=t.host,N("settings","boolean","ssl",t.ssl),this.ssl=p(t.ssl,Ei);O("settings",t,["host","ssl","credentials"]),N("settings","object","credentials",t.credentials),this.credentials=t.credentials}return t.prototype.equals=function(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials},t}(),Ni=function(){function t(){}return t}(),Ci=function(){function t(e){var n=this;this.INTERNAL={delete:function(){return n._?n._.shutdown():Promise.resolve()},disableNetwork:function(){return n._.disableNetwork()},enableNetwork:function(){return n._.enableNetwork()}};var r=new Ni;if("object"==typeof e.options){var i=e;r.firebaseApp=i,r.databaseId=t.databaseIdFromApp(i),r.persistenceKey=r.firebaseApp.name,r.credentials=new ai(i)}else{var o=e;if(!o.projectId)throw new Ht(Wt.INVALID_ARGUMENT,"Must provide projectId");r.databaseId=new te(o.projectId,o.database),r.persistenceKey="[DEFAULT]",r.credentials=new oi}r.settings=new Si({}),this.x=r,this.q=r.databaseId}return t.prototype.settings=function(t){if(v("Firestore.settings",arguments,1),T("Firestore.settings","object",1,t),f(t,"persistence"))throw new Ht(Wt.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var e=new Si(t);if(this._&&!this.x.settings.equals(e))throw new Ht(Wt.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");this.x.settings=e,void 0!==e.credentials&&(this.x.credentials=Ct(e.credentials))},t.prototype.enablePersistence=function(){if(this._)throw new Ht(Wt.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.");return this.configureClient(!0)},t.prototype.ensureClientConfigured=function(){return this._||this.configureClient(!1),this._},t.prototype.configureClient=function(t){var e=this;c(!!this.x.settings.host,"FirestoreSettings.host cannot be falsey"),c(!this._,"configureClient() called multiple times");var n=new Zt(this.x.databaseId,this.x.persistenceKey,this.x.settings.host,this.x.settings.ssl),r=function(t){if(t instanceof ki){var n=e.x.databaseId,r=t.firestore.x.databaseId;if(!r.equals(n))throw new Ht(Wt.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new bi(e.x.databaseId,t.Q)}return t};return this.z=new wi(r),this._=new ti(Qt.getPlatform(),n,this.x.credentials,new ni),this._.start(t)},t.databaseIdFromApp=function(t){var e=t.options;if(!f(e,"projectId")){if(f(e,"firestoreId"))throw new Ht(Wt.INVALID_ARGUMENT,'"firestoreId" is now specified as "projectId" in firebase.initializeApp.');throw new Ht(Wt.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.')}if(f(e,"firestoreOptions"))throw new Ht(Wt.INVALID_ARGUMENT,'"firestoreOptions" values are now specified with Firestore.settings()');var n=e.projectId;if(!n||"string"!=typeof n)throw new Ht(Wt.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new te(n)},Object.defineProperty(t.prototype,"app",{get:function(){if(!this.x.firebaseApp)throw new Ht(Wt.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this.x.firebaseApp},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("Firestore.collection",arguments,1),T("Firestore.collection","string",1,t),!t)throw new Ht(Wt.INVALID_ARGUMENT,"Must provide a non-empty collection path to collection()");return this.ensureClientConfigured(),new _i(re.fromString(t),this)},t.prototype.doc=function(t){if(v("Firestore.doc",arguments,1),T("Firestore.doc","string",1,t),!t)throw new Ht(Wt.INVALID_ARGUMENT,"Must provide a non-empty document path to doc()");return this.ensureClientConfigured(),ki.forPath(re.fromString(t),this)},t.prototype.runTransaction=function(t){var e=this;return v("Firestore.runTransaction",arguments,1),T("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction(function(n){return t(new Di(e,n))})},t.prototype.batch=function(){return this.ensureClientConfigured(),new Ai(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(r()){case Vt.DEBUG:return"debug";case Vt.ERROR:return"error";case Vt.SILENT:return"silent";default:return u("Unknown log level: "+r())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(v("Firestore.setLogLevel",arguments,1),T("Firestore.setLogLevel","string",1,t),t){case"debug":i(Vt.DEBUG);break;case"error":i(Vt.ERROR);break;case"silent":i(Vt.SILENT);break;default:throw new Ht(Wt.INVALID_ARGUMENT,"Invalid log level: "+t)}},t}(),Di=function(){function t(t,e){this.tt=t,this.et=e}return t.prototype.get=function(t){var e=this;v("Transaction.get",arguments,1);var n=Lt("Transaction.get",t,this.tt);return this.et.lookup([n.Q]).then(function(t){if(!t||1!==t.length)return u("Mismatch in docs returned from document lookup.");var r=t[0];return r instanceof ue?new Ri(e.tt,n.Q,null,!1):new Ri(e.tt,n.Q,r,!1)})},t.prototype.set=function(t,e,n){w("Transaction.set",arguments,2,3);var r=Lt("Transaction.set",t,this.tt);n=Pt("Transaction.set",n);var i=this.tt.z.parseSetData("Transaction.set",e,n);return this.et.set(r.Q,i),this},t.prototype.update=function(t,e,n){for(var r=[],i=3;i<arguments.length;i++)r[i-3]=arguments[i];var o,a;return"string"==typeof e||e instanceof Pn?(b("Transaction.update",arguments,3),o=Lt("Transaction.update",t,this.tt),a=this.tt.z.parseUpdateVarargs("Transaction.update",e,n,r)):(v("Transaction.update",arguments,2),o=Lt("Transaction.update",t,this.tt),a=this.tt.z.parseUpdateData("Transaction.update",e)),this.et.update(o.Q,a),this},t.prototype.delete=function(t){v("Transaction.delete",arguments,1);var e=Lt("Transaction.delete",t,this.tt);return this.et.delete(e.Q),this},t}(),Ai=function(){function t(t){this.tt=t,this.nt=[],this.rt=!1}return t.prototype.set=function(t,e,n){w("WriteBatch.set",arguments,2,3),this.verifyNotCommitted();var r=Lt("WriteBatch.set",t,this.tt);n=Pt("WriteBatch.set",n);var i=this.tt.z.parseSetData("WriteBatch.set",e,n);return this.nt=this.nt.concat(i.toMutations(r.Q,en.NONE)),this},t.prototype.update=function(t,e,n){for(var r=[],i=3;i<arguments.length;i++)r[i-3]=arguments[i];this.verifyNotCommitted();var o,a;return"string"==typeof e||e instanceof Pn?(b("WriteBatch.update",arguments,3),o=Lt("WriteBatch.update",t,this.tt),a=this.tt.z.parseUpdateVarargs("WriteBatch.update",e,n,r)):(v("WriteBatch.update",arguments,2),o=Lt("WriteBatch.update",t,this.tt),a=this.tt.z.parseUpdateData("WriteBatch.update",e)),this.nt=this.nt.concat(a.toMutations(o.Q,en.exists(!0))),this},t.prototype.delete=function(t){v("WriteBatch.delete",arguments,1),this.verifyNotCommitted();var e=Lt("WriteBatch.delete",t,this.tt);return this.nt=this.nt.concat(new sn(e.Q,en.NONE)),this},t.prototype.commit=function(){return this.verifyNotCommitted(),this.rt=!0,this.nt.length>0?this.tt.ensureClientConfigured().write(this.nt):Promise.resolve()},t.prototype.verifyNotCommitted=function(){if(this.rt)throw new Ht(Wt.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),ki=function(){function t(t,e){this.Q=t,this.firestore=e,this._=this.firestore.ensureClientConfigured()}return t.forPath=function(e,n){if(e.length%2!=0)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new t(new ae(e),n)},Object.defineProperty(t.prototype,"id",{get:function(){return this.Q.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new _i(this.Q.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this.Q.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("DocumentReference.collection",arguments,1),T("DocumentReference.collection","string",1,t),!t)throw new Ht(Wt.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=re.fromString(t);return new _i(this.Q.path.child(e),this.firestore)},t.prototype.set=function(t,e){w("DocumentReference.set",arguments,1,2),e=Pt("DocumentReference.set",e);var n=this.firestore.z.parseSetData("DocumentReference.set",t,e);return this._.write(n.toMutations(this.Q,en.NONE))},t.prototype.update=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i;return"string"==typeof t||t instanceof Pn?(b("DocumentReference.update",arguments,2),i=this.firestore.z.parseUpdateVarargs("DocumentReference.update",t,e,n)):(v("DocumentReference.update",arguments,1),i=this.firestore.z.parseUpdateData("DocumentReference.update",t)),this._.write(i.toMutations(this.Q,en.exists(!0)))},t.prototype.delete=function(){return v("DocumentReference.delete",arguments,0),this._.write([new sn(this.Q,en.NONE)])},t.prototype.onSnapshot=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];w("DocumentReference.onSnapshot",arguments,1,4);var n,r={includeMetadataChanges:!1},i=0;"object"!=typeof t[i]||Dt(t[i])||(r=t[i],O("DocumentReference.onSnapshot",r,["includeMetadataChanges"]),N("DocumentReference.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++);var o={includeDocumentMetadataChanges:r.includeMetadataChanges,includeQueryMetadataChanges:r.includeMetadataChanges};return Dt(t[i])?n=t[i]:(T("DocumentReference.onSnapshot","function",i,t[i]),E("DocumentReference.onSnapshot","function",i+1,t[i+1]),E("DocumentReference.onSnapshot","function",i+2,t[i+2]),n={next:t[i],error:t[i+1],complete:t[i+2]}),this.onSnapshotInternal(o,n)},t.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 ei({next:function(t){if(e.next){c(t.docs.size<=1,"Too many documents returned on a document query");var r=t.docs.get(n.Q);e.next(new Ri(n.firestore,n.Q,r,t.fromCache))}},error:r}),o=this._.listen(Pe.atPath(this.Q.path),i,t);return function(){i.mute(),n._.unlisten(o)}},t.prototype.get=function(){var t=this;return v("DocumentReference.get",arguments,0),new Promise(function(e,n){var r=t.onSnapshotInternal({includeQueryMetadataChanges:!0,includeDocumentMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(t){r(),!t.exists&&t.metadata.fromCache?n(new Ht(Wt.ABORTED,"Failed to get document because the client is offline.")):e(t)},error:n})})},t}(),Ri=function(){function t(t,e,n,r){this.tt=t,this.Q=e,this.it=n,this.ot=r}return t.prototype.data=function(){if(v("DocumentSnapshot.data",arguments,0),!this.it)throw new Ht(Wt.NOT_FOUND,"This document doesn't exist. Check doc.exists to make sure the document exists before calling doc.data().");return this.convertObject(this.it.data)},t.prototype.get=function(t){if(v("DocumentSnapshot.get",arguments,1),!this.it)throw new Ht(Wt.NOT_FOUND,"This document doesn't exist. Check doc.exists to make sure the document exists before calling doc.get().");var e=this.it.data.field(Ot("DocumentSnapshot.get",t));return void 0===e?void 0:this.convertValue(e)},Object.defineProperty(t.prototype,"id",{get:function(){return this.Q.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ref",{get:function(){return new ki(this.Q,this.tt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"exists",{get:function(){return null!==this.it},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"metadata",{get:function(){return{hasPendingWrites:null!==this.it&&this.it.hasLocalMutations,fromCache:this.ot}},enumerable:!0,configurable:!0}),t.prototype.convertObject=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.convertValue(r)}),n},t.prototype.convertValue=function(t){if(t instanceof Ae)return this.convertObject(t);if(t instanceof ke)return this.convertArray(t);if(t instanceof Ce){var e=t.value(),n=this.tt.ensureClientConfigured().databaseId();return t.databaseId.equals(n)||a("Document "+this.Q.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 ("+n.projectId+"/"+n.database+") instead."),new ki(e,this.tt)}return t.value()},t.prototype.convertArray=function(t){var e=this;return t.internalValue.map(function(t){return e.convertValue(t)})},t}(),Oi=function(){function t(t,e){this.at=t,this.firestore=e}return t.prototype.where=function(e,n,r){v("Query.where",arguments,3),T("Query.where","string",2,n),R("Query.where",3,r);var i,o=Ot("Query.where",e);if(o.isKeyField())if("string"==typeof r){if(-1!==r.indexOf("/"))throw new Ht(Wt.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a valid document ID if the first parameter is FieldPath.documentId(), but it contains a slash.");if(""===r)throw new Ht(Wt.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a valid document ID if the first parameter is FieldPath.documentId(), but it was an empty string.");var a=this.at.path.child(new re([r]));c(a.length%2==0,"Path should be a document key"),i=new Ce(this.firestore.q,new ae(a))}else{if(!(r instanceof ki))throw new Ht(Wt.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a string or a DocumentReference if the first parameter is FieldPath.documentId(), but it was: "+A(r)+".");var s=r;i=new Ce(this.firestore.q,s.Q)}else i=this.firestore.z.parseQueryValue("Query.where",r);var u=W(o,Le.fromString(n),i);return this.validateNewFilter(u),new t(this.at.addFilter(u),this.firestore)},t.prototype.orderBy=function(e,n){w("Query.orderBy",arguments,1,2),E("Query.orderBy","string",2,n);var r;if(void 0===n||"asc"===n)r=Fe.ASCENDING;else{if("desc"!==n)throw new Ht(Wt.INVALID_ARGUMENT,"Function Query.orderBy() has unknown direction '"+n+"', expected 'asc' or 'desc'.");r=Fe.DESCENDING}if(null!==this.at.startAt)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");if(null!==this.at.endAt)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");var i=Ot("Query.orderBy",e),o=new qe(i,r);return this.validateNewOrderBy(o),new t(this.at.addOrderBy(o),this.firestore)},t.prototype.limit=function(e){if(v("Query.limit",arguments,1),T("Query.limit","number",1,e),e<=0)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid Query. Query limit ("+e+") is invalid. Limit must be positive.");return new t(this.at.withLimit(e),this.firestore)},t.prototype.startAt=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];b("Query.startAt",arguments,1);var i=this.boundFromDocOrFields("Query.startAt",e,n,!0);return new t(this.at.withStartAt(i),this.firestore)},t.prototype.startAfter=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];b("Query.startAfter",arguments,1);var i=this.boundFromDocOrFields("Query.startAfter",e,n,!1);return new t(this.at.withStartAt(i),this.firestore)},t.prototype.endBefore=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];b("Query.endBefore",arguments,1);var i=this.boundFromDocOrFields("Query.endBefore",e,n,!0);return new t(this.at.withEndAt(i),this.firestore)},t.prototype.endAt=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];b("Query.endAt",arguments,1);var i=this.boundFromDocOrFields("Query.endAt",e,n,!1);return new t(this.at.withEndAt(i),this.firestore)},t.prototype.boundFromDocOrFields=function(t,e,n,r){if(R(t,1,e),e instanceof Ri){if(n.length>0)throw new Ht(Wt.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var i=e;if(!i.exists)throw new Ht(Wt.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,i.it,r)}var o=[e].concat(n);return this.boundFromFields(t,o,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],i=0,o=this.at.orderBy;i<o.length;i++){var a=o[i];if(a.field.isKeyField())r.push(new Ce(this.firestore.q,e.key));else{var s=e.field(a.field);if(void 0===s){var u=a.field.canonicalString();throw new Ht(Wt.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 Ve(r,n)},t.prototype.boundFromFields=function(t,e,n){var r=this.at.explicitOrderBy;if(e.length>r.length)throw new Ht(Wt.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 Ht(Wt.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in "+t+"(), but got a "+typeof a);if(-1!==a.indexOf("/"))throw new Ht(Wt.INVALID_ARGUMENT,"Invalid query. Document ID '"+a+"' contains a slash in "+t+"()");var s=new ae(this.at.path.child(a));i.push(new Ce(this.firestore.q,s))}else{var u=this.firestore.z.parseQueryValue(t,a);i.push(u)}}return new Ve(i,n)},t.prototype.onSnapshot=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];w("Query.onSnapshot",arguments,1,4);var n,r={},i=0;return"object"!=typeof t[i]||Dt(t[i])||(r=t[i],O("Query.onSnapshot",r,["includeQueryMetadataChanges","includeDocumentMetadataChanges"]),N("Query.onSnapshot","boolean","includeDocumentMetadataChanges",r.includeDocumentMetadataChanges),N("Query.onSnapshot","boolean","includeQueryMetadataChanges",r.includeQueryMetadataChanges),i++),Dt(t[i])?n=t[i]:(T("Query.onSnapshot","function",i,t[i]),E("Query.onSnapshot","function",i+1,t[i+1]),E("Query.onSnapshot","function",i+2,t[i+2]),n={next:t[i],error:t[i+1],complete:t[i+2]}),this.onSnapshotInternal(r,n)},t.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 ei({next:function(t){e.next&&e.next(new Mi(n.firestore,n.at,t))},error:r}),o=this.firestore.ensureClientConfigured(),a=o.listen(this.at,i,t);return function(){i.mute(),o.unlisten(a)}},t.prototype.get=function(){var t=this;return v("Query.get",arguments,0),new Promise(function(e,n){var r=t.onSnapshotInternal({includeDocumentMetadataChanges:!1,includeQueryMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(t){r(),e(t)},error:n})})},t.prototype.validateNewFilter=function(t){if(t instanceof xe&&t.isInequality()){var e=this.at.getInequalityFilterField();if(null!==e&&!e.equals(t.field))throw new Ht(Wt.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+e+"' and '"+t.field+"'");var n=this.at.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(t.field,n)}},t.prototype.validateNewOrderBy=function(t){if(null===this.at.getFirstOrderByField()){var e=this.at.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.equals(t))throw new Ht(Wt.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t+"' and so you must also use '"+t+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e+"' instead.")},t}(),Mi=function(){function t(t,e,n){this.tt=t,this.st=e,this.ut=n,this.ct=null,this.metadata={fromCache:n.fromCache,hasPendingWrites:n.hasPendingWrites}}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach(function(e){return t.push(e)}),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this.ut.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this.ut.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;w("QuerySnapshot.forEach",arguments,1,2),T("QuerySnapshot.forEach","function",1,t),this.ut.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new Oi(this.st,this.tt)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"docChanges",{get:function(){return this.ct||(this.ct=xt(this.tt,this.ut)),this.ct},enumerable:!0,configurable:!0}),t.prototype.convertToDocumentImpl=function(t){return new Ri(this.tt,t.key,t,this.metadata.fromCache)},t}(),_i=function(t){function e(e,n){var r=t.call(this,Pe.atPath(e),n)||this;if(e.length%2!=1)throw new Ht(Wt.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.canonicalString()+" has "+e.length);return r}return Ii(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this.at.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this.at.path.popLast();return t.isEmpty()?null:new ki(new ae(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this.at.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(w("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=zt.newId()),T("CollectionReference.doc","string",1,t),""===t)throw new Ht(Wt.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=re.fromString(t);return ki.forPath(this.at.path.child(e),this.firestore)},e.prototype.add=function(t){v("CollectionReference.add",arguments,1),T("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(Oi),Pi=l(Ci,"Use firebase.firestore() instead."),Li=l(Di,"Use firebase.firestore().runTransaction() instead."),xi=l(Ai,"Use firebase.firestore().batch() instead."),Bi=l(ki,"Use firebase.firestore().doc() instead."),Ui=l(Ri),Fi=l(Oi),Vi=l(Mi),qi=l(_i,"Use firebase.firestore().collection() instead."),ji={Firestore:Pi,GeoPoint:Jt,Blob:Yt,Transaction:Li,WriteBatch:xi,DocumentReference:Bi,DocumentSnapshot:Ui,Query:Fi,QuerySnapshot:Vi,CollectionReference:qi,FieldPath:Pn,FieldValue:di,setLogLevel:Ci.setLogLevel};e.registerFirestore=Ft,Ft(qt.default)},115:function(module,exports,__webpack_require__){(function(){function l(t){return"string"==typeof t}function aa(){}function ba(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 n(t){return"array"==ba(t)}function ca(t){var e=ba(t);return"array"==e||"object"==e&&"number"==typeof t.length}function da(t){return"function"==ba(t)}function p(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}function fa(t,e,n){return t.call.apply(t.bind,arguments)}function ha(t,e,n){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),t.apply(e,n)}}return function(){return t.apply(e,arguments)}}function r(t,e,n){return r=Function.prototype.bind&&-1!=(""+Function.prototype.bind).indexOf("native code")?fa:ha,r.apply(null,arguments)}function ia(t,e){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function u(t,e){function n(){}n.prototype=e.prototype,t.L=e.prototype,t.prototype=new n,t.prototype.constructor=t,t.Bb=function(t,n,r){for(var i=Array(arguments.length-2),o=2;o<arguments.length;o++)i[o-2]=arguments[o];return e.prototype[n].apply(t,i)}}function ja(t){if(Error.captureStackTrace)Error.captureStackTrace(this,ja);else{var e=Error().stack;e&&(this.stack=e)}t&&(this.message=t+"")}function ka(t,e){for(var n=t.split("%s"),r="",i=Array.prototype.slice.call(arguments,1);i.length&&1<n.length;)r+=n.shift()+i.shift();return r+n.join("%s")}function ma(t,e){return t<e?-1:t>e?1:0}function na(t,e){e.unshift(t),ja.call(this,ka.apply(null,e)),e.shift()}function oa(t,e){throw new na("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this),this.i=this.i,this.v=this.v}function ua(t){t:{for(var e=va,n=t.length,r=l(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 0>e?null:l(t)?t.charAt(e):t[e]}function wa(t){if(!n(t))for(var e=t.length-1;0<=e;e--)delete t[e];t.length=0}function xa(t){return Array.prototype.concat.apply([],arguments)}function ya(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 y(t){return-1!=x.indexOf(t)}function Ba(t,e,n){for(var r in t)e.call(n,t[r],r,t)}function Ca(t){var e,n=[],r=0;for(e in t)n[r++]=t[e];return n}function Da(t){var e,n=[],r=0;for(e in t)n[r++]=e;return n}function Ea(t){var e,n={};for(e in t)n[e]=t[e];return n}function Ga(t,e){for(var n,r,i=1;i<arguments.length;i++){r=arguments[i];for(n in r)t[n]=r[n];for(var o=0;o<Fa.length;o++)n=Fa[o],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function Ha(t){return Ha[" "](t),t}function Ia(t,e){var n=Ja;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=e(t)}function Oa(){var t=k.document;return t?t.documentMode:void 0}function Ua(t){return Ia(t,function(){for(var e=0,n=la(Pa+"").split("."),r=la(t+"").split("."),i=Math.max(n.length,r.length),o=0;0==e&&o<i;o++){var a=n[o]||"",s=r[o]||"";do{if(a=/(\d*)(\D*)(.*)/.exec(a)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],0==a[0].length&&0==s[0].length)break;e=ma(0==a[1].length?0:parseInt(a[1],10),0==s[1].length?0:parseInt(s[1],10))||ma(0==a[2].length,0==s[2].length)||ma(a[2],s[2]),a=a[3],s=s[3]}while(0==e)}return 0<=e})}function A(t,e){this.type=t,this.a=this.target=e,this.Qa=!0}function ab(t,e){if(A.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[0]:null;if(this.target=t.target||t.srcElement,this.a=e,e=t.relatedTarget){if(Ma){t:{try{Ha(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,null===r?(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.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.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=l(t.pointerType)?t.pointerType:bb[t.pointerType]||"",this.c=t,t.defaultPrevented&&this.b()}}function db(t){return!(!t||!t[cb])}function fb(t,e,n,r,i){this.listener=t,this.a=null,this.src=e,this.type=n,this.capture=!!r,this.da=i,this.key=++eb,this.X=this.ba=!1}function gb(t){t.X=!0,t.listener=null,t.a=null,t.src=null,t.da=null}function hb(t){this.src=t,this.a={},this.b=0}function ib(t,e,n,r,i,o){var a=""+e;(e=t.a[a])||(e=t.a[a]=[],t.b++);var s=jb(e,n,i,o);return-1<s?(t=e[s],r||(t.ba=!1)):(t=new fb(n,t.src,a,!!i,o),t.ba=r,e.push(t)),t}function kb(t,e){var n=e.type;if(n in t.a){var r,i=t.a[n],o=sa(i,e);(r=0<=o)&&Array.prototype.splice.call(i,o,1),r&&(gb(e),0==t.a[n].length&&(delete t.a[n],t.b--))}}function lb(t,e,n,r,i){return t=t.a[""+e],e=-1,t&&(e=jb(t,n,r,i)),-1<e?t[e]:null}function jb(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}function pb(t,e,r,i,o){if(i&&i.once)return qb(t,e,r,i,o);if(n(e)){for(var a=0;a<e.length;a++)pb(t,e[a],r,i,o);return null}return r=rb(r),db(t)?t.$(e,r,p(i)?!!i.capture:!!i,o):sb(t,e,r,!1,i,o)}function sb(t,e,n,r,i,o){if(!e)throw Error("Invalid event type");var a=p(i)?!!i.capture:!!i,s=tb(t);if(s||(t[mb]=s=new hb(t)),n=ib(s,e,n,r,a,o),n.a)return n;if(r=ub(),n.a=r,r.src=t,r.listener=n,t.addEventListener)$a||(i=a),void 0===i&&(i=!1),t.addEventListener(""+e,r,i);else{if(!t.attachEvent)throw Error("addEventListener and attachEvent are unavailable.");t.attachEvent(vb(""+e),r)}return ob++,n}function ub(){var t=wb,e=Ya?function(n){return t.call(e.src,e.listener,n)}:function(n){if(!(n=t.call(e.src,e.listener,n)))return n};return e}function qb(t,e,r,i,o){if(n(e)){for(var a=0;a<e.length;a++)qb(t,e[a],r,i,o);return null}return r=rb(r),db(t)?t.Ia(e,r,p(i)?!!i.capture:!!i,o):sb(t,e,r,!0,i,o)}function xb(t,e,r,i,o){if(n(e))for(var a=0;a<e.length;a++)xb(t,e[a],r,i,o);else i=p(i)?!!i.capture:!!i,r=rb(r),db(t)?t.xa(e,r,i,o):t&&(t=tb(t))&&(e=lb(t,e,r,i,o))&&yb(e)}function yb(t){if("number"!=typeof t&&t&&!t.X){var e=t.src;if(db(e))kb(e.c,t);else{var n=t.type,r=t.a;e.removeEventListener?e.removeEventListener(n,r,t.capture):e.detachEvent&&e.detachEvent(vb(n),r),ob--,(n=tb(e))?(kb(n,t),0==n.b&&(n.src=null,e[mb]=null)):gb(t)}}}function vb(t){return t in nb?nb[t]:nb[t]="on"+t}function zb(t,e,n,r){var i=!0;if((t=tb(t))&&(e=t.a[""+e]))for(e=e.concat(),t=0;t<e.length;t++){var o=e[t];o&&o.capture==n&&!o.X&&(o=Ab(o,r),i=i&&!1!==o)}return i}function Ab(t,e){var n=t.listener,r=t.da||t.src;return t.ba&&yb(t),n.call(r,e)}function wb(t,e){if(t.X)return!0;if(!Ya){if(!e)t:{e=["window","event"];for(var n=k,r=0;r<e.length;r++)if(null==(n=n[e[r]])){e=null;break t}e=n}if(r=e,e=new ab(r,this),n=!0,!(0>r.keyCode||void 0!=r.returnValue)){t:{var i=!1;if(0==r.keyCode)try{r.keyCode=-1;break t}catch(t){i=!0}(i||void 0==r.returnValue)&&(r.returnValue=!0)}for(r=[],i=e.a;i;i=i.parentNode)r.push(i);for(t=t.type,i=r.length-1;0<=i;i--){e.a=r[i];var o=zb(r[i],t,!0,e);n=n&&o}for(i=0;i<r.length;i++)e.a=r[i],o=zb(r[i],t,!1,e),n=n&&o}return n}return Ab(t,new ab(e,this))}function tb(t){return t=t[mb],t instanceof hb?t:null}function rb(t){return da(t)?t:(t[Bb]||(t[Bb]=function(e){return t.handleEvent(e)}),t[Bb])}function B(){w.call(this),this.c=new hb(this),this.P=this,this.J=null}function Cb(t,e,n,r){if(!(e=t.c.a[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.ba&&kb(t.c,a),i=!1!==s.call(u,r)&&i}}return i&&0!=r.Qa}function Db(t){return!/^\s*$/.test(t)&&/^[\],:{}\s\u2028\u2029]*$/.test(t.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,""))}function Eb(a){if(a+="",Db(a))try{return eval("("+a+")")}catch(t){}throw Error("Invalid JSON string: "+a)}function Fb(t){var e=[];return Gb(new Hb,t,e),e.join("")}function Hb(){}function Gb(t,e,r){if(null==e)r.push("null");else{if("object"==typeof e){if(n(e)){var i=e;e=i.length,r.push("[");for(var o="",a=0;a<e;a++)r.push(o),Gb(t,i[a],r),o=",";return void r.push("]")}if(!(e instanceof String||e instanceof Number||e instanceof Boolean)){r.push("{"),o="";for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&"function"!=typeof(a=e[i])&&(r.push(o),Ib(i,r),r.push(":"),Gb(t,a,r),o=",");return void r.push("}")}e=e.valueOf()}switch(typeof e){case"string":Ib(e,r);break;case"number":r.push(isFinite(e)&&!isNaN(e)?e+"":"null");break;case"boolean":r.push(e+"");break;case"function":r.push("null");break;default:throw Error("Unknown type: "+typeof e)}}}function Ib(t,e){e.push('"',t.replace(Lb,function(t){var e=Jb[t];return e||(e="\\u"+(65536|t.charCodeAt(0)).toString(16).substr(1),Jb[t]=e),e}),'"')}function Mb(t,e,n){this.f=n,this.c=t,this.g=e,this.b=0,this.a=null}function Ob(){var t=Pb,e=null;return t.a&&(e=t.a,t.a=t.a.next,t.a||(t.b=null),e.next=null),e}function Nb(){this.next=this.b=this.a=null}function Qb(t){k.setTimeout(function(){throw t},0)}function Sb(){var t=k.MessageChannel;if(void 0===t&&"undefined"!=typeof window&&window.postMessage&&window.addEventListener&&!y("Presto")&&(t=function(){var t=document.createElement("IFRAME");t.style.display="none",t.src="",document.documentElement.appendChild(t);var e=t.contentWindow;t=e.document,t.open(),t.write(""),t.close();var n="callImmediate"+Math.random(),i="file:"==e.location.protocol?"*":e.location.protocol+"//"+e.location.host;t=r(function(t){"*"!=i&&t.origin!=i||t.data!=n||this.port1.onmessage()},this),e.addEventListener("message",t,!1),this.port1={},this.port2={postMessage:function(){e.postMessage(n,i)}}}),void 0!==t&&!y("Trident")&&!y("MSIE")){var e=new t,n={},i=n;return e.port1.onmessage=function(){if(void 0!==n.next){n=n.next;var t=n.Ca;n.Ca=null,t()}},function(t){i.next={Ca:t},i=i.next,e.port2.postMessage(0)}}return"undefined"!=typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(t){var e=document.createElement("SCRIPT");e.onreadystatechange=function(){e.onreadystatechange=null,e.parentNode.removeChild(e),e=null,t(),t=null},document.documentElement.appendChild(e)}:function(t){k.setTimeout(t,0)}}function Ub(){if(-1!=(k.Promise+"").indexOf("[native code]")){var t=k.Promise.resolve(void 0);Tb=function(){t.then(Vb)}}else Tb=function(){var t=Vb;!da(k.setImmediate)||k.Window&&k.Window.prototype&&!y("Edge")&&k.Window.prototype.setImmediate==k.setImmediate?(Rb||(Rb=Sb()),Rb(t)):k.setImmediate(t)}}function Vb(){for(var t;t=Ob();){try{t.a.call(t.b)}catch(t){Qb(t)}C.g(t),C.b<C.f&&(C.b++,t.next=C.a,C.a=t)}Wb=!1}function Xb(e,n){B.call(this),this.b=e||1,this.a=n||k,this.f=r(this.jb,this),this.g=t()}function Yb(t){t.Z=!1,t.K&&(t.a.clearTimeout(t.K),t.K=null)}function Zb(t,e,n){if(da(t))n&&(t=r(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=r(t.handleEvent,t)}return 2147483647<+e?-1:k.setTimeout(t,e||0)}function $b(t,e,n){w.call(this),this.f=null!=n?r(t,n):t,this.c=e,this.b=r(this.cb,this),this.a=[]}function ac(t){t.W=Zb(t.b,t.c),t.f.apply(null,t.a)}function D(t){w.call(this),this.b=t,this.a={}}function cc(t){Ba(t.a,function(t,e){this.a.hasOwnProperty(e)&&yb(t)},t),t.a={}}function dc(t,e,n,r,i){this.reset(t,e,n,r,i)}function fc(t){this.f=t,this.b=this.c=this.a=null}function E(t,e){this.name=t,this.value=e}function lc(t){return t.c?t.c:t.a?lc(t.a):(oa("Root logger has no level set."),null)}function F(t,e){t.log(gc,e,void 0)}function G(t,e){t.log(hc,e,void 0)}function oc(t){nc||(nc=new fc(""),mc[""]=nc,nc.c=jc);var e;if(!(e=mc[t])){e=new fc(t);var n=t.lastIndexOf("."),r=t.substr(n+1);n=oc(t.substr(0,n)),n.b||(n.b={}),n.b[r]=e,e.a=n,mc[t]=e}return e}function pc(t,e){t&&t.log(ic,e,void 0)}function H(t,e){t&&t.log(kc,e,void 0)}function qc(){this.a=oc("goog.labs.net.webChannel.WebChannelDebug")}function rc(t,e,r,i){if(r)try{var o=JSON.parse(r);if(o)for(var a=0;a<o.length;a++)if(n(o[a])){var s=o[a];if(!(2>s.length)){var u=s[1];if(n(u)&&!(1>u.length)){var c=u[0];if("noop"!=c&&"stop"!=c&&"close"!=c)for(var h=1;h<u.length;h++)u[h]=""}}}var l=Fb(o)}catch(e){I(t,"Exception parsing expected JS array - probably was not JS"),l=r}else l=null;I(t,"XMLHTTP TEXT ("+e+"): "+l+(i?" "+i:""))}function sc(t,e,n){(t=t.a)&&F(t,(n||"Exception")+e)}function I(t,e){pc(t.a,e)}function tc(t){A.call(this,"serverreachability",t)}function uc(){J.dispatchEvent(new tc(J))}function vc(t){A.call(this,"statevent",t)}function K(){J.dispatchEvent(new vc(J))}function wc(t){A.call(this,"timingevent",t)}function xc(t,e){if(!da(t))throw Error("Fn must not be null and must be a function");return k.setTimeout(function(){t()},e)}function Ac(){}function Bc(t){var e;return(e=t.a)||(e={},Cc(t)&&(e[0]=!0,e[1]=!0),e=t.a=e),e}function Ec(){}function Fc(t){return(t=Cc(t))?new ActiveXObject(t):new XMLHttpRequest}function Cc(t){if(!t.b&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],n=0;n<4;n++){var r=e[n];try{return new ActiveXObject(r),t.b=r}catch(t){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed")}return t.b}function L(t,e,n,r,i){this.m=t,this.b=e,this.f=r,this.S=i||1,this.M=new D(this),this.P=Gc,t=this.F=new Xb,t.b=Hc,t.K&&t.Z?(Yb(t),t.start()):t.K&&Yb(t),this.h=null,this.c=!1,this.a=this.B=this.g=this.l=this.I=this.H=this.T=this.o=null,this.C=0,this.i=this.j=null,this.v=-1,this.s=!1,this.N=0,this.G=null,this.J=!1}function Ic(t,e){switch(t){case 0:return"Non-200 return code ("+e+")";case 1:return"XMLHTTP failure (no data)";case 2:return"HttpConnection timeout";default:return"Unknown error"}}function Lc(t,e,n){t.I=1,t.l=Mc(M(e)),t.B=n,t.J=!0,Nc(t,null)}function Oc(t,e,n,r){t.I=1,t.l=Mc(M(e)),t.B=null,t.J=n,Nc(t,r)}function Nc(e,n){e.H=t(),Pc(e),e.g=M(e.l),Qc(e.g,"t",e.S),e.C=0,e.a=e.m.ra(e.m.fa()?n:null),0<e.N&&(e.G=new $b(r(e.Ra,e,e.a),e.N)),e.M.$(e.a,"readystatechange",e.gb),n=e.h?Ea(e.h):{},e.B?(e.j||(e.j="POST"),n["Content-Type"]="application/x-www-form-urlencoded",e.a.ta(e.g,e.j,e.B,n)):(e.j="GET",e.a.ta(e.g,e.j,null,n)),uc();var i=e.B;if(i){n="",i=i.split("&");for(var o=0;o<i.length;o++){var a=i[o].split("=");if(1<a.length){var s=a[0];a=a[1];var u=s.split("_");n=2<=u.length&&"type"==u[1]?n+(s+"=")+a+"&":n+(s+"=redacted&")}}}else n=null;I(e.b,"XMLHTTP REQ ("+e.f+") [attempt "+e.S+"]: "+e.j+"\n"+e.g+"\n"+n)}function Sc(t,e,n){for(var r=!0;!t.s&&t.C<n.length;){var i=Wc(t,n);if(i==Kc){4==e&&(t.i=4,K(),r=!1),rc(t.b,t.f,null,"[Incomplete Response]");break}if(i==Jc){t.i=4,K(),rc(t.b,t.f,n,"[Invalid Chunk]"),r=!1;break}rc(t.b,t.f,i,null),Tc(t,i)}4==e&&0==n.length&&(t.i=1,K(),r=!1),t.c=t.c&&r,r||(rc(t.b,t.f,n,"[Invalid Chunked Response]"),Uc(t),Vc(t))}function Wc(t,e){var n=t.C,r=e.indexOf("\n",n);return-1==r?Kc:(n=+e.substring(n,r),isNaN(n)?Jc:(r+=1)+n>e.length?Kc:(e=e.substr(r,n),t.C=r+n,e))}function Pc(e){e.T=t()+e.P,Xc(e,e.P)}function Xc(t,e){if(null!=t.o)throw Error("WatchDog timer not null");t.o=xc(r(t.eb,t),e)}function Rc(t){t.o&&(k.clearTimeout(t.o),t.o=null)}function Vc(t){t.m.Ka()||t.s||t.m.wa(t)}function Uc(t){Rc(t);var e=t.G;e&&"function"==typeof e.Y&&e.Y(),t.G=null,Yb(t.F),cc(t.M),t.a&&(e=t.a,t.a=null,e.abort(),e.Y())}function Tc(t,e){try{t.m.Na(t,e),uc()}catch(e){sc(t.b,e,"Error in httprequest callback")}}function Yc(t){if(t.A&&"function"==typeof t.A)return t.A();if(l(t))return t.split("");if(ca(t)){for(var e=[],n=t.length,r=0;r<n;r++)e.push(t[r]);return e}return Ca(t)}function Zc(t,e){if(t.forEach&&"function"==typeof t.forEach)t.forEach(e,void 0);else if(ca(t)||l(t))ta(t,e,void 0);else{if(t.O&&"function"==typeof t.O)var n=t.O();else if(t.A&&"function"==typeof t.A)n=void 0;else if(ca(t)||l(t)){n=[];for(var r=t.length,i=0;i<r;i++)n.push(i)}else n=Da(t);r=Yc(t),i=r.length;for(var o=0;o<i;o++)e.call(void 0,r[o],n&&n[o],t)}}function O(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){t instanceof O?(n=t.O(),r=t.A()):(n=Da(t),r=Ca(t));for(var i=0;i<n.length;i++)this.set(n[i],r[i])}}function ad(t){t.b={},t.a.length=0,t.c=0}function bd(t,e){return!!P(t.b,e)&&(delete t.b[e],t.c--,t.a.length>2*t.c&&$c(t),!0)}function $c(t){if(t.c!=t.a.length){for(var e=0,n=0;e<t.a.length;){var r=t.a[e];P(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;)r=t.a[e],P(i,r)||(t.a[n++]=r,i[r]=1),e++;t.a.length=n}}function P(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function dd(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," ")):"")}}}function Q(t,e){this.b=this.j=this.f="",this.i=null,this.g=this.a="",this.h=!1;var n;t instanceof Q?(this.h=void 0!==e?e:t.h,ed(this,t.f),this.j=t.j,fd(this,t.b),gd(this,t.i),this.a=t.a,hd(this,id(t.c)),this.g=t.g):t&&(n=(t+"").match(cd))?(this.h=!!e,ed(this,n[1]||"",!0),this.j=jd(n[2]||""),fd(this,n[3]||"",!0),gd(this,n[4]),this.a=jd(n[5]||"",!0),hd(this,n[6]||"",!0),this.g=jd(n[7]||"")):(this.h=!!e,this.c=new kd(null,0,this.h))}function M(t){return new Q(t)}function ed(t,e,n){t.f=n?jd(e,!0):e,t.f&&(t.f=t.f.replace(/:$/,""))}function fd(t,e,n){t.b=n?jd(e,!0):e}function gd(t,e){if(e){if(e=+e,isNaN(e)||0>e)throw Error("Bad port number "+e);t.i=e}else t.i=null}function hd(t,e,n){e instanceof kd?(t.c=e,qd(t.c,t.h)):(n||(e=ld(e,rd)),t.c=new kd(e,0,t.h))}function R(t,e,n){t.c.set(e,n)}function Qc(t,e,r){n(r)||(r=[r+""]),sd(t.c,e,r)}function Mc(e){return R(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36)),e}function td(t){return t instanceof Q?M(t):new Q(t,void 0)}function ud(t,e,n,r){var i=new Q(null,void 0);return t&&ed(i,t),e&&fd(i,e),n&&gd(i,n),r&&(i.a=r),i}function jd(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function ld(t,e,n){return l(t)?(t=encodeURI(t).replace(e,vd),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function vd(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function kd(t,e,n){this.b=this.a=null,this.c=t||null,this.f=!!n}function S(t){t.a||(t.a=new O,t.b=0,t.c&&dd(t.c,function(e,n){e=decodeURIComponent(e.replace(/\+/g," ")),S(t),t.c=null,e=wd(t,e);var r=t.a.get(e);r||t.a.set(e,r=[]),r.push(n),t.b+=1}))}function xd(t,e){S(t),e=wd(t,e),P(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,bd(t.a,e))}function yd(t,e){return S(t),e=wd(t,e),P(t.a.b,e)}function sd(t,e,n){xd(t,e),0<n.length&&(t.c=null,t.a.set(wd(t,e),ya(n)),t.b+=n.length)}function id(t){var e=new kd;return e.c=t.c,t.a&&(e.a=new O(t.a),e.b=t.b),e}function wd(t,e){return e+="",t.f&&(e=e.toLowerCase()),e}function qd(t,e){e&&!t.f&&(S(t),t.c=null,t.a.forEach(function(t,e){var n=e.toLowerCase();e!=n&&(xd(this,e),sd(this,n,t))},t)),t.f=e}function zd(){this.a=t()}function Bd(){Ad||(Ad=new zd)}function Cd(){Ad||(Ad=new zd)}function Dd(){}function Fd(){A.call(this,"d")}function Gd(){A.call(this,"c")}function Hd(t,e){this.a=t,this.b=e,this.c=this.i=null,this.h=!1,this.l=null,this.f=-1,this.m=this.g=null}function Id(t){I(t.b,"TestConnection: starting stage 2");var e=t.a.J.a;if(null!=e)I(t.b,"Buffered"),K(),e?(K(),Jd(t.a,t,!1)):(K(),Jd(t.a,t,!0));else{t.c=new L(t,t.b,0,void 0,void 0),t.c.h=t.i,e=Kd(t.a,t.g,t.l),K(),Qc(e,"TYPE","xmlhttp");var n=t.a.j,r=t.a.N;n&&r&&R(e,n,r),Oc(t.c,e,!1,t.g)}}function Md(){this.a=this.b=null}function Nd(t){if(this.a=new O,t){t=Yc(t);for(var e=t.length,n=0;n<e;n++){var r=t[n];this.a.set(T(r),r)}}}function T(t){var e=typeof t;return"object"==e&&t||"function"==e?"o"+(t[q]||(t[q]=++ea)):e.charAt(0)+t}function Od(t){this.f=t||Pd,this.c=k.pa&&k.pa.La&&k.pa.La()&&k.pa.La().Cb?this.f:1,this.a=null,1<this.c&&(this.a=new Nd),this.b=null}function Qd(t,e){t.a||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(t.c=t.f,t.a=new Nd,t.b&&(Rd(t,t.b),t.b=null))}function Sd(t){return!!t.b||!!t.a&&t.a.u()>=t.c}function Td(t,e){return t.b?t.b==e:!!t.a&&t.a.contains(e)}function Rd(t,e){t.a?t.a.a.set(T(e),e):t.b=e}function Ud(t,e){this.a=t,this.b=e}function Vd(t,e){this.a=t,this.b=e}function Wd(){this.a=new Vd}function Xd(t,e,n){var r=n||"";try{Zc(t,function(t,n){var i=t;p(t)&&(i=Fb(t)),e.push(r+n+"="+encodeURIComponent(i))})}catch(t){throw e.push(r+"type="+encodeURIComponent("_badmap")),t}}function Yd(t,e){var n=new qc;I(n,"TestLoadImage: loading "+t);var r=new Image;r.onload=ia(Zd,n,r,"TestLoadImage: loaded",!0,e),r.onerror=ia(Zd,n,r,"TestLoadImage: error",!1,e),r.onabort=ia(Zd,n,r,"TestLoadImage: abort",!1,e),r.ontimeout=ia(Zd,n,r,"TestLoadImage: timeout",!1,e),k.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=t}function Zd(t,e,n,r,i){try{I(t,n),e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,i(r)}catch(e){sc(t,e)}}function U(t){B.call(this),this.headers=new O,this.G=t||null,this.f=!1,this.F=this.a=null,this.M=this.s="",this.j=0,this.g="",this.h=this.I=this.o=this.H=!1,this.l=0,this.B=null,this.N=$d,this.C=this.m=!1}function ee(t){return z&&Ua(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}function va(t){return"content-type"==t.toLowerCase()}function ce(t,e){t.f=!1,t.a&&(t.h=!0,t.a.abort(),t.h=!1),t.g=e,t.j=5,fe(t),ge(t)}function fe(t){t.H||(t.H=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function he(t){if(t.f&&void 0!==goog)if(t.F[1]&&4==N(t)&&2==t.V())H(t.b,V(t,"Local request error detected and ignored"));else if(t.o&&4==N(t))Zb(t.Ma,0,t);else if(t.dispatchEvent("readystatechange"),4==N(t)){H(t.b,V(t,"Request complete")),t.f=!1;try{var e=t.V();t:switch(e){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var n=!0;break t;default:n=!1}var r;if(!(r=n)){var i;if(i=0===e){var o=(t.s+"").match(cd)[1]||null;if(!o&&k.self&&k.self.location){var a=k.self.location.protocol;o=a.substr(0,a.length-1)}i=!ae.test(o?o.toLowerCase():"")}r=i}r?(t.dispatchEvent("complete"),t.dispatchEvent("success")):(t.j=6,t.g=t.Ha()+" ["+t.V()+"]",fe(t))}finally{ge(t)}}}function ge(t,e){if(t.a){de(t);var n=t.a,r=t.F[0]?aa:null;t.a=null,t.F=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(e){(t=t.b)&&F(t,"Problem encountered resetting onreadystatechange: "+e.message)}}}function de(t){t.a&&t.C&&(t.a.ontimeout=null),"number"==typeof t.B&&(k.clearTimeout(t.B),t.B=null)}function N(t){return t.a?t.a.readyState:0}function V(t,e){return e+" ["+t.M+" "+t.s+" "+t.V()+"]"}function ie(t){var e="";return Ba(t,function(t,n){e+=n,e+=":",e+=t,e+="\r\n"}),e}function je(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=ie(n),l(t)){if(e=encodeURIComponent(e+""),n=null!=n?"="+encodeURIComponent(n+""):"",e+=n){if(n=t.indexOf("#"),0>n&&(n=t.length),0>(r=t.indexOf("?"))||r>n){r=n;var i=""}else i=t.substring(r+1,n);t=[t.substr(0,r),i,t.substr(n)],n=t[1],t[1]=e?n?n+"&"+e:e:n,t=t[0]+(t[1]?"?"+t[1]:"")+t[2]}return t}return R(t,e,n),t}function ke(t,e,n){this.za=e||0,this.Ba=0,this.h=[],this.l=[],this.a=new qc,this.J=n||new Md,this.ia=this.ya=this.H=this.ja=this.b=this.N=this.j=this.ha=this.f=this.P=this.i=null,this.Va=this.I=0,this.ka=this.C=this.s=this.m=this.o=this.c=null,this.v=this.Aa=this.S=-1,this.ga=this.B=this.G=0,this.T=t&&t.supportsCrossDomainXhr||!1,this.M="",this.g=new Od(t&&t.concurrentRequestLimit),this.la=new Wd,this.F=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,this.Ua=t&&t.fastHandshake||!1}function le(e){if(I(e.a,"disconnect()"),me(e),3==e.D){var n=e.I++,r=M(e.H);R(r,"SID",e.M),R(r,"RID",n),R(r,"TYPE","terminate"),ne(e,r),n=new L(e,e.a,0,n,void 0),n.I=2,n.l=Mc(M(r)),r=!1,k.navigator&&k.navigator.sendBeacon&&(r=k.navigator.sendBeacon(""+n.l,"")),r||((new Image).src=n.l),n.H=t(),Pc(n)}oe(e)}function me(t){t.C&&(t.C.abort(),t.C=null),t.b&&(t.b.cancel(),t.b=null),t.m&&(k.clearTimeout(t.m),t.m=null),pe(t),t.g.cancel(),t.o&&(k.clearTimeout(t.o),t.o=null)}function qe(t,e){if(1e3==t.h.length){var n="Already have 1000 queued maps upon queueing "+Fb(e),r=t.a.a;r&&F(r,n)}t.h.push(new Ud(t.Va++,e)),3==t.D&&re(t)}function re(t){Sd(t.g)||t.o||(t.o=xc(r(t.Pa,t),0),t.G=0)}function te(t,e){if(e){t.h=t.l.concat(t.h),t.l.length=0;var n=t.I-1}else n=t.I++;e=se(t);var r=M(t.H);R(r,"SID",t.M),R(r,"RID",n),R(r,"AID",t.S),ne(t,r),t.f&&t.i&&je(r,t.f,t.i),n=new L(t,t.a,0,n,t.G+1),null===t.f&&(n.h=t.i),n.setTimeout(Math.round(1e4)+Math.round(1e4*Math.random())),Rd(t.g,n),Lc(n,r,e)}function ne(t,e){t.c&&Zc({},function(t,n){R(e,n,t)})}function se(t){var e=Math.min(t.h.length,1e3),n=t.c?r(t.c.Wa,t.c,t):null,i=t.h,o=["count="+e];if(0<e){var a=i[0].a;o.push("ofs="+a)}else a=0;for(var s=0;s<e;s++){var u=i[s].a,c=i[s].b;u-=a;try{Xd(c,o,"req"+u+"_")}catch(t){n&&n(c)}}return n=o.join("&"),t.l=t.l.concat(t.h.splice(0,e)),n}function ue(t){if(!t.b&&!t.m){t.ga=1;var e=t.Oa;Tb||Ub(),Wb||(Tb(),Wb=!0);var n=Pb,r=C.get();r.set(e,t),n.b?n.b.next=r:n.a=r,n.b=r,t.B=0}}function ve(t){return t.b||t.m?((t=t.a.a)&&F(t,"Request already in progress"),!1):!(3<=t.B||(I(t.a,"Going to retry GET"),t.ga++,t.m=xc(r(t.Oa,t),we(t,t.B)),t.B++,0))}function Jd(t,e,n){I(t.a,"Test Connection Finished");var r=e.m;r&&Qd(t.g,r),t.ka=n,t.v=e.f,I(t.a,"connectChannel_()"),t.H=xe(t,t.ja),re(t)}function Ld(t,e){I(t.a,"Test Connection Failed"),t.v=e.f,W(t,2)}function pe(t){null!=t.s&&(k.clearTimeout(t.s),t.s=null)}function we(t,e){var n=5e3+Math.floor(1e4*Math.random());return t.sa()||(I(t.a,"Inactive channel"),n*=2),n*e}function W(t,e){if(I(t.a,"Error code "+e),2==e){var n=null;t.c&&(n=null);var i=r(t.ib,t);n||(n=new Q("//www.google.com/images/cleardot.gif"),k.location&&"http"==k.location.protocol||ed(n,"https"),Mc(n)),Yd(""+n,i)}else K();I(t.a,"HttpChannel: error - "+e),t.D=0,t.c&&t.c.Da(t,e),oe(t),me(t)}function oe(t){if(t.D=0,t.v=-1,t.c)if(0==t.l.length&&0==t.h.length)t.c.na(t);else{I(t.a,"Number of undelivered maps, pending: "+t.l.length+", outgoing: "+t.h.length);var e=ya(t.l),n=ya(t.h);t.l.length=0,t.h.length=0,t.c.na(t,e,n)}}function xe(t,e){return e=ye(t,null,e),I(t.a,"GetForwardChannelUri: "+e),e}function Kd(t,e,n){return e=ye(t,t.fa()?e:null,n),I(t.a,"GetBackChannelUri: "+e),e}function ye(t,e,n){var r=td(n);if(""!=r.b)e&&fd(r,e+"."+r.b),gd(r,r.i);else{var i,o=k.location;i=e?e+"."+o.hostname:o.hostname,r=ud(o.protocol,i,o.port,n)}return t.ha&&Ba(t.ha,function(t,e){R(r,e,t)}),e=t.j,n=t.N,e&&n&&R(r,e,n),R(r,"VER",t.oa),ne(t,r),r}function ze(){}function Ae(t){for(var e=arguments[0],n=1;n<arguments.length;n++){var r=arguments[n];if(0==r.lastIndexOf("/",0))e=r;else{var i;(i=""==e)||(i=e.length-1,i=0<=i&&e.indexOf("/",i)==i),e+=i?r:"/"+r}}return e}function Be(){if(z&&!(10<=+Va))throw Error("Environmental error: no available transport.")}function X(t,e){B.call(this),this.a=new ke(e,20),this.b=t,this.s=e&&e.testUrl?e.testUrl:Ae(this.b,"test"),this.f=oc("goog.labs.net.webChannel.WebChannelBaseTransport"),this.g=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,this.a.P=e&&e.initMessageHeaders||null,(t=e&&e.httpHeadersOverwriteParam)&&!/^[\s\xa0]*$/.test(t)&&(this.a.f=t),this.o=e&&e.supportsCrossDomainXhr||!1,this.m=e&&e.sendRawJson||!1,(e=e&&e.httpSessionIdParam)&&!/^[\s\xa0]*$/.test(e)&&(this.a.j=e,null!==(t=this.g)&&e in t&&(t=this.g,e in t&&delete t[e],(t=this.f)&&G(t,"Ignore httpSessionIdParam also specified with messageUrlParams: "+e))),this.h=new Ce(this)}function De(t){Fd.call(this),this.data=t}function Ee(){Gd.call(this),this.status=1}function Ce(t){this.a=t}function Ge(){this.b=[],this.a=[]}function He(t){return 0==t.b.length&&(t.b=t.a,t.b.reverse(),t.a=[]),t.b.pop()}function Ie(t,e){if(w.call(this),this.h=t||0,this.c=e||10,this.h>this.c)throw Error(Je);this.a=new Ge,this.b=new Nd,this.g=null,this.aa()}function Ke(t){if("function"==typeof t.Y)t.Y();else for(var e in t)t[e]=null}function Le(t,e){this.a=t,this.b=e}function Me(t){if(this.a=[],t)t:{if(t instanceof Me){var e=t.O();if(t=t.A(),0>=this.u()){for(var n=this.a,r=0;r<e.length;r++)n.push(new Le(e[r],t[r]));break t}}else e=Da(t),t=Ca(t);for(r=0;r<e.length;r++)Ne(this,e[r],t[r])}}function Ne(t,e,n){var r=t.a;for(r.push(new Le(e,n)),e=r.length-1,t=t.a,n=t[e];0<e&&(r=e-1>>1,t[r].a>n.a);)t[e]=t[r],e=r;t[e]=n}function Oe(){Me.call(this)}function Y(t,e){this.f=new Oe,Ie.call(this,t,e)}function Z(t,e,n,r){this.l=t,this.j=!!r,Y.call(this,e,n)}var g,goog=goog||{},k=this,q="closure_uid_"+(1e9*Math.random()>>>0),ea=0,t=Date.now||function(){return+new Date};u(ja,Error),ja.prototype.name="CustomError";var la=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};u(na,ja),na.prototype.name="AssertionError";var qa=0,ra={};w.prototype.i=!1,w.prototype.Y=function(){if(!this.i&&(this.i=!0,this.w(),0!=qa)){var t=this[q]||(this[q]=++ea);delete ra[t]}},w.prototype.w=function(){if(this.v)for(;this.v.length;)this.v.shift()()};var sa=Array.prototype.indexOf?function(t,e,n){return Array.prototype.indexOf.call(t,e,n)}:function(t,e,n){if(n=null==n?0:0>n?Math.max(0,t.length+n):n,l(t))return l(e)&&1==e.length?t.indexOf(e,n):-1;for(;n<t.length;n++)if(n in t&&t[n]===e)return n;return-1},ta=Array.prototype.forEach?function(t,e,n){Array.prototype.forEach.call(t,e,n)}:function(t,e,n){for(var r=t.length,i=l(t)?t.split(""):t,o=0;o<r;o++)o in i&&e.call(n,i[o],o,t)},x;t:{var za=k.navigator;if(za){var Aa=za.userAgent;if(Aa){x=Aa;break t}}x=""}var Fa="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");Ha[" "]=aa;var Ka=y("Opera"),z=y("Trident")||y("MSIE"),La=y("Edge"),Ma=y("Gecko")&&!(-1!=x.toLowerCase().indexOf("webkit")&&!y("Edge"))&&!(y("Trident")||y("MSIE"))&&!y("Edge"),Na=-1!=x.toLowerCase().indexOf("webkit")&&!y("Edge"),Pa;t:{var Qa="",Sa=function(){var t=x;return Ma?/rv\:([^\);]+)(\)|;)/.exec(t):La?/Edge\/([\d\.]+)/.exec(t):z?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(t):Na?/WebKit\/(\S+)/.exec(t):Ka?/(?:Version)[ \/]?(\S+)/.exec(t):void 0}();if(Sa&&(Qa=Sa?Sa[1]:""),z){var Ta=Oa();if(null!=Ta&&Ta>parseFloat(Qa)){Pa=Ta+"";break t}}Pa=Qa}var Ja={},Va,Wa=k.document;Va=Wa&&z?Oa()||("CSS1Compat"==Wa.compatMode?parseInt(Pa,10):5):void 0;var Xa=Object.freeze||function(t){return t},Ya=!z||9<=+Va,Za=z&&!Ua("9"),$a=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return k.addEventListener("test",aa,e),k.removeEventListener("test",aa,e),t}();A.prototype.b=function(){this.Qa=!1},u(ab,A);var bb=Xa({2:"touch",3:"pen",4:"mouse"});ab.prototype.b=function(){ab.L.b.call(this);var t=this.c;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,Za)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}};var cb="closure_listenable_"+(1e6*Math.random()|0),eb=0,mb="closure_lm_"+(1e6*Math.random()|0),nb={},ob=0,Bb="__closure_events_fn_"+(1e9*Math.random()>>>0);u(B,w),B.prototype[cb]=!0,g=B.prototype,g.addEventListener=function(t,e,n,r){pb(this,t,e,n,r)},g.removeEventListener=function(t,e,n,r){xb(this,t,e,n,r)},g.dispatchEvent=function(t){var e,n=this.J;if(n)for(e=[];n;n=n.J)e.push(n);n=this.P;var r=t.type||t;if(l(t))t=new A(t,n);else if(t instanceof A)t.target=t.target||n;else{var i=t;t=new A(r,n),Ga(t,i)}if(i=!0,e)for(var o=e.length-1;0<=o;o--){var a=t.a=e[o];i=Cb(a,r,!0,t)&&i}if(a=t.a=n,i=Cb(a,r,!0,t)&&i,i=Cb(a,r,!1,t)&&i,e)for(o=0;o<e.length;o++)a=t.a=e[o],i=Cb(a,r,!1,t)&&i;return i},g.w=function(){if(B.L.w.call(this),this.c){var t,e=this.c,n=0;for(t in e.a){for(var r=e.a[t],i=0;i<r.length;i++)++n,gb(r[i]);delete e.a[t],e.b--}}this.J=null},g.$=function(t,e,n,r){return ib(this.c,t+"",e,!1,n,r)},g.Ia=function(t,e,n,r){return ib(this.c,t+"",e,!0,n,r)},g.xa=function(t,e,n,r){var i=this.c;if((t+="")in i.a){var o=i.a[t];e=jb(o,e,n,r),-1<e?(gb(o[e]),Array.prototype.splice.call(o,e,1),0==o.length&&(delete i.a[t],i.b--),i=!0):i=!1}else i=!1;return i};var Jb={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\u000b"},Lb=/\uffff/.test("")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g;Mb.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 C=new Mb(function(){return new Nb},function(t){t.reset()},100);Nb.prototype.set=function(t,e){this.a=t,this.b=e,this.next=null},Nb.prototype.reset=function(){this.next=this.b=this.a=null};var Rb,Tb,Wb=!1,Pb=new function(){this.b=this.a=null};u(Xb,B),g=Xb.prototype,g.Z=!1,g.K=null,g.jb=function(){if(this.Z){var e=t()-this.g;0<e&&e<.8*this.b?this.K=this.a.setTimeout(this.f,this.b-e):(this.K&&(this.a.clearTimeout(this.K),this.K=null),this.dispatchEvent("tick"),this.Z&&(this.K=this.a.setTimeout(this.f,this.b),this.g=t()))}},g.start=function(){this.Z=!0,this.K||(this.K=this.a.setTimeout(this.f,this.b),this.g=t())},g.w=function(){Xb.L.w.call(this),Yb(this),delete this.a},u($b,w),g=$b.prototype,g.ea=!1,g.W=null,g.Ya=function(t){this.a=arguments,this.W?this.ea=!0:ac(this)},g.w=function(){$b.L.w.call(this),this.W&&(k.clearTimeout(this.W),this.W=null,this.ea=!1,this.a=[])},g.cb=function(){this.W=null,this.ea&&(this.ea=!1,ac(this))},u(D,w);var bc=[];D.prototype.$=function(t,e,r,i){n(e)||(e&&(bc[0]=""+e),e=bc);for(var o=0;o<e.length;o++){var a=pb(t,e[o],r||this.handleEvent,i||!1,this.b||this);if(!a)break;this.a[a.key]=a}return this},D.prototype.xa=function(t,e,r,i,o){if(n(e))for(var a=0;a<e.length;a++)this.xa(t,e[a],r,i,o);else r=r||this.handleEvent,i=p(i)?!!i.capture:!!i,o=o||this.b||this,r=rb(r),i=!!i,(e=db(t)?lb(t.c,e+"",r,i,o):t&&(t=tb(t))?lb(t,e,r,i,o):null)&&(yb(e),delete this.a[e.key]);return this},D.prototype.w=function(){D.L.w.call(this),cc(this)},D.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},dc.prototype.a=null;var ec=0;dc.prototype.reset=function(e,n,r,i,o){"number"==typeof o||ec++,i||t(),this.b=n,delete this.a},E.prototype.toString=function(){return this.name};var gc=new E("SEVERE",1e3),hc=new E("WARNING",900),ic=new E("INFO",800),jc=new E("CONFIG",700),kc=new E("FINE",500);fc.prototype.log=function(t,e,n){if(t.value>=lc(this).value)for(da(e)&&(e=e()),t=new dc(t,e+"",this.f),n&&(t.a=n),n="log:"+t.b,(t=k.console)&&t.timeStamp&&t.timeStamp(n),(t=k.msWriteProfilerMark)&&t(n),n=this;n;)n=n.a};var mc={},nc=null,J=new B;u(tc,A),u(vc,A),u(wc,A);var yc={NO_ERROR:0,kb:1,rb:2,qb:3,nb:4,pb:5,sb:6,Sa:7,TIMEOUT:8,vb:9},zc={mb:"complete",zb:"success",Ta:"error",Sa:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",tb:"incrementaldata",wb:"progress",ob:"downloadprogress",Ab:"uploadprogress"};Ac.prototype.a=null;var Dc;u(Ec,Ac),Dc=new Ec;var Gc=45e3,Hc=250,Jc={},Kc={};g=L.prototype,g.setTimeout=function(t){this.P=t},g.gb=function(t){t=t.target;var e=this.G;e&&3==N(t)?(I(this.b,"Throttling readystatechange."),e.Ya()):this.Ra(t)},g.Ra=function(t){try{if(t==this.a){var e=N(this.a),n=this.a.Ga();if(!(3>e||3==e&&!Ka&&!this.a.U())){this.s||4!=e||7==n||uc(),Rc(this);var r=this.a.V();this.v=r;var i=this.a.U();if(i||I(this.b,"No response text for uri "+this.g+" status "+r),this.c=200==r,I(this.b,"XMLHTTP RESP ("+this.f+") [ attempt "+this.S+"]: "+this.j+"\n"+this.g+"\n"+e+" "+r),this.c)this.J?(Sc(this,e,i),Ka&&this.c&&3==e&&(this.M.$(this.F,"tick",this.fb),this.F.start())):(rc(this.b,this.f,i,null),Tc(this,i)),4==e&&Uc(this),this.c&&!this.s&&(4==e?this.m.wa(this):(this.c=!1,Pc(this)));else{if(400==r&&0<i.indexOf("Unknown SID")){this.i=3,K();var o=this.b.a;o&&G(o,"XMLHTTP Unknown SID ("+this.f+")")}else{this.i=0,K();var a=this.b.a;a&&G(a,"XMLHTTP Bad status "+r+" ("+this.f+")")}Uc(this),Vc(this)}}}else{var s=this.b.a;s&&G(s,"Called back with an unexpected xmlhttp")}}catch(t){I(this.b,"Failed call to OnXmlHttpReadyStateChanged_"),this.a&&this.a.U()?sc(this.b,t,"ResponseText: "+this.a.U()):sc(this.b,t,"No response text")}},g.fb=function(){var t=N(this.a),e=this.a.U();this.C<e.length&&(Rc(this),Sc(this,t,e),this.c&&4!=t&&Pc(this))},g.cancel=function(){this.s=!0,Uc(this)},g.eb=function(){this.o=null;var e=t();if(0<=e-this.T)this.c&&(e=this.b.a)&&F(e,"Received watchdog timeout even though request loaded successfully"),I(this.b,"TIMEOUT: "+this.g),2!=this.I&&(uc(),K()),Uc(this),this.i=2,Vc(this);else{var n=this.b.a;n&&G(n,"WatchDog timer called too early"),Xc(this,this.T-e)}},g=O.prototype,g.u=function(){return this.c},g.A=function(){$c(this);for(var t=[],e=0;e<this.a.length;e++)t.push(this.b[this.a[e]]);return t},g.O=function(){return $c(this),this.a.concat()},g.get=function(t,e){return P(this.b,t)?this.b[t]:e},g.set=function(t,e){P(this.b,t)||(this.c++,this.a.push(t)),this.b[t]=e},g.forEach=function(t,e){for(var n=this.O(),r=0;r<n.length;r++){var i=n[r],o=this.get(i);t.call(e,o,i,this)}};var cd=/^(?:([^:\/?#.]+):)?(?:\/\/(?:([^\/?#]*)@)?([^\/#?]*?)(?::([0-9]+))?(?=[\/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;Q.prototype.toString=function(){var t=[],e=this.f;e&&t.push(ld(e,md,!0),":");var n=this.b;return(n||"file"==e)&&(t.push("//"),(e=this.j)&&t.push(ld(e,md,!0),"@"),t.push(encodeURIComponent(n+"").replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.i)&&t.push(":",n+"")),(n=this.a)&&(this.b&&"/"!=n.charAt(0)&&t.push("/"),t.push(ld(n,"/"==n.charAt(0)?nd:od,!0))),(n=""+this.c)&&t.push("?",n),(n=this.g)&&t.push("#",ld(n,pd)),t.join("")},Q.prototype.resolve=function(t){var e=M(this),n=!!t.f;n?ed(e,t.f):n=!!t.j,n?e.j=t.j:n=!!t.b,n?fd(e,t.b):n=null!=t.i;var r=t.a;if(n)gd(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(-1!=i.indexOf("./")||-1!=i.indexOf("/.")){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,n?hd(e,id(t.c)):n=!!t.g,n&&(e.g=t.g),e};var md=/[#\/\?@]/g,od=/[\#\?:]/g,nd=/[\#\?]/g,rd=/[\#\?@]/g,pd=/#/g;g=kd.prototype,g.u=function(){return S(this),this.b},g.forEach=function(t,e){S(this),this.a.forEach(function(n,r){ta(n,function(n){t.call(e,n,r,this)},this)},this)},g.O=function(){S(this);for(var t=this.a.A(),e=this.a.O(),n=[],r=0;r<e.length;r++)for(var i=t[r],o=0;o<i.length;o++)n.push(e[r]);return n},g.A=function(t){S(this);var e=[];if(l(t))yd(this,t)&&(e=xa(e,this.a.get(wd(this,t))));else{t=this.a.A();for(var n=0;n<t.length;n++)e=xa(e,t[n])}return e},g.set=function(t,e){return S(this),this.c=null,t=wd(this,t),yd(this,t)&&(this.b-=this.a.get(t).length),this.a.set(t,[e]),this.b+=1,this},g.get=function(t,e){return t=t?this.A(t):[],0<t.length?t[0]+"":e},g.toString=function(){if(this.c)return this.c;if(!this.a)return"";for(var t=[],e=this.a.O(),n=0;n<e.length;n++){var r=e[n],i=encodeURIComponent(r+"");r=this.A(r);for(var o=0;o<r.length;o++){var a=i;""!==r[o]&&(a+="="+encodeURIComponent(r[o]+"")),t.push(a)}}return this.c=t.join("&")};var Ad=null;zd.prototype.set=function(t){this.a=t},zd.prototype.reset=function(){this.set(t())},zd.prototype.get=function(){return this.a},u(Cd,Bd);var Ed={OPEN:"a",lb:"b",Ta:"c",ub:"d"};u(Fd,A),u(Gd,A),g=Hd.prototype,g.R=null,g.ra=function(t){return this.a.ra(t)},g.abort=function(){this.c&&(this.c.cancel(),this.c=null),this.f=-1},g.Ka=function(){return!1},g.Na=function(t,e){if(this.f=t.v,0==this.R){if(I(this.b,"TestConnection: Got data for stage 1"),!this.a.F&&(t=t.a)){var n=t.a?t.a.getResponseHeader("X-Client-Wire-Protocol"):null;this.m=n||null,this.a.j&&((t=t.a?t.a.getResponseHeader("X-HTTP-Session-Id"):null)?this.a.N=t:(t=this.b.a)&&G(t,"Missing X_HTTP_SESSION_ID in the handshake response"))}if(e){try{var r=this.a.la.a.parse(e)}catch(t){return sc(this.b,t),void Ld(this.a,this)}this.g=r[0]}else I(this.b,"TestConnection: Null responseText"),Ld(this.a,this)}else 1==this.R&&(this.h?K():"11111"==e?(K(),this.h=!0,(!z||10<=+Va)&&(this.f=200,this.c.cancel(),I(this.b,"Test connection succeeded; using streaming connection"),K(),Jd(this.a,this,!0))):(K(),this.h=!1))},g.wa=function(){this.f=this.c.v,this.c.c?0==this.R?(this.R=1,I(this.b,"TestConnection: request complete for initial check"),Id(this)):1==this.R&&(I(this.b,"TestConnection: request complete for stage 2"),this.h?(I(this.b,"Test connection succeeded; using streaming connection"),K(),Jd(this.a,this,!0)):(I(this.b,"Test connection failed; not using streaming"),K(),Jd(this.a,this,!1))):(I(this.b,"TestConnection: request failed, in state "+this.R),0==this.R?K():1==this.R&&K(),Ld(this.a,this))},g.fa=function(){return this.a.fa()},g.sa=function(){return this.a.sa()},Nd.prototype.u=function(){return this.a.u()},Nd.prototype.contains=function(t){return t=T(t),P(this.a.b,t)},Nd.prototype.A=function(){return this.a.A()};var Pd=10;Od.prototype.cancel=function(){this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(ta(this.a.A(),function(t){t.cancel()}),ad(this.a.a))},Vd.prototype.stringify=function(t){return k.JSON.stringify(t,this.a)},Vd.prototype.parse=function(t){return k.JSON.parse(t,this.b)},u(U,B);var $d="";U.prototype.b=oc("goog.net.XhrIo");var ae=/^https?$/i,be=["POST","PUT"];g=U.prototype,g.ta=function(t,e,n,i){if(this.a)throw Error("[goog.net.XhrIo] Object is active with another request="+this.s+"; newUri="+t);e=e?e.toUpperCase():"GET",this.s=t,this.g="",this.j=0,this.M=e,this.H=!1,this.f=!0,this.a=Fc(this.G?this.G:Dc),this.F=Bc(this.G?this.G:Dc),this.a.onreadystatechange=r(this.Ma,this);try{H(this.b,V(this,"Opening Xhr")),this.I=!0,this.a.open(e,t+"",!0),this.I=!1}catch(t){return H(this.b,V(this,"Error opening Xhr: "+t.message)),void ce(this,t)}t=n||"";var o=new O(this.headers);i&&Zc(i,function(t,e){o.set(e,t)}),i=ua(o.O()),n=k.FormData&&t instanceof k.FormData,!(0<=sa(be,e))||i||n||o.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),o.forEach(function(t,e){this.a.setRequestHeader(e,t)},this),this.N&&(this.a.responseType=this.N),"withCredentials"in this.a&&this.a.withCredentials!==this.m&&(this.a.withCredentials=this.m);try{de(this),0<this.l&&(this.C=ee(this.a),H(this.b,V(this,"Will abort after "+this.l+"ms if incomplete, xhr2 "+this.C)),this.C?(this.a.timeout=this.l,this.a.ontimeout=r(this.Ja,this)):this.B=Zb(this.Ja,this.l,this)),H(this.b,V(this,"Sending request")),this.o=!0,this.a.send(t),this.o=!1}catch(t){H(this.b,V(this,"Send error: "+t.message)),ce(this,t)}},g.Ja=function(){void 0!==goog&&this.a&&(this.g="Timed out after "+this.l+"ms, aborting",this.j=8,H(this.b,V(this,this.g)),this.dispatchEvent("timeout"),this.abort(8))},g.abort=function(t){this.a&&this.f&&(H(this.b,V(this,"Aborting")),this.f=!1,this.h=!0,this.a.abort(),this.h=!1,this.j=t||7,this.dispatchEvent("complete"),this.dispatchEvent("abort"),ge(this))},g.w=function(){this.a&&(this.f&&(this.f=!1,this.h=!0,this.a.abort(),this.h=!1),ge(this,!0)),U.L.w.call(this)},g.Ma=function(){this.i||(this.I||this.o||this.h?he(this):this.bb())},g.bb=function(){he(this)},g.V=function(){try{return 2<N(this)?this.a.status:-1}catch(t){return-1}},g.Ha=function(){try{return 2<N(this)?this.a.statusText:""}catch(t){return H(this.b,"Can not get status: "+t.message),""}},g.U=function(){try{return this.a?this.a.responseText:""}catch(t){return H(this.b,"Can not get responseText: "+t.message),""}},g.Za=function(t){if(this.a){var e=this.a.responseText;t&&0==e.indexOf(t)&&(e=e.substring(t.length));t:{if(t=e,k.JSON)try{var n=k.JSON.parse(t);break t}catch(t){}n=Eb(t)}return n}},g.Ga=function(){return this.j},g.$a=function(){return l(this.g)?this.g:this.g+""},g=ke.prototype,g.oa=8,g.D=1,g.Ka=function(){return 0==this.D},g.Pa=function(t){if(this.o=null,I(this.a,"startForwardChannel_"),1==this.D)if(t)(t=this.a.a)&&F(t,"Not supposed to retry the open");else{I(this.a,"open_()"),this.I=Math.floor(1e5*Math.random()),t=this.I++;var e=new L(this,this.a,0,t,void 0),n=this.i;this.P&&(n?(n=Ea(n),Ga(n,this.P)):n=this.P),null===this.f&&(e.h=n);var r=se(this),i=M(this.H);R(i,"RID",t),0<this.za&&R(i,"CVER",this.za),this.F&&this.j&&R(i,"X-HTTP-Session-Id",this.j),ne(this,i),this.f&&n&&je(i,this.f,n),Rd(this.g,e),this.Ua?(R(i,"$req",r),Lc(e,i,null)):Lc(e,i,r),this.D=2}else 3==this.D&&(t?te(this,t):0==this.h.length?I(this.a,"startForwardChannel_ returned: nothing to send"):Sd(this.g)?(t=this.a.a)&&F(t,"startForwardChannel_ returned: connection already in progress"):(te(this),I(this.a,"startForwardChannel_ finished, sent request")))},g.Oa=function(){this.m=null,I(this.a,"Creating new HttpRequest"),this.b=new L(this,this.a,0,"rpc",this.ga),null===this.f&&(this.b.h=this.i),this.b.N=0;var t=M(this.ya);R(t,"RID","rpc"),R(t,"SID",this.M),R(t,"CI",this.ka?"0":"1"),R(t,"AID",this.S),ne(this,t),R(t,"TYPE","xmlhttp"),this.f&&this.i&&je(t,this.f,this.i),Oc(this.b,t,!0,this.ia),I(this.a,"New Request created")},g.Na=function(t,e){if(0!=this.D&&(this.b==t||Td(this.g,t)))if(this.v=t.v,Td(this.g,t)&&3==this.D){try{var i=this.la.a.parse(e)}catch(t){i=null}if(n(i)&&3==i.length)if(e=i,0==e[0])t:if(I(this.a,"Server claims our backchannel is missing."),this.m)I(this.a,"But we are currently starting the request.");else{if(this.b){if(!(this.b.H+3e3<t.H))break t;pe(this),this.b.cancel(),this.b=null}else(t=this.a.a)&&G(t,"We do not have a BackChannel established");ve(this),K()}else this.Aa=e[1],0<(t=this.Aa-this.S)&&(e=e[2],I(this.a,e+" bytes (in "+t+" arrays) are outstanding on the BackChannel"),37500>e&&this.ka&&0==this.B&&!this.s&&(this.s=xc(r(this.ab,this),6e3)));else I(this.a,"Bad POST response data returned"),W(this,11)}else if(this.b==t&&pe(this),!/^[\s\xa0]*$/.test(e))for(e=i=this.la.a.parse(e),i=0;i<e.length;i++){var o=e[i];if(this.S=o[0],o=o[1],2==this.D)if("c"==o[0]){this.M=o[1],this.ia=o[2];var a=o[3];null!=a&&(this.oa=a,I(this.a,"VER="+this.oa)),o=o[4],null!=o&&(this.Ba=o,I(this.a,"SVER="+this.Ba)),this.F&&(o=t.a)&&((a=o.a?o.a.getResponseHeader("X-Client-Wire-Protocol"):null)&&Qd(this.g,a),this.j&&((o=o.a?o.a.getResponseHeader("X-HTTP-Session-Id"):null)?(this.N=o,R(this.H,this.j,o)):(o=this.a.a)&&G(o,"Missing X_HTTP_SESSION_ID in the handshake response"))),this.D=3,this.c&&this.c.Fa(this),this.ya=Kd(this,this.ia,this.ja),ue(this)}else"stop"!=o[0]&&"close"!=o[0]||W(this,7);else 3==this.D&&("stop"==o[0]||"close"==o[0]?"stop"==o[0]?W(this,7):le(this):"noop"!=o[0]&&this.c&&this.c.Ea(this,o),this.B=0)}},g.ab=function(){null!=this.s&&(this.s=null,this.b.cancel(),this.b=null,ve(this),K())},g.wa=function(e){if(I(this.a,"Request complete"),this.b==e){pe(this),this.b=null;var n=2}else{if(!Td(this.g,e))return;n=this.g,n.b&&n.b==e?n.b=null:n.a&&n.a.contains(e)&&bd(n.a.a,T(e)),n=1}if(this.v=e.v,0!=this.D)if(e.c)1==n?(t(),J.dispatchEvent(new wc(J)),re(this),this.l.length=0):ue(this);else{var i=e.i;if(3==i||0==i&&0<this.v)I(this.a,"Not retrying due to error type");else{I(this.a,"Maybe retrying, last error: "+Ic(i,this.v));var o;if((o=1==n)&&(Sd(this.g)||this.o?((e=this.a.a)&&F(e,"Request already in progress"),o=!1):1==this.D||2==this.D||2<=this.G?o=!1:(I(this.a,"Going to retry POST"),this.o=xc(r(this.Pa,this,e),we(this,this.G)),this.G++,o=!0)),o||2==n&&ve(this))return;I(this.a,"Exceeded max number of retries")}switch(I(this.a,"Error: HTTP request failed"),i){case 1:W(this,5);break;case 4:W(this,10);break;case 3:W(this,6);break;default:W(this,2)}}},g.ib=function(t){t?I(this.a,"Successfully pinged google.com"):I(this.a,"Failed to ping google.com"),K()},g.ra=function(t){if(t&&!this.T)throw Error("Can't create secondary domain capable XhrIo object.");return t=new U,t.m=this.T,t},g.sa=function(){return!!this.c&&!0},g.fa=function(){return this.T},new Cd,g=ze.prototype,g.Fa=function(){},g.Ea=function(){},g.Da=function(){},g.na=function(){},g.Wa=function(){},Be.prototype.a=function(t,e){return new X(t,e)},u(X,B),X.prototype.j=function(){this.a.c=this.h,this.o&&(this.a.T=!0);var t=this.a,e=this.s,n=this.b,r=this.g||void 0;I(t.a,"connect()"),K(),t.ja=n,t.ha=r||{},t.F&&(I(t.a,"connect() bypassed channel-test."),t.J.b=[],t.J.a=!1),I(t.a,"connectTest_()"),t.C=new Hd(t,t.a),null===t.f&&(t.C.i=t.i),n=e,t.f&&t.i&&(n=je(e,t.f,t.i)),t=t.C,t.l=n,e=xe(t.a,t.l),K(),(n=t.a.J.b)?(t.g=n[0],t.R=1,Id(t)):(Qc(e,"MODE","init"),!t.a.F&&t.a.j&&Qc(e,"X-HTTP-Session-Id",t.a.j),t.c=new L(t,t.b,0,void 0,void 0),t.c.h=t.i,Oc(t.c,e,!1,null),t.R=0)},X.prototype.close=function(){le(this.a)},X.prototype.l=function(t){if(this.m){var e={};e.__data__=Fb(t),qe(this.a,e)}else qe(this.a,t)},X.prototype.w=function(){this.a.c=null,delete this.h,le(this.a),delete this.a,X.L.w.call(this)},u(De,Fd),u(Ee,Gd),u(Ce,ze),Ce.prototype.Fa=function(){pc(this.a.f,"WebChannel opened on "+this.a.b),this.a.dispatchEvent("a")},Ce.prototype.Ea=function(t,e){this.a.dispatchEvent(new De(e))},Ce.prototype.Da=function(t,e){pc(this.a.f,"WebChannel aborted on "+this.a.b+" due to channel error: "+e),this.a.dispatchEvent(new Ee)},Ce.prototype.na=function(){pc(this.a.f,"WebChannel closed on "+this.a.b),this.a.dispatchEvent("b")};var Fe=ia(function(t,e){function n(){}n.prototype=t.prototype;var r=new n;return t.apply(r,Array.prototype.slice.call(arguments,1)),r},Be);Ge.prototype.u=function(){return this.b.length+this.a.length},Ge.prototype.contains=function(t){return 0<=sa(this.b,t)||0<=sa(this.a,t)},Ge.prototype.A=function(){for(var t=[],e=this.b.length-1;0<=e;--e)t.push(this.b[e]);var n=this.a.length;for(e=0;e<n;++e)t.push(this.a[e]);return t},u(Ie,w);var Je="[goog.structs.Pool] Min can not be greater than max";g=Ie.prototype,g.ca=function(){var e=t();if(!(null!=this.g&&0>e-this.g)){for(var n;0<this.a.u()&&(n=He(this.a),!this.va(n));)this.aa();return!n&&this.u()<this.c&&(n=this.qa()),n&&(this.g=e,this.b.a.set(T(n),n)),n}},g.hb=function(t){return!!bd(this.b.a,T(t))&&(this.ma(t),!0)},g.ma=function(t){bd(this.b.a,T(t)),this.va(t)&&this.u()<this.c?this.a.a.push(t):Ke(t)},g.aa=function(){for(var t=this.a;this.u()<this.h;){var e=this.qa();t.a.push(e)}for(;this.u()>this.c&&0<this.a.u();)Ke(He(t))},g.qa=function(){return{}},g.va=function(t){return"function"!=typeof t.Xa||t.Xa()},g.contains=function(t){return this.a.contains(t)||this.b.contains(t)},g.u=function(){return this.a.u()+this.b.u()},g.w=function(){if(Ie.L.w.call(this),0<this.b.u())throw Error("[goog.structs.Pool] Objects not released");delete this.b;for(var t=this.a;0!=t.b.length||0!=t.a.length;)Ke(He(t));delete this.a},Me.prototype.A=function(){for(var t=this.a,e=[],n=t.length,r=0;r<n;r++)e.push(t[r].b);return e},Me.prototype.O=function(){for(var t=this.a,e=[],n=t.length,r=0;r<n;r++)e.push(t[r].a);return e},Me.prototype.u=function(){return this.a.length},u(Oe,Me),u(Y,Ie),g=Y.prototype,g.ca=function(t,e){if(!t)return Y.L.ca.call(this);Ne(this.f,void 0!==e?e:100,t),this.ua()},g.ua=function(){for(var t=this.f;0<t.u();){var e=this.ca();if(!e)break;var n=t,r=n.a,i=r.length,o=r[0];if(0>=i)o=void 0;else{if(1==i)wa(r);else{r[0]=r.pop(),r=0,n=n.a,i=n.length;for(var a=n[r];r<i>>1;){var s=2*r+1,u=2*r+2;if(s=u<i&&n[u].a<n[s].a?u:s,n[s].a>a.a)break;n[r]=n[s],r=s}n[r]=a}o=o.b}o.apply(this,[e])}},g.ma=function(t){Y.L.ma.call(this,t),this.ua()},g.aa=function(){Y.L.aa.call(this),this.ua()},g.w=function(){Y.L.w.call(this),k.clearTimeout(void 0),wa(this.f.a),this.f=null},u(Z,Y),Z.prototype.qa=function(){var t=new U,e=this.l;return e&&e.forEach(function(e,n){t.headers.set(n,e)}),this.j&&(t.m=!0),t},Z.prototype.va=function(t){return!t.i&&!t.a},Be.prototype.createWebChannel=Be.prototype.a,X.prototype.send=X.prototype.l,X.prototype.open=X.prototype.j,X.prototype.close=X.prototype.close,yc.NO_ERROR=0,yc.TIMEOUT=8,yc.HTTP_ERROR=6,zc.COMPLETE="complete",Dd.EventType=Ed,Ed.OPEN="a",Ed.CLOSE="b",Ed.ERROR="c",Ed.MESSAGE="d",B.prototype.listen=B.prototype.$,Z.prototype.getObject=Z.prototype.ca,Z.prototype.releaseObject=Z.prototype.hb,U.prototype.listenOnce=U.prototype.Ia,U.prototype.getLastError=U.prototype.$a,U.prototype.getLastErrorCode=U.prototype.Ga,U.prototype.getStatus=U.prototype.V,U.prototype.getStatusText=U.prototype.Ha,U.prototype.getResponseJson=U.prototype.Za,U.prototype.getResponseText=U.prototype.U,U.prototype.getResponseText=U.prototype.U,U.prototype.send=U.prototype.ta,module.exports={createWebChannelTransport:Fe,ErrorCode:yc,EventType:zc,WebChannel:Dd,XhrIoPool:Z}}).call("undefined"!=typeof window?window:this)}},[113])}catch(t){throw Error("Cannot instantiate firebase-firestore.js - be sure to load firebase-app.js first.")}
  //# sourceMappingURL=firebase-firestore.js.map