PageSourceSearch

https://vietlott.mobi/_next/static/chunks/484bcb1e.b89bbbe386840761a5ac.js

js vietlott.mobi collected 2026-10-07 19:51:22 UTC 329,916 bytes, 1 lines download raw bytes

1(window.webpackJsonp_N_E=window.webpackJsonp_N_E||[]).push([[6],{"6Joi":function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var r,i,o=(r=n("wj3C"))&&"object"===typeof r&&"default"in r?r.default:r,a=n("mrSG"),s=n("q/0M"),u=n("zVF4"),c=n("x7I3"),h=o.SDK_VERSION,l=new s.Logger("@firebase/firestore");function f(){return l.logLevel===s.LogLevel.DEBUG?i.DEBUG:l.logLevel===s.LogLevel.SILENT?i.SILENT:i.ERROR}function d(e){switch(e){case i.DEBUG:l.logLevel=s.LogLevel.DEBUG;break;case i.ERROR:l.logLevel=s.LogLevel.ERROR;break;case i.SILENT:l.logLevel=s.LogLevel.SILENT;break;default:l.error("Firestore ("+h+"): Invalid value passed to `setLogLevel`")}}function p(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(l.logLevel<=s.LogLevel.DEBUG){var i=n.map(y);l.debug.apply(l,a.__spreadArrays(["Firestore ("+h+") ["+e+"]: "+t],i))}}function m(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(l.logLevel<=s.LogLevel.ERROR){var r=t.map(y);l.error.apply(l,a.__spreadArrays(["Firestore ("+h+"): "+e],r))}}function y(e){if("string"===typeof e)return e;var t=w.getPlatform();try{return t.formatJSON(e)}catch(n){return e}}function g(e){var t="FIRESTORE ("+h+") INTERNAL ASSERTION FAILED: "+e;throw m(t),new Error(t)}function v(e,t){e||g(t)}!function(e){e[e.DEBUG=0]="DEBUG",e[e.ERROR=1]="ERROR",e[e.SILENT=2]="SILENT"}(i||(i={}));var w=function(){function e(){}return e.setPlatform=function(t){e.platform&&g("Platform already defined"),e.platform=t},e.getPlatform=function(){return e.platform||g("Platform not set"),e.platform},e}();function b(){return w.getPlatform().emptyByteString}var S={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"},T=function(e){function t(t,n){var r=e.call(this,n)||this;return r.code=t,r.message=n,r.name="FirebaseError",r.toString=function(){return r.name+": [code="+r.code+"]: "+r.message},r}return a.__extends(t,e),t}(Error);function E(e,t){function n(){var e="This constructor is private.";throw t&&(e+=" ",e+=t),new T(S.INVALID_ARGUMENT,e)}for(var r in n.prototype=e.prototype,e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function I(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function C(e,t){return void 0!==e?e:t}function D(e,t){for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var r=Number(n);isNaN(r)||t(r,e[n])}}function _(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function N(e){for(var t in v(null!=e&&"object"===typeof e,"isEmpty() expects object parameter."),e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function A(e,t){if(0!==t.length)throw new T(S.INVALID_ARGUMENT,"Function "+e+"() does not support arguments, but was called with "+H(t.length,"argument")+".")}function k(e,t,n){if(t.length!==n)throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires "+H(n,"argument")+", but was called with "+H(t.length,"argument")+".")}function R(e,t,n){if(t.length<n)throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires at least "+H(n,"argument")+", but was called with "+H(t.length,"argument")+".")}function M(e,t,n,r){if(t.length<n||t.length>r)throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires between "+n+" and "+r+" arguments, but was called with "+H(t.length,"argument")+".")}function L(e,t,n,r){if(!(t instanceof Array)||t.length<r)throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires its "+n+" argument to be an array with at least "+H(r,"element")+".")}function O(e,t,n,r){U(e,t,j(n)+" argument",r)}function P(e,t,n,r){void 0!==r&&O(e,t,n,r)}function x(e,t,n,r){U(e,t,n+" option",r)}function q(e,t,n,r){void 0!==r&&x(e,t,n,r)}function V(e,t,n,r,i){void 0!==r&&function(e,t,n,r,i){if(!(r instanceof Array))throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires its "+t+" option to be an array, but it was: "+K(r));for(var o=0;o<r.length;++o)if(!i(r[o]))throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires all "+t+" elements to be "+n+", but the value at index "+o+" was: "+K(r[o]))}(e,t,n,r,i)}function F(e,t,n,r,i){void 0!==r&&function(e,t,n,r,i){for(var o=[],a=0,s=i;a<s.length;a++){var u=s[a];if(u===r)return;o.push(K(u))}var c=K(r);throw new T(S.INVALID_ARGUMENT,"Invalid value "+c+" provided to function "+e+'() for option "'+n+'". Acceptable values: '+o.join(", "))}(e,0,n,r,i)}function B(e,t,n,r){if(!t.some((function(e){return e===r})))throw new T(S.INVALID_ARGUMENT,"Invalid value "+K(r)+" provided to function "+e+"() for its "+j(n)+" argument. Acceptable values: "+t.join(", "))}function U(e,t,n,r){if(!("object"===t?Q(r):"non-empty string"===t?"string"===typeof r&&""!==r:typeof r===t)){var i=K(r);throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires its "+n+" to be of type "+t+", but it was: "+i)}}function Q(e){return"object"===typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function K(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"===typeof e)return e.length>20&&(e=e.substring(0,20)+"..."),JSON.stringify(e);if("number"===typeof e||"boolean"===typeof e)return""+e;if("object"===typeof e){if(e instanceof Array)return"an array";var t=function(e){if(e.constructor){var t=/function\s+([^\s(]+)\s*\(/.exec(e.constructor.toString());if(t&&t.length>1)return t[1]}return null}(e);return t?"a custom "+t+" object":"an object"}return"function"===typeof e?"a function":g("Unknown wrong type: "+typeof e)}function W(e,t,n){if(void 0===n)throw new T(S.INVALID_ARGUMENT,"Function "+e+"() requires a valid "+j(t)+" argument, but it was undefined.")}function G(e,t,n){_(t,(function(t,r){if(n.indexOf(t)<0)throw new T(S.INVALID_ARGUMENT,"Unknown option '"+t+"' passed to function "+e+"(). Available options: "+n.join(", "))}))}function z(e,t,n,r){var i=K(r);return new T(S.INVALID_ARGUMENT,"Function "+e+"() requires its "+j(n)+" argument to be a "+t+", but it was: "+i)}function j(e){switch(e){case 1:return"first";
1case 2:return"second";case 3:return"third";default:return e+"th"}}function H(e,t){return e+" "+t+(1===e?"":"s")}var Y=function(){function e(){}return e.newId=function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="",n=0;n<20;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return v(20===t.length,"Invalid auto ID: "+t),t},e}();function J(e,t){return e<t?-1:e>t?1:0}function X(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!e[n].isEqual(t[n]))return!1;return!0}function Z(e){return e+"\0"}function $(){if("undefined"===typeof Uint8Array)throw new T(S.UNIMPLEMENTED,"Uint8Arrays are not available in this environment.")}function ee(){if(!w.getPlatform().base64Available)throw new T(S.UNIMPLEMENTED,"Blobs are unavailable in Firestore in this environment.")}var te,ne=function(){function e(e){ee(),this._binaryString=e}return e.fromBase64String=function(t){k("Blob.fromBase64String",arguments,1),O("Blob.fromBase64String","string",1,t),ee();try{var n=w.getPlatform().atob(t);return new e(n)}catch(r){throw new T(S.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+r)}},e.fromUint8Array=function(t){if(k("Blob.fromUint8Array",arguments,1),$(),!(t instanceof Uint8Array))throw z("Blob.fromUint8Array","Uint8Array",1,t);var n=Array.prototype.map.call(t,(function(e){return String.fromCharCode(e)})).join("");return new e(n)},e.prototype.toBase64=function(){return k("Blob.toBase64",arguments,0),ee(),w.getPlatform().btoa(this._binaryString)},e.prototype.toUint8Array=function(){k("Blob.toUint8Array",arguments,0),$();for(var e=new Uint8Array(this._binaryString.length),t=0;t<this._binaryString.length;t++)e[t]=this._binaryString.charCodeAt(t);return e},e.prototype.toString=function(){return"Blob(base64: "+this.toBase64()+")"},e.prototype.isEqual=function(e){return this._binaryString===e._binaryString},e.prototype._compareTo=function(e){return J(this._binaryString,e._binaryString)},e}(),re=E(ne,"Use Blob.fromUint8Array() or Blob.fromBase64String() instead."),ie=function(e,t,n,r,i){this.databaseId=e,this.persistenceKey=t,this.host=n,this.ssl=r,this.forceLongPolling=i},oe="(default)",ae=function(){function e(e,t){this.projectId=e,this.database=t||oe}return Object.defineProperty(e.prototype,"isDefaultDatabase",{get:function(){return this.database===oe},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){return t instanceof e&&t.projectId===this.projectId&&t.database===this.database},e.prototype.compareTo=function(e){return J(this.projectId,e.projectId)||J(this.database,e.database)},e}(),se=function(){function e(e,t){var n=this;this.previousValue=e,t&&(t.sequenceNumberHandler=function(e){return n.setPreviousValue(e)},this.writeNewSequenceNumber=function(e){return t.writeSequenceNumber(e)})}return e.prototype.setPreviousValue=function(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue},e.prototype.next=function(){var e=++this.previousValue;return this.writeNewSequenceNumber&&this.writeNewSequenceNumber(e),e},e.INVALID=-1,e}(),ue="__name__",ce=function(){function e(e,t,n){void 0===t?t=0:t>e.length&&g("offset "+t+" out of range "+e.length),void 0===n?n=e.length-t:n>e.length-t&&g("length "+n+" out of range "+(e.length-t)),this.segments=e,this.offset=t,this.len=n}return Object.defineProperty(e.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){return 0===e.comparator(this,t)},e.prototype.child=function(t){var n=this.segments.slice(this.offset,this.limit());return t instanceof e?t.forEach((function(e){n.push(e)})):n.push(t),this.construct(n)},e.prototype.limit=function(){return this.offset+this.length},e.prototype.popFirst=function(e){return e=void 0===e?1:e,v(this.length>=e,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+e,this.length-e)},e.prototype.popLast=function(){return v(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},e.prototype.firstSegment=function(){return v(!this.isEmpty(),"Can't 
1call firstSegment() on empty path"),this.segments[this.offset]},e.prototype.lastSegment=function(){return this.get(this.length-1)},e.prototype.get=function(e){return v(e<this.length,"Index out of range"),this.segments[this.offset+e]},e.prototype.isEmpty=function(){return 0===this.length},e.prototype.isPrefixOf=function(e){if(e.length<this.length)return!1;for(var t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0},e.prototype.isImmediateParentOf=function(e){if(this.length+1!==e.length)return!1;for(var t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0},e.prototype.forEach=function(e){for(var t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])},e.prototype.toArray=function(){return this.segments.slice(this.offset,this.limit())},e.comparator=function(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++){var i=e.get(r),o=t.get(r);if(i<o)return-1;if(i>o)return 1}return e.length<t.length?-1:e.length>t.length?1:0},e}(),he=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a.__extends(t,e),t.prototype.construct=function(e,n,r){return new t(e,n,r)},t.prototype.canonicalString=function(){return this.toArray().join("/")},t.prototype.toString=function(){return this.canonicalString()},t.fromString=function(e){if(e.indexOf("//")>=0)throw new T(S.INVALID_ARGUMENT,"Invalid path ("+e+"). Paths must not contain // in them.");return new t(e.split("/").filter((function(e){return e.length>0})))},t.EMPTY_PATH=new t([]),t}(ce),le=/^[_a-zA-Z][_a-zA-Z0-9]*$/,fe=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a.__extends(t,e),t.prototype.construct=function(e,n,r){return new t(e,n,r)},t.isValidIdentifier=function(e){return le.test(e)},t.prototype.canonicalString=function(){return this.toArray().map((function(e){return e=e.replace("\\","\\\\").replace("`","\\`"),t.isValidIdentifier(e)||(e="`"+e+"`"),e})).join(".")},t.prototype.toString=function(){return this.canonicalString()},t.prototype.isKeyField=function(){return 1===this.length&&this.get(0)===ue},t.keyField=function(){return new t([ue])},t.fromServerFormat=function(e){for(var n=[],r="",i=0,o=function(){if(0===r.length)throw new T(S.INVALID_ARGUMENT,"Invalid field path ("+e+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},a=!1;i<e.length;){var s=e[i];if("\\"===s){if(i+1===e.length)throw new T(S.INVALID_ARGUMENT,"Path has trailing escape character: "+e);var u=e[i+1];if("\\"!==u&&"."!==u&&"`"!==u)throw new T(S.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);r+=u,i+=2}else"`"===s?(a=!a,i++):"."!==s||a?(r+=s,i++):(o(),i++)}if(o(),a)throw new T(S.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new t(n)},t.EMPTY_PATH=new t([]),t}(ce),de=function(){function e(t){this.path=t,v(e.isDocumentKey(t),"Invalid DocumentKey with an odd number of segments: "+t.toArray().join("/"))}return e.prototype.hasCollectionId=function(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e},e.prototype.isEqual=function(e){return null!==e&&0===he.comparator(this.path,e.path)},e.prototype.toString=function(){return this.path.toString()},e.comparator=function(e,t){return he.comparator(e.path,t.path)},e.isDocumentKey=function(e){return e.length%2===0},e.fromSegments=function(t){return new e(new he(t.slice()))},e.fromPathString=function(t){return new e(he.fromString(t))},e.EMPTY=new e(new he([])),e}(),pe=function(){var e=this;this.promise=new Promise((function(t,n){e.resolve=t,e.reject=n}))};!function(e){e.All="all",e.ListenStreamIdle="listen_stream_idle",e.ListenStreamConnectionBackoff="listen_stream_connection_backoff",e.WriteStreamIdle="write_stream_idle",e.WriteStreamConnectionBackoff="write_stream_connection_backoff",e.OnlineStateTimeout="online_state_timeout",e.ClientMetadataRefresh="client_metadata_refresh",e.LruGarbageCollection="lru_garbage_collection",e.RetryTransaction="retry_transaction"}(te||(te={}));var me=function(){function e(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new pe,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.catch=this.deferred.promise.catch.bind(this.deferred.promise),this.deferred.promise.catch((function(e){}))}return e.createAndSchedule=function(t,n,r,i,o){var a=new e(t,n,Date.now()+r,i,o);return a.start(r),a},e.prototype.start=function(e){var t=this;this.timerHandle=setTimeout((function(){return t.handleDelayElapsed()}),e)},e.prototype.skipDelay=function(){return this.handleDelayElapsed()},e.prototype.cancel=function(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new T(S.CANCELLED,"Operation cancelled"+(e?": "+e:""))))},e.prototype.handleDelayElapsed=function(){var e=this;this.asyncQueue.enqueueAndForget((function(){return null!==e.timerHandle?(e.clearTimeout(),e.op().then((function(t){return e.deferred.resolve(t)}))):Promise.resolve()}))},e.prototype.clearTimeout=function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)},e}(),ye=function(){function e(){this.tail=Promise.resolve(),this._isShuttingDown=!1,this.delayedOperations=[],this.failure=null,this.operationInProgress=!1,this.timerIdsToSkip=[]}return Object.defineProperty(e.prototype,"isShuttingDown",{get:function(){return this._isShuttingDown},enumerable:!0,configurable:!0}),e.prototype.enqueueAndForget=function(e){this.enqueue(e)},e.prototype.enqueueAndForgetEvenAfterShutdown=function(e){this.verifyNotFailed(),this.enqueueInternal(e)},e.prototype.enqueueEvenAfterShutdown=function(e){return this.verifyNotFailed(),this.enqueueInternal(e)},e.prototype.enqueueAndInitiateShutdown=function(e){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(t){switch(t.label){case 0:return this.verifyNotFailed(),this._isShuttingDown?[3,2]:(this._isShuttingDown=!0,[4,this.enqueueEvenAfterShutdown(e)]);case 1:t.sent(),t.label=2;case 2:return[2]}}
1))}))},e.prototype.enqueue=function(e){return this.verifyNotFailed(),this._isShuttingDown?new Promise((function(e){})):this.enqueueInternal(e)},e.prototype.enqueueInternal=function(e){var t=this,n=this.tail.then((function(){return t.operationInProgress=!0,e().catch((function(e){t.failure=e,t.operationInProgress=!1;var n=e.stack||e.message||"";throw m("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout((function(){throw e}),0),e})).then((function(e){return t.operationInProgress=!1,e}))}));return this.tail=n,n},e.prototype.enqueueAfterDelay=function(e,t,n){var r=this;this.verifyNotFailed(),v(t>=0,"Attempted to schedule an operation with a negative delay of "+t),this.timerIdsToSkip.indexOf(e)>-1&&(t=0);var i=me.createAndSchedule(this,e,t,n,(function(e){return r.removeDelayedOperation(e)}));return this.delayedOperations.push(i),i},e.prototype.verifyNotFailed=function(){this.failure&&g("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},e.prototype.verifyOperationInProgress=function(){v(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},e.prototype.drain=function(){return this.enqueueEvenAfterShutdown((function(){return Promise.resolve()}))},e.prototype.containsDelayedOperation=function(e){for(var t=0,n=this.delayedOperations;t<n.length;t++){if(n[t].timerId===e)return!0}return!1},e.prototype.runDelayedOperationsEarly=function(e){var t=this;return this.drain().then((function(){v(e===te.All||t.containsDelayedOperation(e),"Attempted to drain to missing operation "+e),t.delayedOperations.sort((function(e,t){return e.targetTimeMs-t.targetTimeMs}));for(var n=0,r=t.delayedOperations;n<r.length;n++){var i=r[n];if(i.skipDelay(),e!==te.All&&i.timerId===e)break}return t.drain()}))},e.prototype.skipDelaysForTimerId=function(e){this.timerIdsToSkip.push(e)},e.prototype.removeDelayedOperation=function(e){var t=this.delayedOperations.indexOf(e);v(t>=0,"Delayed operation not found."),this.delayedOperations.splice(t,1)},e}(),ge="\x01";function ve(e){for(var t="",n=0;n<e.length;n++)t.length>0&&(t=be(t)),t=we(e.get(n),t);return be(t)}function we(e,t){for(var n=t,r=e.length,i=0;i<r;i++){var o=e.charAt(i);switch(o){case"\0":n+="\x01\x10";break;case ge:n+="\x01\x11";break;default:n+=o}}return n}function be(e){return e+ge+"\x01"}function Se(e){var t=e.length;if(v(t>=2,"Invalid path "+e),2===t)return v(e.charAt(0)===ge&&"\x01"===e.charAt(1),"Non-empty path "+e+" had length 2"),he.EMPTY_PATH;for(var n=t-2,r=[],i="",o=0;o<t;){var a=e.indexOf(ge,o);switch((a<0||a>n)&&g('Invalid encoded resource path: "'+e+'"'),e.charAt(a+1)){case"\x01":var s=e.substring(o,a),u=void 0;0===i.length?u=s:(u=i+=s,i=""),r.push(u);break;case"\x10":i+=e.substring(o,a),i+="\0";break;case"\x11":i+=e.substring(o,a+1);break;default:g('Invalid encoded resource path: "'+e+'"')}o=a+2}return new he(r)}var Te=function(){function e(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new T(S.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new T(S.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new T(S.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new T(S.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}return e.now=function(){return e.fromMillis(Date.now())},e.fromDate=function(t){return e.fromMillis(t.getTime())},e.fromMillis=function(t){var n=Math.floor(t/1e3);return new e(n,1e6*(t-1e3*n))},e.prototype.toDate=function(){return new Date(this.toMillis())},e.prototype.toMillis=function(){return 1e3*this.seconds+this.nanoseconds/1e6},e.prototype._compareTo=function(e){return this.seconds===e.seconds?J(this.nanoseconds,e.nanoseconds):J(this.seconds,e.seconds)},e.prototype.isEqual=function(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds},e.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"},e}(),Ee=function(){function e(e){this.timestamp=e}return e.fromMicroseconds=function(t){var n=Math.floor(t/1e6);return new e(new Te(n,t%1e6*1e3))},e.fromTimestamp=function(t){return new e(t)},e.forDeletedDoc=function(){return e.MIN},e.prototype.compareTo=function(e){return this.timestamp._compareTo(e.timestamp)},e.prototype.isEqual=function(e){return this.timestamp.isEqual(e.timestamp)},e.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3},e.prototype.toString=function(){return"SnapshotVersion("+this.timestamp.toString()+")"},e.prototype.toTimestamp=function(){return this.timestamp},e.MIN=new e(new Te(0,0)),e}(),Ie=function(){function e(e,t){this.comparator=e,this.root=t||De.EMPTY}return e.prototype.insert=function(t,n){return new e(this.comparator,this.root.insert(t,n,this.comparator).copy(null,null,De.BLACK,null,
1null))},e.prototype.remove=function(t){return new e(this.comparator,this.root.remove(t,this.comparator).copy(null,null,De.BLACK,null,null))},e.prototype.get=function(e){for(var t=this.root;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null},e.prototype.indexOf=function(e){for(var t=0,n=this.root;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1},e.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(e.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),e.prototype.minKey=function(){return this.root.minKey()},e.prototype.maxKey=function(){return this.root.maxKey()},e.prototype.inorderTraversal=function(e){return this.root.inorderTraversal(e)},e.prototype.forEach=function(e){this.inorderTraversal((function(t,n){return e(t,n),!1}))},e.prototype.toString=function(){var e=[];return this.inorderTraversal((function(t,n){return e.push(t+":"+n),!1})),"{"+e.join(", ")+"}"},e.prototype.reverseTraversal=function(e){return this.root.reverseTraversal(e)},e.prototype.getIterator=function(){return new Ce(this.root,null,this.comparator,!1)},e.prototype.getIteratorFrom=function(e){return new Ce(this.root,e,this.comparator,!1)},e.prototype.getReverseIterator=function(){return new Ce(this.root,null,this.comparator,!0)},e.prototype.getReverseIteratorFrom=function(e){return new Ce(this.root,e,this.comparator,!0)},e}(),Ce=function(){function e(e,t,n,r){this.isReverse=r,this.nodeStack=[];for(var i=1;!e.isEmpty();)if(i=t?n(e.key,t):1,r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}return e.prototype.getNext=function(){v(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t},e.prototype.hasNext=function(){return this.nodeStack.length>0},e.prototype.peek=function(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}},e}(),De=function(){function e(t,n,r,i,o){this.key=t,this.value=n,this.color=null!=r?r:e.RED,this.left=null!=i?i:e.EMPTY,this.right=null!=o?o:e.EMPTY,this.size=this.left.size+1+this.right.size}return e.prototype.copy=function(t,n,r,i,o){return new e(null!=t?t:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},e.prototype.isEmpty=function(){return!1},e.prototype.inorderTraversal=function(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)},e.prototype.reverseTraversal=function(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)},e.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},e.prototype.minKey=function(){return this.min().key},e.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},e.prototype.insert=function(e,t,n){var r=this,i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp()},e.prototype.removeMin=function(){if(this.left.isEmpty())return e.EMPTY;var t=this;return t.left.isRed()||t.left.left.isRed()||(t=t.moveRedLeft()),(t=t.copy(null,null,null,t.left.removeMin(),null)).fixUp()},e.prototype.remove=function(t,n){var r,i=this;if(n(t,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(t,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(t,i.key)){if(i.right.isEmpty())return e.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(t,n))}return i.fixUp()},e.prototype.isRed=function(){return this.color},e.prototype.fixUp=function(){var e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e},e.prototype.moveRedLeft=function(){var e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e},e.prototype.moveRedRight=function(){var e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e},e.prototype.rotateLeft=function(){var t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)},e.prototype.rotateRight=function(){var t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)},e.prototype.colorFlip=function(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)},e.prototype.checkMaxDepth=function(){var e=this.check();return Math.pow(2,e)<=this.size+1},e.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw g("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw g("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check();if(e!==this.right.check())throw g("Black depths differ");return e+(this.isRed()?0:1)},e.EMPTY=null,e.RED=!0,e.BLACK=!1,e}(),_e=function(){function e(){this.size=0}return Object.defineProperty(e.prototype,"key",{get:function(){throw g("LLRBEmptyNode has no key.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){throw g("LLRBEmptyNode has no value.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"color",{get:function(){throw g("LLRBEmptyNode has no color.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"left",{get:function(){throw g("LLRBEmptyNode has no left child.")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"right",{get:function(){throw g("LLRBEmptyNode has no right child.")},enumerable:!0,configurable:!0}),e.prototype.copy=function(e,t,n,r,i){return this},e.prototype.insert=function(e,t,n){return new De(e,t)},e.prototype.remove=function(e,t){return this},e.prototype.isEmpty=function(){return!0},e.prototype.inorderTraversal=function(e){return!1},e.prototype.reverseTraversal=function(e){return!1},e.prototype.minKey=function(){return null},e.prototype.maxKey=function(){return null},e.prototype.isRed=function(){return!1},e.prototype.checkMaxDepth=function(){return!0},e.prototype.check=function(){return 0},e}();
1De.EMPTY=new _e;var Ne=function(){function e(e){this.comparator=e,this.data=new Ie(this.comparator)}return e.fromMapKeys=function(t){var n=new e(t.comparator);return t.forEach((function(e){n=n.add(e)})),n},e.prototype.has=function(e){return null!==this.data.get(e)},e.prototype.first=function(){return this.data.minKey()},e.prototype.last=function(){return this.data.maxKey()},Object.defineProperty(e.prototype,"size",{get:function(){return this.data.size},enumerable:!0,configurable:!0}),e.prototype.indexOf=function(e){return this.data.indexOf(e)},e.prototype.forEach=function(e){this.data.inorderTraversal((function(t,n){return e(t),!1}))},e.prototype.forEachInRange=function(e,t){for(var n=this.data.getIteratorFrom(e[0]);n.hasNext();){var r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}},e.prototype.forEachWhile=function(e,t){var n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();){if(!e(n.getNext().key))return}},e.prototype.firstAfterOrEqual=function(e){var t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null},e.prototype.getIterator=function(){return new Ae(this.data.getIterator())},e.prototype.getIteratorFrom=function(e){return new Ae(this.data.getIteratorFrom(e))},e.prototype.add=function(e){return this.copy(this.data.remove(e).insert(e,!0))},e.prototype.delete=function(e){return this.has(e)?this.copy(this.data.remove(e)):this},e.prototype.isEmpty=function(){return this.data.isEmpty()},e.prototype.unionWith=function(e){var t=this;return e.forEach((function(e){t=t.add(e)})),t},e.prototype.isEqual=function(t){if(!(t instanceof e))return!1;if(this.size!==t.size)return!1;for(var n=this.data.getIterator(),r=t.data.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(0!==this.comparator(i,o))return!1}return!0},e.prototype.toArray=function(){var e=[];return this.forEach((function(t){e.push(t)})),e},e.prototype.toString=function(){var e=[];return this.forEach((function(t){return e.push(t)})),"SortedSet("+e.toString()+")"},e.prototype.copy=function(t){var n=new e(this.comparator);return n.data=t,n},e}(),Ae=function(){function e(e){this.iter=e}return e.prototype.getNext=function(){return this.iter.getNext().key},e.prototype.hasNext=function(){return this.iter.hasNext()},e}(),ke=new Ie(de.comparator);function Re(){return ke}function Me(){return Re()}var Le=new Ie(de.comparator);function Oe(){return Le}var Pe=new Ie(de.comparator);function xe(){return Pe}var qe=new Ne(de.comparator);function Ve(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=qe,r=0,i=e;r<i.length;r++){var o=i[r];n=n.add(o)}return n}var Fe=new Ne(J);function Be(){return Fe}var Ue=-1,Qe=function(){function e(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r,v(r.length>0,"Cannot create an empty mutation batch")}return e.prototype.applyToRemoteDocument=function(e,t,n){t&&v(t.key.isEqual(e),"applyToRemoteDocument: key "+e+" should match maybeDoc key\n        "+t.key);var r=n.mutationResults;v(r.length===this.mutations.length,"Mismatch between mutations length\n      ("+this.mutations.length+") and mutation results length\n      ("+r.length+").");for(var i=0;i<this.mutations.length;i++){var o=this.mutations[i];if(o.key.isEqual(e)){var a=r[i];t=o.applyToRemoteDocument(t,a)}}return t},e.prototype.applyToLocalView=function(e,t){t&&v(t.key.isEqual(e),"applyToLocalDocument: key "+e+" should match maybeDoc key\n        "+t.key);for(var n=0,r=this.baseMutations;n<r.length;n++){(s=r[n]).key.isEqual(e)&&(t=s.applyToLocalView(t,t,this.localWriteTime))}for(var i=t,o=0,a=this.mutations;o<a.length;o++){var s;(s=a[o]).key.isEqual(e)&&(t=s.applyToLocalView(t,i,this.localWriteTime))}return t},e.prototype.applyToLocalDocumentSet=function(e){var t=this,n=e;return this.mutations.forEach((function(r){var i=t.applyToLocalView(r.key,e.get(r.key));i&&(n=n.insert(r.key,i))})),n},e.prototype.keys=function(){return this.mutations.reduce((function(e,t){return e.add(t.key)}),Ve())},e.prototype.isEqual=function(e){return this.batchId===e.batchId&&X(this.mutations,e.mutations)&&X(this.baseMutations,e.baseMutations)},e}(),Ke=function(){function e(e,t,n,r,i){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.streamToken=r,this.docVersions=i}return e.from=function(t,n,r,i){v(t.mutations.length===r.length,"Mutations sent "+t.mutations.length+" must equal results received "+r.length);for(var o=xe(),a=t.mutations,s=0;s<a.length;s++)o=o.insert(a[s].key,r[s].version);return new e(t,n,r,i,o)},e}(),We=function(){function e(e){var t=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e((function(e){t.isDone=!0,t.result=e,t.nextCallback&&t.nextCallback(e)}),(function(e){t.isDone=!0,t.error=e,t.catchCallback&&t.catchCallback(e)}))}return e.prototype.catch=function(e){return this.next(void 0,e)},e.prototype.next=function(t,n){var r=this;return this.callbackAttached&&g("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(t,this.result):new e((function(e,i){r.nextCallback=function(n){r.wrapSuccess(t,n).next(e,i)},r.catchCallback=function(t){r.wrapFailure(n,t).next(e,i)}}))},e.prototype.toPromise=function(){var e=this;return new Promise((function(t,n){e.next(t,n)}))},e.prototype.wrapUserFunction=function(t){try{var n=t();return n instanceof e?n:e.resolve(n)}catch(r){return e.reject(r)}},e.prototype.wrapSuccess=function(t,n){return t?this.wrapUserFunction((function(){return t(n)})):e.resolve(n)},e.prototype.wrapFailure=function(t,n){return t?this.wrapUserFunction((function(){return t(n)})):e.reject(n)},e.resolve=function(t){return new e((function(e,n){e(t)}))}
1,e.reject=function(t){return new e((function(e,n){n(t)}))},e.waitFor=function(t){return new e((function(e,n){var r=0,i=0,o=!1;t.forEach((function(t){++r,t.next((function(){++i,o&&i===r&&e()}),(function(e){return n(e)}))})),o=!0,i===r&&e()}))},e.or=function(t){for(var n=e.resolve(!1),r=function(t){n=n.next((function(n){return n?e.resolve(n):t()}))},i=0,o=t;i<o.length;i++){r(o[i])}return n},e.forEach=function(e,t){var n=this,r=[];return e.forEach((function(e,i){r.push(t.call(n,e,i))})),this.waitFor(r)},e}(),Ge="SimpleDb",ze=function(){function t(e){this.db=e,12.2===t.getIOSVersion(u.getUA())&&m("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}return t.openOrCreate=function(e,n,r){return v(t.isAvailable(),"IndexedDB not supported in current environment."),p(Ge,"Opening database:",e),new We((function(i,o){var a=window.indexedDB.open(e,n);a.onsuccess=function(e){var n=e.target.result;i(new t(n))},a.onblocked=function(){o(new T(S.FAILED_PRECONDITION,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},a.onerror=function(e){var t=e.target.error;"VersionError"===t.name?o(new T(S.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):o(t)},a.onupgradeneeded=function(t){p(Ge,'Database "'+e+'" requires upgrade from version:',t.oldVersion);var n=t.target.result;r.createOrUpgrade(n,a.transaction,t.oldVersion,en).next((function(){p(Ge,"Database upgrade to version "+en+" complete")}))}})).toPromise()},t.delete=function(e){return p(Ge,"Removing database:",e),Je(window.indexedDB.deleteDatabase(e)).toPromise()},t.isAvailable=function(){if("undefined"===typeof window||null==window.indexedDB)return!1;if(t.isMockPersistence())return!0;if(void 0===window.navigator)return!1;var e=u.getUA(),n=t.getIOSVersion(e),r=0<n&&n<10,i=t.getAndroidVersion(e),o=0<i&&i<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||r||o)},t.isMockPersistence=function(){return"undefined"!==typeof e&&"YES"===e.env.USE_MOCK_PERSISTENCE},t.getStore=function(e,t){return e.store(t)},t.getIOSVersion=function(e){var t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)},t.getAndroidVersion=function(e){var t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)},t.prototype.setVersionChangeListener=function(e){this.db.onversionchange=function(t){return e(t)}},t.prototype.runTransaction=function(e,t,n){return a.__awaiter(this,void 0,void 0,(function(){var r,i,o,s,u,c;return a.__generator(this,(function(h){switch(h.label){case 0:r=e.startsWith("readonly"),i=e.endsWith("idempotent"),o=0,s=function(){var e,s,c,h;return a.__generator(this,(function(a){switch(a.label){case 0:++o,e=He.open(u.db,r?"readonly":"readwrite",t),a.label=1;case 1:return a.trys.push([1,3,,4]),(s=n(e).catch((function(t){return e.abort(t),We.reject(t)})).toPromise()).catch((function(){})),[4,e.completionPromise];case 2:return a.sent(),[2,{value:s}];case 3:return c=a.sent(),h=i&&"FirebaseError"!==c.name&&o<3,p(Ge,"Transaction failed with error: %s. Retrying: %s.",c.message,h),h?[3,4]:[2,{value:Promise.reject(c)}];case 4:return[2]}}
1))},u=this,h.label=1;case 1:return[5,s()];case 2:return"object"===typeof(c=h.sent())?[2,c.value]:[3,1];case 3:return[2]}}))}))},t.prototype.close=function(){this.db.close()},t}(),je=function(){function e(e){this.dbCursor=e,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(e.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cursor",{set:function(e){this.dbCursor=e},enumerable:!0,configurable:!0}),e.prototype.done=function(){this.shouldStop=!0},e.prototype.skip=function(e){this.nextKey=e},e.prototype.delete=function(){return Je(this.dbCursor.delete())},e}(),He=function(){function e(e){var t=this;this.transaction=e,this.aborted=!1,this.completionDeferred=new pe,this.transaction.oncomplete=function(){t.completionDeferred.resolve()},this.transaction.onabort=function(){e.error?t.completionDeferred.reject(e.error):t.completionDeferred.resolve()},this.transaction.onerror=function(e){var n=Ze(e.target.error);t.completionDeferred.reject(n)}}return e.open=function(t,n,r){return new e(t.transaction(r,n))},Object.defineProperty(e.prototype,"completionPromise",{get:function(){return this.completionDeferred.promise},enumerable:!0,configurable:!0}),e.prototype.abort=function(e){e&&this.completionDeferred.reject(e),this.aborted||(p(Ge,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())},e.prototype.store=function(e){var t=this.transaction.objectStore(e);return v(!!t,"Object store not part of transaction: "+e),new Ye(t)},e}(),Ye=function(){function e(e){this.store=e}return e.prototype.put=function(e,t){var n;return void 0!==t?(p(Ge,"PUT",this.store.name,e,t),n=this.store.put(t,e)):(p(Ge,"PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),Je(n)},e.prototype.add=function(e){return p(Ge,"ADD",this.store.name,e,e),Je(this.store.add(e))},e.prototype.get=function(e){var t=this;return Je(this.store.get(e)).next((function(n){return void 0===n&&(n=null),p(Ge,"GET",t.store.name,e,n),n}))},e.prototype.delete=function(e){return p(Ge,"DELETE",this.store.name,e),Je(this.store.delete(e))},e.prototype.count=function(){return p(Ge,"COUNT",this.store.name),Je(this.store.count())},e.prototype.loadAll=function(e,t){var n=this.cursor(this.options(e,t)),r=[];return this.iterateCursor(n,(function(e,t){r.push(t)})).next((function(){return r}))},e.prototype.deleteAll=function(e,t){p(Ge,"DELETE ALL",this.store.name);var n=this.options(e,t);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,(function(e,t,n){return n.delete()}))},e.prototype.iterate=function(e,t){var n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.iterateCursor(r,t)},e.prototype.iterateSerial=function(e){var t=this.cursor({});return new We((function(n,r){t.onerror=function(e){var t=Ze(e.target.error);r(t)},t.onsuccess=function(t){var r=t.target.result;r?e(r.primaryKey,r.value).next((function(e){e?r.continue():n()})):n()}}))},e.prototype.iterateCursor=function(e,t){var n=[];return new We((function(r,i){e.onerror=function(e){i(e.target.error)},e.onsuccess=function(e){var i=e.target.result;if(i){var o=new je(i),a=t(i.primaryKey,i.value,o);if(a instanceof We){var s=a.catch((function(e){return o.done(),We.reject(e)}));n.push(s)}o.isDone?r():null===o.skipToKey?i.continue():i.continue(o.skipToKey)}else r()}})).next((function(){return We.waitFor(n)}))},e.prototype.options=function(e,t){var n=void 0;return void 0!==e&&("string"===typeof e?n=e:(v(void 0===t,"3rd argument must not be defined if 2nd is a range."),t=e)),{index:n,range:t}},e.prototype.cursor=function(e){var t="next";if(e.reverse&&(t="prev"),e.index){var n=this.store.index(e.index);return e.keysOnly?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)},e}();function Je(e){return new We((function(t,n){e.onsuccess=function(e){var n=e.target.result;t(n)},e.onerror=function(e){var t=Ze(e.target.error);n(t)}}))}var Xe=!1;function Ze(e){var t=ze.getIOSVersion(u.getUA());if(t>=12.2&&t<13){var n="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(n)>=0){var r=new T("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '"+n+"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");return Xe||(Xe=!0,setTimeout((function(){throw r}),0)),r}}return e}var $e=function(){function e(e,t,n,r){this.userId=e,this.serializer
1=t,this.indexManager=n,this.referenceDelegate=r,this.documentKeysByBatchId={}}return e.forUser=function(t,n,r,i){return v(""!==t.uid,"UserID must not be an empty string."),new e(t.isAuthenticated()?t.uid:"",n,r,i)},e.prototype.checkEmpty=function(e){var t=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return rt(e).iterate({index:an.userMutationsIndex,range:n},(function(e,n,r){t=!1,r.done()})).next((function(){return t}))},e.prototype.acknowledgeBatch=function(e,t,n){return this.getMutationQueueMetadata(e).next((function(t){return t.lastStreamToken=nt(n),ot(e).put(t)}))},e.prototype.getLastStreamToken=function(e){return this.getMutationQueueMetadata(e).next((function(e){return e.lastStreamToken}))},e.prototype.setLastStreamToken=function(e,t){return this.getMutationQueueMetadata(e).next((function(n){return n.lastStreamToken=nt(t),ot(e).put(n)}))},e.prototype.addMutationBatch=function(e,t,n,r){var i=this,o=it(e),a=rt(e);return a.add({}).next((function(s){v("number"===typeof s,"Auto-generated key is not a number");for(var u=new Qe(s,t,n,r),c=i.serializer.toDbMutationBatch(i.userId,u),h=[],l=new Ne((function(e,t){return J(e.canonicalString(),t.canonicalString())})),f=0,d=r;f<d.length;f++){var p=d[f],m=sn.key(i.userId,p.key.path,s);l=l.add(p.key.path.popLast()),h.push(a.put(c)),h.push(o.put(m,sn.PLACEHOLDER))}return l.forEach((function(t){h.push(i.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((function(){i.documentKeysByBatchId[s]=u.keys()})),We.waitFor(h).next((function(){return u}))}))},e.prototype.lookupMutationBatch=function(e,t){var n=this;return rt(e).get(t).next((function(e){return e?(v(e.userId===n.userId,"Unexpected user '"+e.userId+"' for mutation batch "+t),n.serializer.fromDbMutationBatch(e)):null}))},e.prototype.lookupMutationKeys=function(e,t){var n=this;return this.documentKeysByBatchId[t]?We.resolve(this.documentKeysByBatchId[t]):this.lookupMutationBatch(e,t).next((function(e){if(e){var r=e.keys();return n.documentKeysByBatchId[t]=r,r}return null}))},e.prototype.getNextMutationBatchAfterBatchId=function(e,t){var n=this,r=t+1,i=IDBKeyRange.lowerBound([this.userId,r]),o=null;return rt(e).iterate({index:an.userMutationsIndex,range:i},(function(e,t,i){t.userId===n.userId&&(v(t.batchId>=r,"Should have found mutation after "+r),o=n.serializer.fromDbMutationBatch(t)),i.done()})).next((function(){return o}))},e.prototype.getHighestUnacknowledgedBatchId=function(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=Ue;return rt(e).iterate({index:an.userMutationsIndex,range:t,reverse:!0},(function(e,t,r){n=t.batchId,r.done()})).next((function(){return n}))},e.prototype.getAllMutationBatches=function(e){var t=this,n=IDBKeyRange.bound([this.userId,Ue],[this.userId,Number.POSITIVE_INFINITY]);return rt(e).loadAll(an.userMutationsIndex,n).next((function(e){return e.map((function(e){return t.serializer.fromDbMutationBatch(e)}))}))},e.prototype.getAllMutationBatchesAffectingDocumentKey=function(e,t){var n=this,r=sn.prefixForPath(this.userId,t.path),i=IDBKeyRange.lowerBound(r),o=[];return it(e).iterate({range:i},(function(r,i,a){var s=r[0],u=r[1],c=r[2],h=Se(u);if(s===n.userId&&t.path.isEqual(h))return rt(e).get(c).next((function(e){if(!e)throw g("Dangling document-mutation reference found: "+r+" which points to "+c);v(e.userId===n.userId,"Unexpected user '"+e.userId+"' for mutation batch "+c),o.push(n.serializer.fromDbMutationBatch(e))}));a.done()})).next((function(){return o}))},e.prototype.getAllMutationBatchesAffectingDocumentKeys=function(e,t){var n=this,r=new Ne(J),i=[];return t.forEach((function(t){var o=sn.prefixForPath(n.userId,t.path),a=IDBKeyRange.lowerBound(o),s=it(e).iterate({range:a},(function(e,i,o){var a=e[0],s=e[1],u=e[2],c=Se(s);a===n.userId&&t.path.isEqual(c)?r=r.add(u):o.done()}));i.push(s)})),We.waitFor(i).next((function(){return n.lookupMutationBatches(e,r)}))},e.prototype.getAllMutationBatchesAffectingQuery=function(e,t){var n=this;v(!t.isDocumentQuery(),"Document queries shouldn't go down this path"),v(!t.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var r=t.path,i=r.length+1,o=sn.prefixForPath(this.userId,r),a=IDBKeyRange.lowerBound(o),s=new Ne(J);return it(e).iterate({range:a},(function(e,t,o){var a=e[0],u=e[1],c=e[2],h=Se(u);a===n.userId&&r.isPrefixOf(h)?h.length===i&&(s=s.add(c)):o.done()})).next((function(){return n.lookupMutationBatches(e,s)}))},e.prototype.lookupMutationBatches=function(e,t){var n=this,r=[],i=[];return t.forEach((function(t){i.push(rt(e).get(t).next((function(e){if(null===e)throw g("Dangling document-mutation reference found, which points to "+t);v(e.userId===n.userId,"Unexpected user '"+e.userId+"' for mutation batch "+t),r.push(n.serializer.fromDbMutationBatch(e))})))})),We.waitFor(i).next((function(){return r}))},e.prototype.removeMutationBatch=function(e,t){var n=this;return tt(e.simpleDbTransaction,this.userId,t).next((function(r){return e.addOnCommittedListener((function(){n.removeCachedMutationKeys(t.batchId)})),We.forEach(r,(function(t){return n.referenceDelegate.removeMutationReference(e,t)}))}))},e.prototype.removeCachedMutationKeys=function(e){delete this.documentKeysByBatchId[e]},e.prototype.performConsistencyCheck=function(e){var t=this;return this.checkEmpty(e).next((function(n){if(!n)return We.resolve();
1var r=IDBKeyRange.lowerBound(sn.prefixForUser(t.userId)),i=[];return it(e).iterate({range:r},(function(e,n,r){if(e[0]===t.userId){var o=Se(e[1]);i.push(o)}else r.done()})).next((function(){v(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map((function(e){return e.canonicalString()})))}))}))},e.prototype.containsKey=function(e,t){return et(e,this.userId,t)},e.prototype.getMutationQueueMetadata=function(e){var t=this;return ot(e).get(this.userId).next((function(e){return e||new on(t.userId,Ue,"")}))},e}();function et(e,t,n){var r=sn.prefixForPath(t,n.path),i=r[1],o=IDBKeyRange.lowerBound(r),a=!1;return it(e).iterate({range:o,keysOnly:!0},(function(e,n,r){var o=e[0],s=e[1];e[2];o===t&&s===i&&(a=!0),r.done()})).next((function(){return a}))}function tt(e,t,n){var r=e.store(an.store),i=e.store(sn.store),o=[],a=IDBKeyRange.only(n.batchId),s=0,u=r.iterate({range:a},(function(e,t,n){return s++,n.delete()}));o.push(u.next((function(){v(1===s,"Dangling document-mutation reference found: Missing batch "+n.batchId)})));for(var c=[],h=0,l=n.mutations;h<l.length;h++){var f=l[h],d=sn.key(t,f.key.path,n.batchId);o.push(i.delete(d)),c.push(f.key)}return We.waitFor(o).next((function(){return c}))}function nt(e){return e instanceof Uint8Array?(v(ze.isMockPersistence(),"Persisting non-string stream tokens is only supported with mock persistence."),e.toString()):e}function rt(e){return Bn.getStore(e,an.store)}function it(e){return Bn.getStore(e,sn.store)}function ot(e){return Bn.getStore(e,on.store)}var at;!function(e){e[e.QueryCache=0]="QueryCache",e[e.SyncEngine=1]="SyncEngine"}(at||(at={}));var st=function(){function e(e,t){this.generatorId=e,v((1&e)===e,"Generator ID "+e+" contains more than 1 reserved bits"),this.seek(void 0!==t?t:this.generatorId)}return e.prototype.next=function(){var e=this.nextId;return this.nextId+=2,e},e.prototype.after=function(e){return this.seek(e+2),this.next()},e.prototype.seek=function(e){v((1&e)===this.generatorId,"Cannot supply target ID from different generator ID"),this.nextId=e},e.forQueryCache=function(){return new e(at.QueryCache,2)},e.forSyncEngine=function(){return new e(at.SyncEngine)},e}(),ut=function(){function e(e,t){this.referenceDelegate=e,this.serializer=t,this.targetIdGenerator=st.forQueryCache()}return e.prototype.allocateTargetId=function(e){var t=this;return this.retrieveMetadata(e).next((function(n){return n.highestTargetId=t.targetIdGenerator.after(n.highestTargetId),t.saveMetadata(e,n).next((function(){return n.highestTargetId}))}))},e.prototype.getLastRemoteSnapshotVersion=function(e){return this.retrieveMetadata(e).next((function(e){return Ee.fromTimestamp(new Te(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))}))},e.prototype.getHighestSequenceNumber=function(e){return lt(e.simpleDbTransaction)},e.prototype.setTargetsMetadata=function(e,t,n){var r=this;return this.retrieveMetadata(e).next((function(i){return i.highestListenSequenceNumber=t,n&&(i.lastRemoteSnapshotVersion=n.toTimestamp()),t>i.highestListenSequenceNumber&&(i.highestListenSequenceNumber=t),r.saveMetadata(e,i)}))},e.prototype.addQueryData=function(e,t){var n=this;return this.saveQueryData(e,t).next((function(){return n.retrieveMetadata(e).next((function(r){return r.targetCount+=1,n.updateMetadataFromQueryData(t,r),n.saveMetadata(e,r)}))}))},e.prototype.updateQueryData=function(e,t){return this.saveQueryData(e,t)},e.prototype.removeQueryData=function(e,t){var n=this;return this.removeMatchingKeysForTargetId(e,t.targetId).next((function(){return ct(e).delete(t.targetId)})).next((function(){return n.retrieveMetadata(e)})).next((function(t){return v(t.targetCount>0,"Removing from an empty query cache"),t.targetCount-=1,n.saveMetadata(e,t)}))},e.prototype.removeTargets=function(e,t,n){var r=this,i=0,o=[];return ct(e).iterate((function(a,s){var u=r.serializer.fromDbTarget(s);u.sequenceNumber<=t&&null===n.get(u.targetId)&&(i++,o.push(r.removeQueryData(e,u)))})).next((function(){return We.waitFor(o)})).next((function(){return i}))},e.prototype.forEachTarget=function(e,t){var n=this;return ct(e).iterate((function(e,r){var i=n.serializer.fromDbTarget(r);t(i)}))},e.prototype.retrieveMetadata=function(e){return ht(e.simpleDbTransaction)},e.prototype.saveMetadata=function(e,t){return(n=e,Bn.getStore(n,pn.store)).put(pn.key,t);var n},e.prototype.saveQueryData=function(e,t){return ct(e).put(this.serializer.toDbTarget(t))},e.prototype.updateMetadataFromQueryData=function(e,t){var n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n},e.prototype.getQueryCount=function(e){return this.retrieveMetadata(e).next((function(e){return e.targetCount}))},e.prototype.getQueryData=function(e,t){var n=this,r=t.canonicalId(),i=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),o=null;return ct(e).iterate({range:i,index:fn.queryTargetsIndexName},(function(e,r,i){var a=n.serializer.fromDbTarget(r);
1t.isEqual(a.query)&&(o=a,i.done())})).next((function(){return o}))},e.prototype.addMatchingKeys=function(e,t,n){var r=this,i=[],o=ft(e);return t.forEach((function(t){var a=ve(t.path);i.push(o.put(new dn(n,a))),i.push(r.referenceDelegate.addReference(e,t))})),We.waitFor(i)},e.prototype.removeMatchingKeys=function(e,t,n){var r=this,i=ft(e);return We.forEach(t,(function(t){var o=ve(t.path);return We.waitFor([i.delete([n,o]),r.referenceDelegate.removeReference(e,t)])}))},e.prototype.removeMatchingKeysForTargetId=function(e,t){var n=ft(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)},e.prototype.getMatchingKeysForTargetId=function(e,t){var n=IDBKeyRange.bound([t],[t+1],!1,!0),r=ft(e),i=Ve();return r.iterate({range:n,keysOnly:!0},(function(e,t,n){var r=Se(e[1]),o=new de(r);i=i.add(o)})).next((function(){return i}))},e.prototype.containsKey=function(e,t){var n=ve(t.path),r=IDBKeyRange.bound([n],[Z(n)],!1,!0),i=0;return ft(e).iterate({index:dn.documentTargetsIndex,keysOnly:!0,range:r},(function(e,t,n){var r=e[0];e[1];0!==r&&(i++,n.done())})).next((function(){return i>0}))},e.prototype.getQueryDataForTarget=function(e,t){var n=this;return ct(e).get(t).next((function(e){return e?n.serializer.fromDbTarget(e):null}))},e}();function ct(e){return Bn.getStore(e,fn.store)}function ht(e){return ze.getStore(e,pn.store).get(pn.key).next((function(e){return v(null!==e,"Missing metadata row."),e}))}function lt(e){return ht(e).next((function(e){return e.highestListenSequenceNumber}))}function ft(e){return Bn.getStore(e,dn.store)}var dt,pt=function(){function e(e){this.fields=e}return e.fromSet=function(t){return new e(t)},e.fromArray=function(t){var n=new Ne(fe.comparator);return t.forEach((function(e){return n=n.add(e)})),new e(n)},e.prototype.covers=function(e){var t=!1;return this.fields.forEach((function(n){n.isPrefixOf(e)&&(t=!0)})),t},e.prototype.isEqual=function(e){return this.fields.isEqual(e.fields)},e}(),mt=function(){function e(e,t){this.field=e,this.transform=t}return e.prototype.isEqual=function(e){return this.field.isEqual(e.field)&&this.transform.isEqual(e.transform)},e}(),yt=function(e,t){this.version=e,this.transformResults=t};!function(e){e[e.Set=0]="Set",e[e.Patch=1]="Patch",e[e.Transform=2]="Transform",e[e.Delete=3]="Delete"}(dt||(dt={}));var gt,vt,wt=function(){function e(e,t){this.updateTime=e,this.exists=t,v(void 0===e||void 0===t,'Precondition can specify "exists" or "updateTime" but not both')}return e.exists=function(t){return new e(void 0,t)},e.updateTime=function(t){return new e(t)},Object.defineProperty(e.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),e.prototype.isValidFor=function(e){return void 0!==this.updateTime?e instanceof Qt&&e.version.isEqual(this.updateTime):void 0!==this.exists?this.exists===e instanceof Qt:(v(this.isNone,"Precondition should be empty"),!0)},e.prototype.isEqual=function(e){return t=this.updateTime,n=e.updateTime,(null!==t&&void 0!==t?!(!n||!t.isEqual(n)):t===n)&&this.exists===e.exists;var t,n},e.NONE=new e,e}(),bt=function(){function e(){}return e.prototype.verifyKeyMatches=function(e){null!=e&&v(e.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")},e.getPostMutationVersion=function(e){return e instanceof Qt?e.version:Ee.MIN},e}(),St=function(e){function t(t,n,r){var i=e.call(this)||this;return i.key=t,i.value=n,i.precondition=r,i.type=dt.Set,i}return a.__extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){this.verifyKeyMatches(e),v(null==t.transformResults,"Transform results received by SetMutation.");var n=t.version;return new Qt(this.key,n,{hasCommittedMutations:!0},this.value)},t.prototype.applyToLocalView=function(e,t,n){if(this.verifyKeyMatches(e),!this.precondition.isValidFor(e))return e;var r=bt.getPostMutationVersion(e);return new Qt(this.key,r,{hasLocalMutations:!0},this.value)},t.prototype.extractBaseValue=function(e){return null},t.prototype.isEqual=function(e){return e instanceof t&&this.key.isEqual(e.key)&&this.value.isEqual(e.value)&&this.precondition.isEqual(e.precondition)},t}(bt),Tt=function(e){function t(t,n,r,i){var o=e.call(this)||this;
1return o.key=t,o.data=n,o.fieldMask=r,o.precondition=i,o.type=dt.Patch,o}return a.__extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){if(this.verifyKeyMatches(e),v(null==t.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(e))return new Wt(this.key,t.version);var n=this.patchDocument(e);return new Qt(this.key,t.version,{hasCommittedMutations:!0},n)},t.prototype.applyToLocalView=function(e,t,n){if(this.verifyKeyMatches(e),!this.precondition.isValidFor(e))return e;var r=bt.getPostMutationVersion(e),i=this.patchDocument(e);return new Qt(this.key,r,{hasLocalMutations:!0},i)},t.prototype.extractBaseValue=function(e){return null},t.prototype.isEqual=function(e){return e instanceof t&&this.key.isEqual(e.key)&&this.fieldMask.isEqual(e.fieldMask)&&this.precondition.isEqual(e.precondition)},t.prototype.patchDocument=function(e){var t;return t=e instanceof Qt?e.data():Ft.EMPTY,this.patchObject(t)},t.prototype.patchObject=function(e){var t=this;return this.fieldMask.fields.forEach((function(n){if(!n.isEmpty()){var r=t.data.field(n);e=null!==r?e.set(n,r):e.delete(n)}})),e},t}(bt),Et=function(e){function t(t,n){var r=e.call(this)||this;return r.key=t,r.fieldTransforms=n,r.type=dt.Transform,r.precondition=wt.exists(!0),r}return a.__extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){if(this.verifyKeyMatches(e),v(null!=t.transformResults,"Transform results missing for TransformMutation."),!this.precondition.isValidFor(e))return new Wt(this.key,t.version);var n=this.requireDocument(e),r=this.serverTransformResults(e,t.transformResults),i=t.version,o=this.transformObject(n.data(),r);return new Qt(this.key,i,{hasCommittedMutations:!0},o)},t.prototype.applyToLocalView=function(e,t,n){if(this.verifyKeyMatches(e),!this.precondition.isValidFor(e))return e;var r=this.requireDocument(e),i=this.localTransformResults(n,e,t),o=this.transformObject(r.data(),i);return new Qt(this.key,r.version,{hasLocalMutations:!0},o)},t.prototype.extractBaseValue=function(e){for(var t=null,n=0,r=this.fieldTransforms;n<r.length;n++){var i=r[n],o=e instanceof Qt?e.field(i.field):void 0,a=i.transform.computeBaseValue(o||null);null!=a&&(t=null==t?Ft.EMPTY.set(i.field,a):t.set(i.field,a))}return t},t.prototype.isEqual=function(e){return e instanceof t&&this.key.isEqual(e.key)&&X(this.fieldTransforms,e.fieldTransforms)&&this.precondition.isEqual(e.precondition)},t.prototype.requireDocument=function(e){v(e instanceof Qt,"Unknown MaybeDocument type "+e);var t=e;return v(t.key.isEqual(this.key),"Can only transform a document with the same key"),t},t.prototype.serverTransformResults=function(e,t){var n=[];v(this.fieldTransforms.length===t.length,"server transform result count ("+t.length+") should match field transform count ("+this.fieldTransforms.length+")");for(var r=0;r<t.length;r++){var i=this.fieldTransforms[r],o=i.transform,a=null;e instanceof Qt&&(a=e.field(i.field)),n.push(o.applyToRemoteDocument(a,t[r]))}return n},t.prototype.localTransformResults=function(e,t,n){for(var r=[],i=0,o=this.fieldTransforms;i<o.length;i++){var a=o[i],s=a.transform,u=null;t instanceof Qt&&(u=t.field(a.field)),null===u&&n instanceof Qt&&(u=n.field(a.field)),r.push(s.applyToLocalView(u,e))}return r},t.prototype.transformObject=function(e,t){v(t.length===this.fieldTransforms.length,"TransformResults length mismatch.");for(var n=0;n<this.fieldTransforms.length;n++){var r=this.fieldTransforms[n].field;e=e.set(r,t[n])}return e},t}(bt),It=function(e){function t(t,n){var r=e.call(this)||this;return r.key=t,r.precondition=n,r.type=dt.Delete,r}return a.__extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){return this.verifyKeyMatches(e),v(null==t.transformResults,"Transform results received by DeleteMutation."),new Kt(this.key,t.version,{hasCommittedMutations:!0})},t.prototype.applyToLocalView=function(e,t,n){return this.verifyKeyMatches(e),this.precondition.isValidFor(e)?(e&&v(e.key.isEqual(this.key),"Can only apply mutation to document with same key"),new Kt(this.key,Ee.forDeletedDoc())):e},t.prototype.extractBaseValue=function(e){return null},t.prototype.isEqual=function(e){return e instanceof t&&this.key.isEqual(e.key)&&this.prec
1ondition.isEqual(e.precondition)},t}(bt);!function(e){e[e.NullValue=0]="NullValue",e[e.BooleanValue=1]="BooleanValue",e[e.NumberValue=2]="NumberValue",e[e.TimestampValue=3]="TimestampValue",e[e.StringValue=4]="StringValue",e[e.BlobValue=5]="BlobValue",e[e.RefValue=6]="RefValue",e[e.GeoPointValue=7]="GeoPointValue",e[e.ArrayValue=8]="ArrayValue",e[e.ObjectValue=9]="ObjectValue"}(gt||(gt={})),function(e){e[e.Default=0]="Default",e[e.Estimate=1]="Estimate",e[e.Previous=2]="Previous"}(vt||(vt={}));var Ct=function(){function e(e,t){this.serverTimestampBehavior=e,this.timestampsInSnapshots=t}return e.fromSnapshotOptions=function(t,n){switch(t.serverTimestamps){case"estimate":return new e(vt.Estimate,n);case"previous":return new e(vt.Previous,n);case"none":case void 0:return new e(vt.Default,n);default:return g("fromSnapshotOptions() called with invalid options.")}},e}(),Dt=function(){function e(){}return e.prototype.toString=function(){var e=this.value();return null===e?"null":e.toString()},e.prototype.defaultCompareTo=function(e){return v(this.typeOrder!==e.typeOrder,"Default compareTo should not be used for values of same type."),J(this.typeOrder,e.typeOrder)},e}(),_t=function(e){function t(){var t=e.call(this)||this;return t.typeOrder=gt.NullValue,t.internalValue=null,t}return a.__extends(t,e),t.prototype.value=function(e){return null},t.prototype.isEqual=function(e){return e instanceof t},t.prototype.compareTo=function(e){return e instanceof t?0:this.defaultCompareTo(e)},t.INSTANCE=new t,t}(Dt),Nt=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.BooleanValue,n}return a.__extends(t,e),t.prototype.value=function(e){return this.internalValue},t.prototype.isEqual=function(e){return e instanceof t&&this.internalValue===e.internalValue},t.prototype.compareTo=function(e){return e instanceof t?J(this,e):this.defaultCompareTo(e)},t.of=function(e){return e?t.TRUE:t.FALSE},t.TRUE=new t(!0),t.FALSE=new t(!1),t}(Dt),At=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.NumberValue,n}return a.__extends(t,e),t.prototype.value=function(e){return this.internalValue},t.prototype.compareTo=function(e){return e instanceof t?(n=this.internalValue,r=e.internalValue,n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1):this.defaultCompareTo(e);var n,r},t}(Dt);function kt(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}var Rt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a.__extends(t,e),t.prototype.isEqual=function(e){return e instanceof t&&kt(this.internalValue,e.internalValue)},t}(At),Mt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a.__extends(t,e),t.prototype.isEqual=function(e){return e instanceof t&&kt(this.internalValue,e.internalValue)},t.NAN=new t(NaN),t.POSITIVE_INFINITY=new t(1/0),t.NEGATIVE_INFINITY=new t(-1/0),t}(At),Lt=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.StringValue,n}return a.__extends(t,e),t.prototype.value=function(e){return this.internalValue},t.prototype.isEqual=function(e){return e instanceof t&&this.internalValue===e.internalValue},t.prototype.compareTo=function(e){return e instanceof t?J(this.internalValue,e.internalValue):this.defaultCompareTo(e)},t}(Dt),Ot=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.TimestampValue,n}return a.__extends(t,e),t.prototype.value=function(e){return!e||e.timestampsInSnapshots?this.internalValue:this.internalValue.toDate()},t.prototype.isEqual=function(e){return e instanceof t&&this.internalValue.isEqual(e.internalValue)},t.prototype.compareTo=function(e){return e instanceof t?this.internalValue._compareTo(e.internalValue):e instanceof Pt?-1:this.defaultCompareTo(e)},t}(Dt),Pt=function(e){function t(t,n){var r=e.call(this)||this;return r.localWriteTime=t,r.previousValue=n,r.typeOrder=gt.TimestampValue,r}return a.__extends(t,e),t.prototype.value=function(e){return e&&e.serverTimestampBehavior===vt.Estimate?new Ot(this.localWriteTime).value(e):e&&e.serverTimestampBehavior===vt.Previous&&this.previousValue?this.previousValue.value(e):null},t.prototype.isEqual=function(e){return e instanceof t&&this.localWriteTime.isEqual(e.localWriteTime)},t.prototype.compareTo=function(e){return e instanceof t?this.localWriteTime._compareTo(e.localWriteTime):e instanceof Ot?1:this.defaultCompareTo(e)},t.prototype.toString=function(){return"<ServerTimestamp localTime="+this.localWriteTime.toString()+">"},t}(Dt),xt=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.BlobValue,n}return a.__extends(t,e),t.prototype.value=function(e){return this.internalValue},t.prototype.isEqual=function(e){return e instanceof t&&this.internalValue.isEqual(e.internalValue)},t.prototype.compareTo=function(e){return e instanceof t?this.internalValue._compareTo(e.internalValue):this.defaultCompareTo(e)},t}(Dt),qt=function(e){function t(t,n){var r=e.call(this)||this;return r.databaseId=t,r.key=n,r.typeOrder=gt.RefValue,r}return a.__extends(t,e),t.prototype.value=function(e){return this.key},t.prototype.isEqual=function(e){return e instanceof t&&(this.key.isEqual(e.key)&&this.databaseId.isEqual(e.databaseId))},t.prototype.compareTo=function(e){if(e instanceof t){var n=this.databaseId.compareTo(e.databaseId);return 0!==n?n:de.comparator(this.key,e.key)}return this.defaultCompareTo(e)},t}(Dt),Vt=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.GeoPointValue,n}return a.__extends(t,e),t.prototype.value=function(e){return this.internalValue},t.prototype.isEqual=function(e){return e instanceof t&&this.internalValue.isEqual(e.internalValue)},t.prototype.compareTo=function(e){return e instanceof t?this.internalValue._compareTo(e.internalValue):this.defaultCompareTo(e)},t}(Dt),Ft=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.ObjectValue,n}return a.__extends(t,e),t.prototype.value=function(e){var t={};return this.internalValue.inorderTraversal((function(n,r){t[n]=r.value(e)})),t},t.prototype.forEach=function(e){this.internalValue.inorderTraversal(e)},t.prototype.isEqual=function(e){if(e instanceof t){for(var n=this.internalValue.getIterator(),r=e.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext();if(i.key!==o.key||!i.value.isEqual(o.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},t.prototype.compareTo=function(e){if(e instanceof t){for(var n=this.internalValue.getIterator(),r=e.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext(),a=J(i.key,o.key)||i.value.compareTo(o.value);if(a)return a}return J(n.hasNext(),r.hasNext())}return this.defaultCompareTo(e)},t.prototype.set=function(e,n){if(v(!e.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===e.length)return this.setChild(e.firstSegment(),n);var r=this.child(e.firstSegment());r instanceof t||(r=t.EMPTY);var i=r.set(e.popFirst(),n);return this.setChild(e.firstSegment(),i)},t.prototype.delete=function(e){if(v(!e.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===e.length)return new t(this.internalValue.remove(e.firstSegment()));var n=this.child(e.firstSegment());if(n instanceof t){var r=n.delete(e.popFirst());return new t(this.internalValue.insert(e.firstSegment(),r))}return this},t.prototype.contains=function(e){return null!==this.field(e)},t.prototype.field=function(e){v(!e.isEmpty(),"Can't get field of empty path");var n=this;return e.forEach((function(e){n=n instanceof t?n.internalValue.get(e):null})),n},t.prototype.fieldMask=function(){var e=new Ne(fe.comparator);return this.internalValue.forEach((function(n,r){var i=new fe([n]);if(r instanceof t){var o=r.fieldMask().fields;
1o.isEmpty()?e=e.add(i):o.forEach((function(t){e=e.add(i.child(t))}))}else e=e.add(i)})),pt.fromSet(e)},t.prototype.toString=function(){return this.internalValue.toString()},t.prototype.child=function(e){return this.internalValue.get(e)||void 0},t.prototype.setChild=function(e,n){return new t(this.internalValue.insert(e,n))},t.EMPTY=new t(new Ie(J)),t}(Dt),Bt=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=gt.ArrayValue,n}return a.__extends(t,e),t.prototype.value=function(e){return this.internalValue.map((function(t){return t.value(e)}))},t.prototype.contains=function(e){for(var t=0,n=this.internalValue;t<n.length;t++){if(n[t].isEqual(e))return!0}return!1},t.prototype.forEach=function(e){this.internalValue.forEach(e)},t.prototype.isEqual=function(e){if(e instanceof t){if(this.internalValue.length!==e.internalValue.length)return!1;for(var n=0;n<this.internalValue.length;n++)if(!this.internalValue[n].isEqual(e.internalValue[n]))return!1;return!0}return!1},t.prototype.compareTo=function(e){if(e instanceof t){for(var n=Math.min(this.internalValue.length,e.internalValue.length),r=0;r<n;r++){var i=this.internalValue[r].compareTo(e.internalValue[r]);if(i)return i}return J(this.internalValue.length,e.internalValue.length)}return this.defaultCompareTo(e)},t.prototype.toString=function(){return"["+this.internalValue.map((function(e){return e.toString()})).join(",")+"]"},t}(Dt),Ut=function(){function e(e,t){this.key=e,this.version=t}return e.compareByKey=function(e,t){return de.comparator(e.key,t.key)},e}(),Qt=function(e){function t(t,n,r,i,o,a){var s=e.call(this,t,n)||this;return s.objectValue=i,s.proto=o,s.converter=a,v(void 0!==s.objectValue||void 0!==s.proto&&void 0!==s.converter,"If objectValue is not defined, proto and converter need to be set."),s.hasLocalMutations=!!r.hasLocalMutations,s.hasCommittedMutations=!!r.hasCommittedMutations,s}return a.__extends(t,e),t.prototype.field=function(e){if(this.objectValue)return this.objectValue.field(e);this.fieldValueCache||(this.fieldValueCache=new Map);var t=e.canonicalString(),n=this.fieldValueCache.get(t);if(void 0===n){var r=this.getProtoField(e);n=void 0===r?null:this.converter(r),this.fieldValueCache.set(t,n)}return n},t.prototype.data=function(){var e=this;if(!this.objectValue){var t=Ft.EMPTY;_(this.proto.fields||{},(function(n,r){t=t.set(new fe([n]),e.converter(r))})),this.objectValue=t,this.fieldValueCache=void 0}return this.objectValue},t.prototype.value=function(){return this.data().value()},t.prototype.isEqual=function(e){return e instanceof t&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.hasLocalMutations===e.hasLocalMutations&&this.hasCommittedMutations===e.hasCommittedMutations&&this.data().isEqual(e.data())},t.prototype.toString=function(){return"Document("+this.key+", "+this.version+", "+this.data().toString()+", {hasLocalMutations: "+this.hasLocalMutations+"}), {hasCommittedMutations: "+this.hasCommittedMutations+"})"},Object.defineProperty(t.prototype,"hasPendingWrites",{get:function(){return this.hasLocalMutations||this.hasCommittedMutations},enumerable:!0,configurable:!0}),t.prototype.getProtoField=function(e){v(void 0!==this.proto,"Can only call getProtoField() when proto is defined");for(var t=this.proto.fields?this.proto.fields[e.firstSegment()]:void 0,n=1;n<e.length;++n){if(!t||!t.mapValue||!t.mapValue.fields)return;t=t.mapValue.fields[e.get(n)]}return t},t.compareByField=function(e,t,n){var r=t.field(e),i=n.field(e);return null!==r&&null!==i?r.compareTo(i):g("Trying to compare documents on fields that don't exist")},t}(Ut),Kt=function(e){function t(t,n,r){var i=e.call(this,t,n)||this;return i.hasCommittedMutations=!(!r||!r.hasCommittedMutations),i}return a.__extends(t,e),t.prototype.toString=function(){return"NoDocument("+this.key+", "+this.version+")"},Object.defineProperty(t.prototype,"hasPendingWrites",{get:function(){return this.hasCommittedMutations},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return e instanceof t&&e.hasCommittedMutations===this.hasCommittedMutations&&e.version.isEqual(this.version)&&e.key.isEqual(this.key)},t}(Ut),Wt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a.__extends(t,e),t.prototype.toString=function(){return"UnknownDocument("+this.key+", "+this.version+")"},Object.defineProperty(t.prototype,"hasPendingWrites",{get:function(){return!0},enumerable:!0,configurable:!0}
1),t.prototype.isEqual=function(e){return e instanceof t&&e.version.isEqual(this.version)&&e.key.isEqual(this.key)},t}(Ut),Gt=function(){function e(e){this.mapKeyFn=e,this.inner={}}return e.prototype.get=function(e){var t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(var r=0,i=n;r<i.length;r++){var o=i[r],a=o[0],s=o[1];if(a.isEqual(e))return s}},e.prototype.has=function(e){return void 0!==this.get(e)},e.prototype.set=function(e,t){var n=this.mapKeyFn(e),r=this.inner[n];if(void 0!==r){for(var i=0;i<r.length;i++)if(r[i][0].isEqual(e))return void(r[i]=[e,t]);r.push([e,t])}else this.inner[n]=[[e,t]]},e.prototype.delete=function(e){var t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(var r=0;r<n.length;r++)if(n[r][0].isEqual(e))return 1===n.length?delete this.inner[t]:n.splice(r,1),!0;return!1},e.prototype.forEach=function(e){_(this.inner,(function(t,n){for(var r=0,i=n;r<i.length;r++){var o=i[r],a=o[0],s=o[1];e(a,s)}}))},e.prototype.isEmpty=function(){return N(this.inner)},e}(),zt=function(){function e(){this.changes=new Gt((function(e){return e.toString()})),this.changesApplied=!1}return Object.defineProperty(e.prototype,"readTime",{get:function(){return v(void 0!==this._readTime,"Read time is not set. All removeEntry() calls must include a readTime if `trackRemovals` is used."),this._readTime},set:function(e){v(void 0===this._readTime||this._readTime.isEqual(e),"All changes in a RemoteDocumentChangeBuffer must have the same read time"),this._readTime=e},enumerable:!0,configurable:!0}),e.prototype.addEntry=function(e,t){this.assertNotApplied(),this.readTime=t,this.changes.set(e.key,e)},e.prototype.removeEntry=function(e,t){this.assertNotApplied(),t&&(this.readTime=t),this.changes.set(e,null)},e.prototype.getEntry=function(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?We.resolve(n):this.getFromCache(e,t)},e.prototype.getEntries=function(e,t){return this.getAllFromCache(e,t)},e.prototype.apply=function(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)},e.prototype.assertNotApplied=function(){v(!this.changesApplied,"Changes have already been applied.")},e}(),jt=function(){function e(e,t){this.serializer=e,this.indexManager=t}return e.prototype.addEntry=function(e,t,n){return Yt(e).put(Jt(t),n)},e.prototype.removeEntry=function(e,t){var n=Yt(e),r=Jt(t);return n.delete(r)},e.prototype.updateMetadata=function(e,t){var n=this;return this.getMetadata(e).next((function(r){return r.byteSize+=t,n.setMetadata(e,r)}))},e.prototype.getEntry=function(e,t){var n=this;return Yt(e).get(Jt(t)).next((function(e){return n.maybeDecodeDocument(e)}))},e.prototype.getSizedEntry=function(e,t){var n=this;return Yt(e).get(Jt(t)).next((function(e){var t=n.maybeDecodeDocument(e);return t?{maybeDocument:t,size:Xt(e)}:null}))},e.prototype.getEntries=function(e,t){var n=this,r=Me();return this.forEachDbEntry(e,t,(function(e,t){var i=n.maybeDecodeDocument(t);r=r.insert(e,i)})).next((function(){return r}))},e.prototype.getSizedEntries=function(e,t){var n=this,r=Me(),i=new Ie(de.comparator);return this.forEachDbEntry(e,t,(function(e,t){var o=n.maybeDecodeDocument(t);o?(r=r.insert(e,o),i=i.insert(e,Xt(t))):(r=r.insert(e,null),i=i.insert(e,0))})).next((function(){return{maybeDocuments:r,sizeMap:i}}))},e.prototype.forEachDbEntry=function(e,t,n){if(t.isEmpty())return We.resolve();var r=IDBKeyRange.bound(t.first().path.toArray(),t.last().path.toArray()),i=t.getIterator(),o=i.getNext();return Yt(e).iterate({range:r},(function(e,t,r){for(var a=de.fromSegments(e);o&&de.comparator(o,a)<0;)n(o,null),o=i.getNext();o&&o.isEqual(a)&&(n(o,t),o=i.hasNext()?i.getNext():null),o?r.skip(o.path.toArray()):r.done()})).next((function(){for(;o;)n(o,null),o=i.hasNext()?i.getNext():null}))},e.prototype.getDocumentsMatchingQuery=function(e,t,n){var r=this;v(!t.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var i=Oe(),o=t.path.length+1,a={};if(n.isEqual(Ee.MIN)){var s=t.path.toArray();a.range=IDBKeyRange.lowerBound(s)}else{var u=t.path.toArray(),c=this.serializer.toDbTimestampKey(n);a.range=IDBKeyRange.lowerBound([u,c],!0),a.index=hn.collectionReadTimeIndex}return Yt(e).iterate(a,(function(e,n,a){if(e.length===o){var s=r.serializer.fromDbRemoteDocument(n);t.path.isPrefixOf(s.key.path)?s instanceof Qt&&t.matches(s)&&(i=i.insert(s.key,s)):a.done()}})).next((function(){return i}))},e.prototype.getNewDocumentChanges=function(e,t){var n=this,r=Re(),i=this.serializer.toDbTimestampKey(t),o=Yt(e),a=IDBKeyRange.lowerBound(i,!0);return o.iterate({index:hn.readTimeIndex,range:a},(function(e,t){var o=n.serializer.fromDbRemoteDocument(t);r=r.insert(o.key,o),i=t.readTime})).next((function(){return{changedDocs:r,readTime:n.serializer.fromDbTimestampKey(i)}}))},e.prototype.getLastDocumentChange=function(e){var t,n=this,r=Yt(e),i=Ee.MIN;return r.iterate({index:hn.readTimeIndex,reverse:!0}
1,(function(e,r,o){t=n.serializer.fromDbRemoteDocument(r),r.readTime&&(i=n.serializer.fromDbTimestampKey(r.readTime)),o.done()})).next((function(){return{changedDoc:t,readTime:i}}))},e.prototype.newChangeBuffer=function(t){return new e.RemoteDocumentChangeBuffer(this,!!t&&t.trackRemovals)},e.prototype.getSize=function(e){return this.getMetadata(e).next((function(e){return e.byteSize}))},e.prototype.getMetadata=function(e){return Ht(e).get(ln.key).next((function(e){return v(!!e,"Missing document cache metadata"),e}))},e.prototype.setMetadata=function(e,t){return Ht(e).put(ln.key,t)},e.prototype.maybeDecodeDocument=function(e){if(e){var t=this.serializer.fromDbRemoteDocument(e);return t instanceof Kt&&t.version.isEqual(Ee.forDeletedDoc())?null:t}return null},e.RemoteDocumentChangeBuffer=function(e){function t(t,n){var r=e.call(this)||this;return r.documentCache=t,r.trackRemovals=n,r.documentSizes=new Gt((function(e){return e.toString()})),r}return a.__extends(t,e),t.prototype.applyChanges=function(e){var t=this,n=[],r=0,i=new Ne((function(e,t){return J(e.canonicalString(),t.canonicalString())}));
1return this.changes.forEach((function(o,a){var s=t.documentSizes.get(o);if(v(void 0!==s,"Cannot modify a document that wasn't read (for "+o+")"),a){v(!t.readTime.isEqual(Ee.MIN),"Cannot add a document with a read time of zero");var u=t.documentCache.serializer.toDbRemoteDocument(a,t.readTime);i=i.add(o.path.popLast());var c=Xt(u);r+=c-s,n.push(t.documentCache.addEntry(e,o,u))}else if(r-=s,t.trackRemovals){var h=t.documentCache.serializer.toDbRemoteDocument(new Kt(o,Ee.forDeletedDoc()),t.readTime);n.push(t.documentCache.addEntry(e,o,h))}else n.push(t.documentCache.removeEntry(e,o))})),i.forEach((function(r){n.push(t.documentCache.indexManager.addToCollectionParentIndex(e,r))})),n.push(this.documentCache.updateMetadata(e,r)),We.waitFor(n)},t.prototype.getFromCache=function(e,t){var n=this;return this.documentCache.getSizedEntry(e,t).next((function(e){return null===e?(n.documentSizes.set(t,0),null):(n.documentSizes.set(t,e.size),e.maybeDocument)}))},t.prototype.getAllFromCache=function(e,t){var n=this;return this.documentCache.getSizedEntries(e,t).next((function(e){var t=e.maybeDocuments;return e.sizeMap.forEach((function(e,t){n.documentSizes.set(e,t)})),t}))},t}(zt),e}();function Ht(e){return Bn.getStore(e,ln.store)}function Yt(e){return Bn.getStore(e,hn.store)}function Jt(e){return e.path.toArray()}function Xt(e){var t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw g("Unknown remote document type");t=e.noDocument}return JSON.stringify(t).length}var Zt=function(){function e(){this.collectionParentIndex=new $t}return e.prototype.addToCollectionParentIndex=function(e,t){return this.collectionParentIndex.add(t),We.resolve()},e.prototype.getCollectionParents=function(e,t){return We.resolve(this.collectionParentIndex.getEntries(t))},e}(),$t=function(){function e(){this.index={}}return e.prototype.add=function(e){v(e.length%2===1,"Expected a collection path.");var t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Ne(he.comparator),i=!r.has(n);return this.index[t]=r.add(n),i},e.prototype.has=function(e){var t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)},e.prototype.getEntries=function(e){return(this.index[e]||new Ne(he.comparator)).toArray()},e}(),en=9,tn=function(){function e(e){this.serializer=e}return e.prototype.createOrUpgrade=function(e,t,n,r){var i=this;v(n<r&&n>=0&&r<=en,"Unexpected schema upgrade from v"+n+" to v{toVersion}.");var o=new He(t);n<1&&r>=1&&(function(e){e.createObjectStore(rn.store)}(e),function(e){e.createObjectStore(on.store,{keyPath:on.keyPath}),e.createObjectStore(an.store,{keyPath:an.keyPath,autoIncrement:!0}).createIndex(an.userMutationsIndex,an.userMutationsKeyPath,{unique:!0}),e.createObjectStore(sn.store)}(e),yn(e),function(e){e.createObjectStore(hn.store)}(e));var a=We.resolve();return n<3&&r>=3&&(0!==n&&(!function(e){e.deleteObjectStore(dn.store),e.deleteObjectStore(fn.store),e.deleteObjectStore(pn.store)}(e),yn(e)),a=a.next((function(){return function(e){var t=e.store(pn.store),n=new pn(0,0,Ee.MIN.toTimestamp(),0);return t.put(pn.key,n)}(o)}))),n<4&&r>=4&&(0!==n&&(a=a.next((function(){return function(e,t){return t.store(an.store).loadAll().next((function(n){e.deleteObjectStore(an.store),e.createObjectStore(an.store,{keyPath:an.keyPath,autoIncrement:!0}).createIndex(an.userMutationsIndex,an.userMutationsKeyPath,{unique:!0});var r=t.store(an.store),i=n.map((function(e){return r.put(e)}));return We.waitFor(i)}))}(e,o)}))),a=a.next((function(){!function(e){e.createObjectStore(gn.store,{keyPath:gn.keyPath})}(e)}))),n<5&&r>=5&&(a=a.next((function(){return i.removeAcknowledgedMutations(o)}))),n<6&&r>=6&&(a=a.next((function(){return function(e){e.createObjectStore(ln.store)}(e),i.addDocumentGlobal(o)}))),n<7&&r>=7&&(a=a.next((function(){return i.ensureSequenceNumbers(o)}))),n<8&&r>=8&&(a=a.next((function(){return i.createCollectionParentIndex(e,o)}))),n<9&&r>=9&&(a=a.next((function(){!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e),function(e){var t=e.objectStore(hn.store);t.createIndex(hn.readTimeIndex,hn.readTimeIndexPath,{unique:!1}),t.createIndex(hn.collectionReadTimeIndex,hn.collectionReadTimeIndexPath,{unique:!1})}(t)}))),a},e.prototype.addDocumentGlobal=function(e){var t=0;return e.store(hn.store).iterate((function(e,n){t+=Xt(n)})).next((function(){var n=new ln(t);return e.store(ln.store).put(ln.key,n)}))},e.prototype.removeAcknowledgedMutations=function(e){var t=this,n=e.store(on.store),r=e.store(an.store);return n.loadAll().next((function(n){return We.forEach(n,(function(n){var i=IDBKeyRange.bound([n.userId,Ue],[n.userId,n.lastAcknowledgedBatchId]);
1return r.loadAll(an.userMutationsIndex,i).next((function(r){return We.forEach(r,(function(r){v(r.userId===n.userId,"Cannot process batch "+r.batchId+" from unexpected user");var i=t.serializer.fromDbMutationBatch(r);return tt(e,n.userId,i).next((function(){}))}))}))}))}))},e.prototype.ensureSequenceNumbers=function(e){var t=e.store(dn.store),n=e.store(hn.store);return lt(e).next((function(e){var r=[];return n.iterate((function(n,i){var o=new he(n),a=function(e){return[0,ve(e)]}(o);r.push(t.get(a).next((function(n){return n?We.resolve():function(n){return t.put(new dn(0,ve(n),e))}(o)})))})).next((function(){return We.waitFor(r)}))}))},e.prototype.createCollectionParentIndex=function(e,t){e.createObjectStore(mn.store,{keyPath:mn.keyPath});var n=t.store(mn.store),r=new $t,i=function(e){if(r.add(e)){var t=e.lastSegment(),i=e.popLast();return n.put({collectionId:t,parent:ve(i)})}};return t.store(hn.store).iterate({keysOnly:!0},(function(e,t){var n=new he(e);return i(n.popLast())})).next((function(){return t.store(sn.store).iterate({keysOnly:!0},(function(e,t){e[0];var n=e[1],r=(e[2],Se(n));return i(r.popLast())}))}))},e}();var nn=function(e,t){this.seconds=e,this.nanoseconds=t},rn=function(){function e(e,t,n){this.ownerId=e,this.allowTabSynchronization=t,this.leaseTimestampMs=n}return e.store="owner",e.key="owner",e}();var on=function(){function e(e,t,n){this.userId=e,this.lastAcknowledgedBatchId=t,this.lastStreamToken=n}return e.store="mutationQueues",e.keyPath="userId",e}(),an=function(){function e(e,t,n,r,i){this.userId=e,this.batchId=t,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=i}return e.store="mutations",e.keyPath="batchId",e.userMutationsIndex="userMutationsIndex",e.userMutationsKeyPath=["userId","batchId"],e}();var sn=function(){function e(){}return e.prefixForUser=function(e){return[e]},e.prefixForPath=function(e,t){return[e,ve(t)]},e.key=function(e,t,n){return[e,ve(t),n]},e.store="documentMutations",e.PLACEHOLDER=new e,e}();var un=function(e,t){this.path=e,this.readTime=t},cn=function(e,t){this.path=e,this.version=t},hn=function(){function e(e,t,n,r,i,o){this.unknownDocument=e,this.noDocument=t,this.document=n,this.hasCommittedMutations=r,this.readTime=i,this.parentPath=o}return e.store="remoteDocuments",e.readTimeIndex="readTimeIndex",e.readTimeIndexPath="readTime",e.collectionReadTimeIndex="collectionReadTimeIndex",e.collectionReadTimeIndexPath=["parentPath","readTime"],e}(),ln=function(){function e(e){this.byteSize=e}return e.store="remoteDocumentGlobal",e.key="remoteDocumentGlobalKey",e}();var fn=function(){function e(e,t,n,r,i,o,a){this.targetId=e,this.canonicalId=t,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.lastLimboFreeSnapshotVersion=o,this.query=a}return e.store="targets",e.keyPath="targetId",e.queryTargetsIndexName="queryTargetsIndex",e.queryTargetsKeyPath=["canonicalId","targetId"],e}(),dn=function(){function e(e,t,n){this.targetId=e,this.path=t,this.sequenceNumber=n,v(0===e===(void 0!==n),"A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number")}return e.store="targetDocuments",e.keyPath=["targetId","path"],e.documentTargetsIndex="documentTargetsIndex",e.documentTargetsKeyPath=["path","targetId"],e}(),pn=function(){function e(e,t,n,r){this.highestTargetId=e,this.highestListenSequenceNumber=t,this.lastRemoteSnapshotVersion=n,this.targetCount=r}return e.key="targetGlobalKey",e.store="targetGlobal",e}(),mn=function(){function e(e,t){this.collectionId=e,this.parent=t}return e.store="collectionParents",e.keyPath=["collectionId","parent"],e}();function yn(e){e.createObjectStore(dn.store,{keyPath:dn.keyPath}).createIndex(dn.documentTargetsIndex,dn.documentTargetsKeyPath,{unique:!0}),e.createObjectStore(fn.store,{keyPath:fn.keyPath}).createIndex(fn.queryTargetsIndexName,fn.queryTargetsKeyPath,{unique:!0}),e.createObjectStore(pn.store)}var gn=function(){function e(e,t,n,r){this.clientId=e,this.updateTimeMs=t,this.networkEnabled=n,this.inForeground=r}return e.store="clientMetadata",e.keyPath="clientId",e}();var vn,wn=[on.store,an.store,sn.store,hn.store,fn.store,rn.store,pn.store,dn.store],bn=a.__spreadArrays(wn,[gn.store]),Sn=a.__spreadArrays(bn,[ln.store]),Tn=a.__spreadArrays(Sn,[mn.store]),En=function(){function e(){this.collectionParentsCache=new $t}return e.prototype.addToCollectionParentIndex=function(e,t){var n=this;if(v(t.length%2===1,"Expected a collection path."),!this.collectionParentsCache.has(t)){var r=t.lastSegment(),i=t.popLast();return e.addOnCommittedListener((function(){n.collectionParentsCache.add(t)})),In(e).put({collectionId:r,parent:ve(i)})}return We.resolve()},e.prototype.getCollectionParents=function(e,t){var n=[],r=IDBKeyRange.bound([t,""],[Z(t),""],!1,!0);return In(e).loadAll(r).next((function(e){for(var r=0,i=e;r<i.length;r++){var o=i[r];if(o.collectionId!==t)break;n.push(Se(o.parent))}return n}))},e}();function In(e){return Bn.getStore(e,mn.store)}!function(e){e[e.Listen=0]="Listen",e[e.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",e[e.LimboResolution=2]="LimboResolution"}(vn||(vn={}));var Cn=function(){function e(e,t,n,r,i,o,a){void 0===i&&(i=Ee.MIN),void 0===o&&(o=Ee.MIN),void 0===a&&(a=b()),this.query=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=o,this.resumeToken=a}return e.prototype.withSequenceNumber=function(t){return new e(this.query,this.targetId,this.purpose,t,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)},e.prototype.withResumeToken=function(t,n){return new e(this.query,this.targetId,this.purpose,this.sequenceNumber,n,this.lastLimboFreeSnapshotVersion,t)},e.prototype.withLastLimboFreeSnapshotVersion=function(t){return new e(this.query,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,t,this.resumeToken)},e.prototype.isEqual=function(e){return this.targetId===e.targetId&&this.purpose===e.purpose&&this.sequenceNumber===e.sequenceNumber&&this.snapshotVersion.isEqual(e.snapshotVersion)&&this.lastLimboFreeSnapshotVersion.isEqual(e.lastLimboFreeSnapshotVersion)&&this.resumeToken===e.resumeToken&&this.query.isEqual(e.query)},e}
1(),Dn=function(){function e(e){this.remoteSerializer=e}return e.prototype.fromDbRemoteDocument=function(e){if(e.document)return this.remoteSerializer.fromDocument(e.document,!!e.hasCommittedMutations);if(e.noDocument){var t=de.fromSegments(e.noDocument.path),n=this.fromDbTimestamp(e.noDocument.readTime);return new Kt(t,n,{hasCommittedMutations:!!e.hasCommittedMutations})}if(e.unknownDocument){t=de.fromSegments(e.unknownDocument.path),n=this.fromDbTimestamp(e.unknownDocument.version);return new Wt(t,n)}return g("Unexpected DbRemoteDocument")},e.prototype.toDbRemoteDocument=function(e,t){var n=this.toDbTimestampKey(t),r=e.key.path.popLast().toArray();if(e instanceof Qt){var i=e.proto?e.proto:this.remoteSerializer.toDocument(e),o=e.hasCommittedMutations;return new hn(null,null,i,o,n,r)}if(e instanceof Kt){var a=e.key.path.toArray(),s=this.toDbTimestamp(e.version);o=e.hasCommittedMutations;return new hn(null,new un(a,s),null,o,n,r)}if(e instanceof Wt){a=e.key.path.toArray();var u=this.toDbTimestamp(e.version);return new hn(new cn(a,u),null,null,!0,n,r)}return g("Unexpected MaybeDocument")},e.prototype.toDbTimestampKey=function(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]},e.prototype.fromDbTimestampKey=function(e){var t=new Te(e[0],e[1]);return Ee.fromTimestamp(t)},e.prototype.toDbTimestamp=function(e){var t=e.toTimestamp();return new nn(t.seconds,t.nanoseconds)},e.prototype.fromDbTimestamp=function(e){var t=new Te(e.seconds,e.nanoseconds);return Ee.fromTimestamp(t)},e.prototype.toDbMutationBatch=function(e,t){var n=this,r=t.baseMutations.map((function(e){return n.remoteSerializer.toMutation(e)})),i=t.mutations.map((function(e){return n.remoteSerializer.toMutation(e)}));return new an(e,t.batchId,t.localWriteTime.toMillis(),r,i)},e.prototype.fromDbMutationBatch=function(e){var t=this,n=(e.baseMutations||[]).map((function(e){return t.remoteSerializer.fromMutation(e)})),r=e.mutations.map((function(e){return t.remoteSerializer.fromMutation(e)})),i=Te.fromMillis(e.localWriteTimeMs);return new Qe(e.batchId,i,n,r)},e.prototype.toDbResourcePaths=function(e){var t=[];return e.forEach((function(e){t.push(ve(e.path))})),t},e.prototype.fromDbResourcePaths=function(e){for(var t=Ve(),n=0,r=e;n<r.length;n++){var i=r[n];t=t.add(new de(Se(i)))}return t},e.prototype.fromDbTarget=function(e){var t,n=this.fromDbTimestamp(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?this.fromDbTimestamp(e.lastLimboFreeSnapshotVersion):Ee.MIN,i=e.resumeToken;return t=void 0!==e.query.documents?this.remoteSerializer.fromDocumentsTarget(e.query):this.remoteSerializer.fromQueryTarget(e.query),new Cn(t,e.targetId,vn.Listen,e.lastListenSequenceNumber,n,r,i)},e.prototype.toDbTarget=function(e){v(vn.Listen===e.purpose,"Only queries with purpose "+vn.Listen+" may be stored, got "+e.purpose);var t,n,r=this.toDbTimestamp(e.snapshotVersion),i=this.toDbTimestamp(e.lastLimboFreeSnapshotVersion);return t=e.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(e.query):this.remoteSerializer.toQueryTarget(e.query),e.resumeToken instanceof Uint8Array?(v(ze.isMockPersistence(),"Persisting non-string stream tokens is only supported with mock persistence ."),n=e.resumeToken.toString()):n=e.resumeToken,new fn(e.targetId,e.query.canonicalId(),r,n,e.sequenceNumber,i,t)},e}();function _n(e,t){var n=e[0],r=e[1],i=t[0],o=t[1],a=J(n,i);return 0===a?J(r,o):a}var Nn=function(){function e(e){this.maxElements=e,this.buffer=new Ne(_n),this.previousIndex=0}return e.prototype.nextIndex=function(){return++this.previousIndex},e.prototype.addElement=function(e){var t=[e,this.nextIndex()];if(this.buffer.size<this.maxElements)this.buffer=this.buffer.add(t);else{var n=this.buffer.last();_n(t,n)<0&&(this.buffer=this.buffer.delete(n).add(t))}},Object.defineProperty(e.prototype,"maxValue",{get:function(){return this.buffer.last()[0]},enumerable:!0,configurable:!0}),e}(),An={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},kn=function(){function e(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}return e.withCacheSize=function(t){return new e(t,e.DEFAULT_COLLECTION_PE
1RCENTILE,e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)},e.COLLECTION_DISABLED=-1,e.MINIMUM_CACHE_SIZE_BYTES=1048576,e.DEFAULT_CACHE_SIZE_BYTES=41943040,e.DEFAULT_COLLECTION_PERCENTILE=10,e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,e.DEFAULT=new e(e.DEFAULT_CACHE_SIZE_BYTES,e.DEFAULT_COLLECTION_PERCENTILE,e.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),e.DISABLED=new e(e.COLLECTION_DISABLED,0,0),e}(),Rn=function(){function e(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.hasRun=!1,this.gcTask=null}return e.prototype.start=function(){v(null===this.gcTask,"Cannot start an already started LruScheduler"),this.garbageCollector.params.cacheSizeCollectionThreshold!==kn.COLLECTION_DISABLED&&this.scheduleGC()},e.prototype.stop=function(){this.gcTask&&(this.gcTask.cancel(),this.gcTask=null)},Object.defineProperty(e.prototype,"started",{get:function(){return null!==this.gcTask},enumerable:!0,configurable:!0}),e.prototype.scheduleGC=function(){var e=this;v(null===this.gcTask,"Cannot schedule GC while a task is pending");var t=this.hasRun?3e5:6e4;p("LruGarbageCollector","Garbage collection scheduled in "+t+"ms"),this.gcTask=this.asyncQueue.enqueueAfterDelay(te.LruGarbageCollection,t,(function(){return e.gcTask=null,e.hasRun=!0,e.localStore.collectGarbage(e.garbageCollector).then((function(){return e.scheduleGC()})).catch(Un)}))},e}(),Mn=function(){function e(e,t){this.delegate=e,this.params=t}return e.prototype.calculateTargetCount=function(e,t){return this.delegate.getSequenceNumberCount(e).next((function(e){return Math.floor(t/100*e)}))},e.prototype.nthSequenceNumber=function(e,t){var n=this;if(0===t)return We.resolve(se.INVALID);var r=new Nn(t);return this.delegate.forEachTarget(e,(function(e){return r.addElement(e.sequenceNumber)})).next((function(){return n.delegate.forEachOrphanedDocumentSequenceNumber(e,(function(e){return r.addElement(e)}))})).next((function(){return r.maxValue}))},e.prototype.removeTargets=function(e,t,n){return this.delegate.removeTargets(e,t,n)},e.prototype.removeOrphanedDocuments=function(e,t){return this.delegate.removeOrphanedDocuments(e,t)},e.prototype.collect=function(e,t){var n=this;return this.params.cacheSizeCollectionThreshold===kn.COLLECTION_DISABLED?(p("LruGarbageCollector","Garbage collection skipped; disabled"),We.resolve(An)):this.getCacheSize(e).next((function(r){return r<n.params.cacheSizeCollectionThreshold?(p("LruGarbageCollector","Garbage collection skipped; Cache size "+r+" is lower than threshold "+n.params.cacheSizeCollectionThreshold),An):n.runGarbageCollection(e,t)}))},e.prototype.getCacheSize=function(e){return this.delegate.getCacheSize(e)},e.prototype.runGarbageCollection=function(e,t){var n,r,o,a,s,u,c,h=this,l=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((function(t){return t>h.params.maximumSequenceNumbersToCollect?(p("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+h.params.maximumSequenceNumbersToCollect+" from "+t),r=h.params.maximumSequenceNumbersToCollect):r=t,a=Date.now(),h.nthSequenceNumber(e,r)})).next((function(r){return n=r,s=Date.now(),h.removeTargets(e,n,t)})).next((function(t){return o=t,u=Date.now(),h.removeOrphanedDocuments(e,n)})).next((function(e){(c=Date.now(),f()<=i.DEBUG)&&p("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(a-l)+"ms\n\tDetermined least recently used "+r+" in "+(s-a)+"ms\n\tRemoved "+o+" targets in "+(u-s)+"ms\n\tRemoved "+e+" documents in "+(c-u)+"ms\nTotal Duration: "+(c-l)+"ms");return We.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:o,documentsRemoved:e})}))},e}(),Ln=function(){function e(){this.onCommittedListeners=[]}return e.prototype.addOnCommittedListener=function(e){this.onCommittedListeners.push(e)},e.prototype.raiseOnCommittedEvent=function(){this.onCommittedListeners.forEach((function(e){return e()}))},e}(),On="IndexedDbPersistence",Pn=18e5,xn=5e3,qn="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",Vn="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.",Fn=function(e){function t(t,n){var r=e.call(this)||this;return r.simpleDbTransaction=t,r.currentSequenceNumber=n,r}return a.__extends(t,e),t}(Ln),Bn=function(){function e(t,n,r,i,o,a,s,u){if(this.allowTabSynchronization=t,this.persistenceKey=n,this.clientId=r,this.queue=a,this.sequenceNumberSyncer=u,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.windowUnloadHandler=null,this.inForeground=!1,this.documentVisibilityHandler=null,this.clientMetadataRefresher=null,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(e){return Promise.resolve()},this.referenceDelegate=new Wn(this,o),this.dbName=n+e.MAIN_DATABASE,this.serializer
1=new Dn(s),this.document=i.document,this.queryCache=new ut(this.referenceDelegate,this.serializer),this.indexManager=new En,this.remoteDocumentCache=new jt(this.serializer,this.indexManager),!i.window||!i.window.localStorage)throw new T(S.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=i.window,this.webStorage=this.window.localStorage}return e.getStore=function(e,t){if(e instanceof Fn)return ze.getStore(e.simpleDbTransaction,t);throw g("IndexedDbPersistence must use instances of IndexedDbTransaction")},e.createIndexedDbPersistence=function(t){return a.__awaiter(this,void 0,void 0,(function(){var n;return a.__generator(this,(function(r){switch(r.label){case 0:if(!e.isAvailable())throw new T(S.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");return[4,(n=new e(t.allowTabSynchronization,t.persistenceKey,t.clientId,t.platform,t.lruParams,t.queue,t.serializer,t.sequenceNumberSyncer)).start()];case 1:return r.sent(),[2,n]}}))}))},e.prototype.start=function(){var e=this;return v(!this.started,"IndexedDbPersistence double-started!"),v(null!==this.window,"Expected 'window' to be defined"),ze.openOrCreate(this.dbName,en,new tn(this.serializer)).then((function(t){return e.simpleDb=t,e.updateClientMetadataAndTryBecomePrimary()})).then((function(){return e.attachVisibilityHandler(),e.attachWindowUnloadHook(),e.scheduleClientMetadataAndPrimaryLeaseRefreshes(),e.simpleDb.runTransaction("readonly-idempotent",[pn.store],(function(e){return lt(e)}))})).then((function(t){e.listenSequence=new se(t,e.sequenceNumberSyncer)})).then((function(){e._started=!0})).catch((function(t){return e.simpleDb&&e.simpleDb.close(),Promise.reject(t)}))},e.prototype.setPrimaryStateListener=function(e){var t=this;return this.primaryStateListener=function(n){return a.__awaiter(t,void 0,void 0,(function(){return a.__generator(this,(function(t){return this.started?[2,e(n)]:[2]}))}))},e(this.isPrimary)},e.prototype.setDatabaseDeletedListener=function(e){var t=this;this.simpleDb.setVersionChangeListener((function(n){return a.__awaiter(t,void 0,void 0,(function(){return a.__generator(this,(function(t){switch(t.label){case 0:return null!==n.newVersion?[3,2]:[4,e()];case 1:t.sent(),t.label=2;case 2:return[2]}}
1))}))}))},e.prototype.setNetworkEnabled=function(e){var t=this;this.networkEnabled!==e&&(this.networkEnabled=e,this.queue.enqueueAndForget((function(){return a.__awaiter(t,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.started?[4,this.updateClientMetadataAndTryBecomePrimary()]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}}))}))})))},e.prototype.updateClientMetadataAndTryBecomePrimary=function(){var e=this;return this.simpleDb.runTransaction("readwrite",Tn,(function(t){return Kn(t).put(new gn(e.clientId,Date.now(),e.networkEnabled,e.inForeground)).next((function(){if(e.isPrimary)return e.verifyPrimaryLease(t).next((function(t){t||(e.isPrimary=!1,e.queue.enqueueAndForget((function(){return e.primaryStateListener(!1)})))}))})).next((function(){return e.canActAsPrimary(t)})).next((function(n){var r=e.isPrimary;return e.isPrimary=n,r!==e.isPrimary&&e.queue.enqueueAndForget((function(){return e.primaryStateListener(e.isPrimary)})),r&&!e.isPrimary?e.releasePrimaryLeaseIfHeld(t):e.isPrimary?e.acquireOrExtendPrimaryLease(t):void 0}))}))},e.prototype.verifyPrimaryLease=function(e){var t=this;return Qn(e).get(rn.key).next((function(e){return We.resolve(t.isLocalClient(e))}))},e.prototype.removeClientMetadata=function(e){return Kn(e).delete(this.clientId)},e.prototype.maybeGarbageCollectMultiClientState=function(){return a.__awaiter(this,void 0,void 0,(function(){var t=this;return a.__generator(this,(function(n){switch(n.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,Pn)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary-idempotent",(function(n){var r=e.getStore(n,gn.store);return r.loadAll().next((function(e){var n=t.filterActiveClients(e,Pn),i=e.filter((function(e){return-1===n.indexOf(e)}));return We.forEach(i,(function(e){return r.delete(e.clientId)})).next((function(){return i}))}))}))]);case 1:n.sent().forEach((function(e){t.window.localStorage.removeItem(t.zombiedClientLocalStorageKey(e.clientId))})),n.label=2;case 2:return[2]}}
1))}))},e.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var e=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(te.ClientMetadataRefresh,4e3,(function(){return e.updateClientMetadataAndTryBecomePrimary().then((function(){return e.maybeGarbageCollectMultiClientState()})).then((function(){return e.scheduleClientMetadataAndPrimaryLeaseRefreshes()}))}))},e.prototype.isLocalClient=function(e){return!!e&&e.ownerId===this.clientId},e.prototype.canActAsPrimary=function(e){var t=this;return Qn(e).get(rn.key).next((function(n){if(null!==n&&t.isWithinAge(n.leaseTimestampMs,xn)&&!t.isClientZombied(n.ownerId)){if(t.isLocalClient(n)&&t.networkEnabled)return!0;if(!t.isLocalClient(n)){if(!n.allowTabSynchronization)throw new T(S.FAILED_PRECONDITION,Vn);return!1}}return!(!t.networkEnabled||!t.inForeground)||Kn(e).loadAll().next((function(e){return void 0===t.filterActiveClients(e,xn).find((function(e){if(t.clientId!==e.clientId){var n=!t.networkEnabled&&e.networkEnabled,r=!t.inForeground&&e.inForeground,i=t.networkEnabled===e.networkEnabled;if(n||r&&i)return!0}return!1}))}))})).next((function(e){return t.isPrimary!==e&&p(On,"Client "+(e?"is":"is not")+" eligible for a primary lease."),e}))},e.prototype.shutdown=function(){return a.__awaiter(this,void 0,void 0,(function(){var e=this;return a.__generator(this,(function(t){switch(t.label){case 0:return this._started=!1,this.markClientZombied(),this.clientMetadataRefresher&&(this.clientMetadataRefresher.cancel(),this.clientMetadataRefresher=null),this.detachVisibilityHandler(),this.detachWindowUnloadHook(),[4,this.simpleDb.runTransaction("readwrite-idempotent",[rn.store,gn.store],(function(t){return e.releasePrimaryLeaseIfHeld(t).next((function(){return e.removeClientMetadata(t)}))}))];case 1:return t.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),[2]}}))}))},e.prototype.filterActiveClients=function(e,t){var n=this;return e.filter((function(e){return n.isWithinAge(e.updateTimeMs,t)&&!n.isClientZombied(e.clientId)}))},e.prototype.getActiveClients=function(){var e=this;return this.simpleDb.runTransaction("readonly-idempotent",[gn.store],(function(t){return Kn(t).loadAll().next((function(t){return e.filterActiveClients(t,Pn).map((function(e){return e.clientId}))}))}))},e.clearPersistence=function(t){return a.__awaiter(this,void 0,void 0,(function(){var n;return a.__generator(this,(function(r){switch(r.label){case 0:return e.isAvailable()?(n=t+e.MAIN_DATABASE,[4,ze.delete(n)]):[2,Promise.resolve()];case 1:return r.sent(),[2]}}))}))},Object.defineProperty(e.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),e.prototype.getMutationQueue=function(e){return v(this.started,"Cannot initialize MutationQueue before persistence is started."),$e.forUser(e,this.serializer,this.indexManager,this.referenceDelegate)},e.prototype.getQueryCache=function(){return v(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},e.prototype.getRemoteDocumentCache=function(){return v(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},e.prototype.getIndexManager=function(){return v(this.started,"Cannot initialize IndexManager before persistence is started."),this.indexManager},e.prototype.runTransaction=function(e,t,n){var r=this;p(On,"Starting transaction:",e);var i,o=t.endsWith("idempotent"),a=t.startsWith("readonly")?o?"readonly-idempotent":"readonly":o?"readwrite-idempotent":"readwrite";return this.simpleDb.runTransaction(a,Tn,(function(o){return i=new Fn(o,r.listenSequence.next()),"readwrite-primary"===t||"readwrite-primary-idempotent"===t?r.verifyPrimaryLease(o).next((function(t){if(!t)throw m("Failed to obtain primary lease for action '"+e+"'."),r.isPrimary=!1,r.queue.enqueueAndForget((function(){return r.primaryStateListener(!1)})),new T(S.FAILED_PRECONDITION,qn);return n(i)})).next((function(e){return r.acquireOrExtendPrimaryLease(o).next((function(){return e}))})):r.verifyAllowTabSynchronization(o).next((function(){return n(i)}))})).then((function(e){return i.raiseOnCommittedEvent(),e}))},e.prototype.verifyAllowTabSynchronization=function(e){var t=this;return Qn(e).get(rn.key).next((function(e){if(null!==e&&t.isWithinAge(e.leaseTimestampMs,xn)&&!t.isClientZombied(e.ownerId)&&!t.isLocalClient(e)&&!e.allowTabSynchronization)throw new T(S.FAILED_PRECONDITION,Vn)}))},e.prototype.acquireOrExtendPrimaryLease=function(e){var t=new rn(this.clientId,this.allowTabSynchronization,Date.now());return Qn(e).put(rn.key,t)}
1,e.isAvailable=function(){return ze.isAvailable()},e.buildStoragePrefix=function(e){var t=e.databaseId.projectId;return e.databaseId.isDefaultDatabase||(t+="."+e.databaseId.database),"firestore/"+e.persistenceKey+"/"+t+"/"},e.prototype.releasePrimaryLeaseIfHeld=function(e){var t=this,n=Qn(e);return n.get(rn.key).next((function(e){return t.isLocalClient(e)?(p(On,"Releasing primary lease."),n.delete(rn.key)):We.resolve()}))},e.prototype.isWithinAge=function(e,t){var n=Date.now();return!(e<n-t)&&(!(e>n)||(m("Detected an update time that is in the future: "+e+" > "+n),!1))},e.prototype.attachVisibilityHandler=function(){var e=this;null!==this.document&&"function"===typeof this.document.addEventListener&&(this.documentVisibilityHandler=function(){e.queue.enqueueAndForget((function(){return e.inForeground="visible"===e.document.visibilityState,e.updateClientMetadataAndTryBecomePrimary()}))},this.document.addEventListener("visibilitychange",this.documentVisibilityHandler),this.inForeground="visible"===this.document.visibilityState)},e.prototype.detachVisibilityHandler=function(){this.documentVisibilityHandler&&(v(null!==this.document&&"function"===typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.documentVisibilityHandler),this.documentVisibilityHandler=null)},e.prototype.attachWindowUnloadHook=function(){var e=this;"function"===typeof this.window.addEventListener&&(this.windowUnloadHandler=function(){e.markClientZombied(),e.queue.enqueueAndForget((function(){return e.shutdown()}))},this.window.addEventListener("unload",this.windowUnloadHandler))},e.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(v("function"===typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},e.prototype.isClientZombied=function(e){try{var t=null!==this.webStorage.getItem(this.zombiedClientLocalStorageKey(e));return p(On,"Client '"+e+"' "+(t?"is":"is not")+" zombied in LocalStorage"),t}catch(n){return m(On,"Failed to get zombied client id.",n),!1}},e.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(e){m("Failed to set zombie client id.",e)}},e.prototype.removeClientZombiedEntry=function(){try{this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId))}catch(e){}},e.prototype.zombiedClientLocalStorageKey=function(e){return"firestore_zombie_"+this.persistenceKey+"_"+e},e.MAIN_DATABASE="main",e}();function Un(e){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(t){if(!function(e){return e.code===S.FAILED_PRECONDITION&&e.message===qn}(e))throw e;return p(On,"Unexpectedly lost primary lease"),[2]}))}))}function Qn(e){return e.store(rn.store)}function Kn(e){return e.store(gn.store)}var Wn=function(){function e(e,t){this.db=e,this.inMemoryPins=null,this.garbageCollector=new Mn(this,t)}return e.prototype.getSequenceNumberCount=function(e){var t=this.orphanedDocmentCount(e);return this.db.getQueryCache().getQueryCount(e).next((function(e){return t.next((function(t){return e+t}))}))},e.prototype.orphanedDocmentCount=function(e){var t=0;return this.forEachOrphanedDocumentSequenceNumber(e,(function(e){t++})).next((function(){return t}))},e.prototype.forEachTarget=function(e,t){return this.db.getQueryCache().forEachTarget(e,t)},e.prototype.forEachOrphanedDocumentSequenceNumber=function(e,t){return this.forEachOrphanedDocument(e,(function(e,n){return t(n)}))},e.prototype.setInMemoryPins=function(e){this.inMemoryPins=e},e.prototype.addReference=function(e,t){return Gn(e,t)},e.prototype.removeReference=function(e,t){return Gn(e,t)},e.prototype.removeTargets=function(e,t,n){return this.db.getQueryCache().removeTargets(e,t,n)},e.prototype.removeMutationReference=function(e,t){return Gn(e,t)},e.prototype.isPinned=function(e,t){return this.inMemoryPins.containsKey(t)?We.resolve(!0):function(e,t){var n=!1;return ot(e).iterateSerial((function(r){return et(e,r,t).next((function(e){return e&&(n=!0),We.resolve(!e)}))})).next((function(){return n}))}(e,t)},e.prototype.removeOrphanedDocuments=function(e,t){var n=this,r=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[],o=0;return this.forEachOrphanedDocument(e,(function(a,s){if(s<=t){var u=n.isPinned(e,a).next((function(t){if(!t)return o++,r.getEntry(e,a).next((function(){return r.removeEntry(a),ft(e).delete([0,ve(a.path)])}))}));i.push(u)}})).next((function(){return We.waitFor(i)})).next((function(){return r.apply(e)})).next((function(){return o}
1))},e.prototype.removeTarget=function(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getQueryCache().updateQueryData(e,n)},e.prototype.updateLimboDocument=function(e,t){return Gn(e,t)},e.prototype.forEachOrphanedDocument=function(e,t){var n,r=ft(e),i=se.INVALID;return r.iterate({index:dn.documentTargetsIndex},(function(e,r){var o=e[0],a=(e[1],r.path),s=r.sequenceNumber;0===o?(i!==se.INVALID&&t(new de(Se(n)),i),i=s,n=a):i=se.INVALID})).next((function(){i!==se.INVALID&&t(new de(Se(n)),i)}))},e.prototype.getCacheSize=function(e){return this.db.getRemoteDocumentCache().getSize(e)},e}();function Gn(e,t){return ft(e).put(function(e,t){return new dn(0,ve(e.path),t)}(t,e.currentSequenceNumber))}var zn=function(){function e(e,t,n){this.remoteDocumentCache=e,this.mutationQueue=t,this.indexManager=n}return e.prototype.getDocument=function(e,t){var n=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(e,t).next((function(r){return n.getDocumentInternal(e,t,r)}))},e.prototype.getDocumentInternal=function(e,t,n){return this.remoteDocumentCache.getEntry(e,t).next((function(e){for(var r=0,i=n;r<i.length;r++){e=i[r].applyToLocalView(t,e)}return e}))},e.prototype.applyLocalMutationsToDocuments=function(e,t,n){var r=Me();return t.forEach((function(e,t){for(var i=0,o=n;i<o.length;i++){t=o[i].applyToLocalView(e,t)}r=r.insert(e,t)})),r},e.prototype.getDocuments=function(e,t){var n=this;return this.remoteDocumentCache.getEntries(e,t).next((function(t){return n.getLocalViewOfDocuments(e,t)}))},e.prototype.getLocalViewOfDocuments=function(e,t){var n=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((function(r){var i=n.applyLocalMutationsToDocuments(e,t,r),o=Re();return i.forEach((function(e,t){t||(t=new Kt(e,Ee.forDeletedDoc())),o=o.insert(e,t)})),o}))},e.prototype.getDocumentsMatchingQuery=function(e,t,n){return t.isDocumentQuery()?this.getDocumentsMatchingDocumentQuery(e,t.path):t.isCollectionGroupQuery()?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n)},e.prototype.getDocumentsMatchingDocumentQuery=function(e,t){return this.getDocument(e,new de(t)).next((function(e){var t=Oe();return e instanceof Qt&&(t=t.insert(e.key,e)),t}))},e.prototype.getDocumentsMatchingCollectionGroupQuery=function(e,t,n){var r=this;v(t.path.isEmpty(),"Currently we only support collection group queries at the root.");var i=t.collectionGroup,o=Oe();return this.indexManager.getCollectionParents(e,i).next((function(a){return We.forEach(a,(function(a){var s=t.asCollectionQueryAtPath(a.child(i));return r.getDocumentsMatchingCollectionQuery(e,s,n).next((function(e){e.forEach((function(e,t){o=o.insert(e,t)}))}))})).next((function(){return o}))}))},e.prototype.getDocumentsMatchingCollectionQuery=function(e,t,n){var r,i,o=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n).next((function(n){return r=n,o.mutationQueue.getAllMutationBatchesAffectingQuery(e,t)})).next((function(t){return i=t,o.addMissingBaseDocuments(e,i,r).next((function(e){r=e;for(var t=0,n=i;t<n.length;t++)for(var o=n[t],a=0,s=o.mutations;a<s.length;a++){var u=s[a],c=u.key,h=r.get(c),l=u.applyToLocalView(h,h,o.localWriteTime);r=l instanceof Qt?r.insert(c,l):r.remove(c)}}))})).next((function(){return r.forEach((function(e,n){t.matches(n)||(r=r.remove(e))})),r}))},e.prototype.addMissingBaseDocuments=function(e,t,n){for(var r=Ve(),i=0,o=t;i<o.length;i++)for(var a=0,s=o[i].mutations;a<s.length;a++){var u=s[a];u instanceof Tt&&null===n.get(u.key)&&(r=r.add(u.key))}var c=n;return this.remoteDocumentCache.getEntries(e,r).next((function(e){return e.forEach((function(e,t){null!==t&&t instanceof Qt&&(c=c.insert(e,t))})),c}))},e}(),jn=function(){function e(){this.refsByKey=new Ne(Hn.compareByKey),this.refsByTarget=new Ne(Hn.compareByTargetId)}return e.prototype.isEmpty=function(){return this.refsByKey.isEmpty()},e.prototype.addReference=function(e,t){var n=new Hn(e,t);this.refsByKey=this.refsByKey.add(n),this.refsByTarget=this.refsByTarget.add(n)},e.prototype.addReferences=function(e,t){var n=this;e.forEach((function(e){return n.addReference(e,t)}))},e.prototype.removeReference=function(e,t){this.removeRef(new Hn(e,t))},e.prototype.removeReferences=function(e,t){var n=this;e.forEach((function(e){return n.removeReference(e,t)}))},e.prototype.removeReferencesForId=function(e){var t=this,n=de.EMPTY,r=new Hn(n,e),i=new Hn(n,e+1),o=[];return this.refsByTarget.forEachInRange([r,i],(function(e){t.removeRef(e),o.push(e.key)})),o},e.prototype.removeAllReferences=function(){var e=this;
1this.refsByKey.forEach((function(t){return e.removeRef(t)}))},e.prototype.removeRef=function(e){this.refsByKey=this.refsByKey.delete(e),this.refsByTarget=this.refsByTarget.delete(e)},e.prototype.referencesForId=function(e){var t=de.EMPTY,n=new Hn(t,e),r=new Hn(t,e+1),i=Ve();return this.refsByTarget.forEachInRange([n,r],(function(e){i=i.add(e.key)})),i},e.prototype.containsKey=function(e){var t=new Hn(e,0),n=this.refsByKey.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)},e}(),Hn=function(){function e(e,t){this.key=e,this.targetOrBatchId=t}return e.compareByKey=function(e,t){return de.comparator(e.key,t.key)||J(e.targetOrBatchId,t.targetOrBatchId)},e.compareByTargetId=function(e,t){return J(e.targetOrBatchId,t.targetOrBatchId)||de.comparator(e.key,t.key)},e}(),Yn="LocalStore",Jn=function(){function e(e,t,n){this.persistence=e,this.queryEngine=t,this.localViewReferences=new jn,this.queryDataByTarget=new Ie(J),this.targetIdByQuery=new Gt((function(e){return e.canonicalId()})),this.lastDocumentChangeReadTime=Ee.MIN,v(e.started,"LocalStore was passed an unstarted persistence implementation"),this.persistence.referenceDelegate.setInMemoryPins(this.localViewReferences),this.mutationQueue=e.getMutationQueue(n),this.remoteDocuments=e.getRemoteDocumentCache(),this.queryCache=e.getQueryCache(),this.localDocuments=new zn(this.remoteDocuments,this.mutationQueue,this.persistence.getIndexManager()),this.queryEngine.setLocalDocumentsView(this.localDocuments)}return e.prototype.start=function(){return this.synchronizeLastDocumentChangeReadTime()},e.prototype.handleUserChange=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n,r,i=this;return a.__generator(this,(function(o){switch(o.label){case 0:return t=this.mutationQueue,n=this.localDocuments,[4,this.persistence.runTransaction("Handle user change","readonly-idempotent",(function(r){var o;
1return i.mutationQueue.getAllMutationBatches(r).next((function(a){return o=a,t=i.persistence.getMutationQueue(e),n=new zn(i.remoteDocuments,t,i.persistence.getIndexManager()),t.getAllMutationBatches(r)})).next((function(e){for(var t=[],i=[],a=Ve(),s=0,u=o;s<u.length;s++){var c=u[s];t.push(c.batchId);for(var h=0,l=c.mutations;h<l.length;h++){var f=l[h];a=a.add(f.key)}}for(var d=0,p=e;d<p.length;d++){c=p[d];i.push(c.batchId);for(var m=0,y=c.mutations;m<y.length;m++){f=y[m];a=a.add(f.key)}}return n.getDocuments(r,a).next((function(e){return{affectedDocuments:e,removedBatchIds:t,addedBatchIds:i}}))}))}))];case 1:return r=o.sent(),this.mutationQueue=t,this.localDocuments=n,this.queryEngine.setLocalDocumentsView(this.localDocuments),[2,r]}}))}))},e.prototype.localWrite=function(e){var t,n=this,r=Te.now(),i=e.reduce((function(e,t){return e.add(t.key)}),Ve());return this.persistence.runTransaction("Locally write mutations","readwrite-idempotent",(function(o){return n.localDocuments.getDocuments(o,i).next((function(i){t=i;for(var a=[],s=0,u=e;s<u.length;s++){var c=u[s],h=c.extractBaseValue(t.get(c.key));null!=h&&a.push(new Tt(c.key,h,h.fieldMask(),wt.exists(!0)))}
1return n.mutationQueue.addMutationBatch(o,r,a,e)}))})).then((function(e){var n=e.applyToLocalDocumentSet(t);return{batchId:e.batchId,changes:n}}))},e.prototype.lookupMutationDocuments=function(e){var t=this;return this.persistence.runTransaction("Lookup mutation documents","readonly-idempotent",(function(n){return t.mutationQueue.lookupMutationKeys(n,e).next((function(e){return e?t.localDocuments.getDocuments(n,e):We.resolve(null)}))}))},e.prototype.acknowledgeBatch=function(e){var t=this;return this.persistence.runTransaction("Acknowledge batch","readwrite-primary-idempotent",(function(n){var r=e.batch.keys(),i=t.remoteDocuments.newChangeBuffer({trackRemovals:!0});return t.mutationQueue.acknowledgeBatch(n,e.batch,e.streamToken).next((function(){return t.applyWriteToRemoteDocuments(n,e,i)})).next((function(){return i.apply(n)})).next((function(){return t.mutationQueue.performConsistencyCheck(n)})).next((function(){return t.localDocuments.getDocuments(n,r)}))}))},e.prototype.rejectBatch=function(e){var t=this;return this.persistence.runTransaction("Reject batch","readwrite-primary-idempotent",(function(n){var r;return t.mutationQueue.lookupMutationBatch(n,e).next((function(e){return v(null!==e,"Attempt to reject nonexistent batch!"),r=e.keys(),t.mutationQueue.removeMutationBatch(n,e)})).next((function(){return t.mutationQueue.performConsistencyCheck(n)})).next((function(){return t.localDocuments.getDocuments(n,r)}))}))},e.prototype.getHighestUnacknowledgedBatchId=function(){var e=this;return this.persistence.runTransaction("Get highest unacknowledged batch id","readonly-idempotent",(function(t){return e.mutationQueue.getHighestUnacknowledgedBatchId(t)}))},e.prototype.getLastStreamToken=function(){var e=this;return this.persistence.runTransaction("Get last stream token","readonly-idempotent",(function(t){return e.mutationQueue.getLastStreamToken(t)}))},e.prototype.setLastStreamToken=function(e){var t=this;return this.persistence.runTransaction("Set last stream token","readwrite-primary-idempotent",(function(n){return t.mutationQueue.setLastStreamToken(n,e)}))},e.prototype.getLastRemoteSnapshotVersion=function(){var e=this;return this.persistence.runTransaction("Get last remote snapshot version","readonly-idempotent",(function(t){return e.queryCache.getLastRemoteSnapshotVersion(t)}))},e.prototype.applyRemoteEvent=function(t){var n=this,r=t.snapshotVersion,i=this.queryDataByTarget;return this.persistence.runTransaction("Apply remote event","readwrite-primary-idempotent",(function(o){var a=n.remoteDocuments.newChangeBuffer({trackRemovals:!0});i=n.queryDataByTarget;var s=[];D(t.targetChanges,(function(t,a){var u=i.get(t);if(u){s.push(n.queryCache.removeMatchingKeys(o,a.removedDocuments,t).next((function(){return n.queryCache.addMatchingKeys(o,a.addedDocuments,t)})));var c=a.resumeToken;if(c.length>0){var h=u.withResumeToken(c,r).withSequenceNumber(o.currentSequenceNumber);i=i.insert(t,h),e.shouldPersistQueryData(u,h,a)&&s.push(n.queryCache.updateQueryData(o,h))}}}));var u=Re(),c=Ve();if(t.documentUpdates.forEach((function(e,t){c=c.add(e)})),s.push(a.getEntries(o,c).next((function(e){t.documentUpdates.forEach((function(i,c){var h=e.get(i);c instanceof Kt&&c.version.isEqual(Ee.MIN)?(a.removeEntry(i,r),u=u.insert(i,c)):null==h||c.version.compareTo(h.version)>0||0===c.version.compareTo(h.version)&&h.hasPendingWrites?(Ee.MIN.isEqual(r)&&m(Yn,"Cannot add a document when the remote version is zero"),a.addEntry(c,r),u=u.insert(i,c)):p(Yn,"Ignoring outdated watch update for ",i,". Current version:",h.version," Watch version:",c.version),t.resolvedLimboDocuments.has(i)&&s.push(n.persistence.referenceDelegate.updateLimboDocument(o,i))}))}))),!r.isEqual(Ee.MIN)){var h=n.queryCache.getLastRemoteSnapshotVersion(o).next((function(e){return v(r.compareTo(e)>=0,"Watch stream reverted to previous snapshot?? "+r+" < "+e),n.queryCache.setTargetsMetadata(o,o.currentSequenceNumber,r)}));s.push(h)}return We.waitFor(s).next((function(){return a.apply(o)})).next((function(){return n.localDocuments.getLocalViewOfDocuments(o,u)}))}
1)).then((function(e){return n.queryDataByTarget=i,e}))},e.shouldPersistQueryData=function(e,t,n){return v(t.resumeToken.length>0,"Attempted to persist query data with no resume token"),0===e.resumeToken.length||(t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=this.RESUME_TOKEN_MAX_AGE_MICROS||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0)},e.prototype.notifyLocalViewChanges=function(e){for(var t=this,n=0,r=e;n<r.length;n++){var i=r[n],o=i.targetId;if(this.localViewReferences.addReferences(i.addedKeys,o),this.localViewReferences.removeReferences(i.removedKeys,o),!i.fromCache){var a=this.queryDataByTarget.get(o);v(null!==a,"Can't set limbo-free snapshot version for unknown target: "+o);var s=a.snapshotVersion,u=a.withLastLimboFreeSnapshotVersion(s);this.queryDataByTarget=this.queryDataByTarget.insert(o,u)}}return this.persistence.runTransaction("notifyLocalViewChanges","readwrite-idempotent",(function(n){return We.forEach(e,(function(e){return We.forEach(e.removedKeys,(function(e){return t.persistence.referenceDelegate.removeReference(n,e)}))}))}))},e.prototype.nextMutationBatch=function(e){var t=this;return this.persistence.runTransaction("Get next mutation batch","readonly-idempotent",(function(n){return void 0===e&&(e=Ue),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e)}))},e.prototype.readDocument=function(e){var t=this;return this.persistence.runTransaction("read document","readonly-idempotent",(function(n){return t.localDocuments.getDocument(n,e)}))},e.prototype.allocateQuery=function(e){var t=this;return this.persistence.runTransaction("Allocate query","readwrite-idempotent",(function(n){var r;return t.queryCache.getQueryData(n,e).next((function(i){return i?(r=i,We.resolve(r)):t.queryCache.allocateTargetId(n).next((function(i){return r=new Cn(e,i,vn.Listen,n.currentSequenceNumber),t.queryCache.addQueryData(n,r).next((function(){return r}))}))}))})).then((function(n){return v(null===t.queryDataByTarget.get(n.targetId),"Tried to allocate an already allocated query: "+e),t.queryDataByTarget=t.queryDataByTarget.insert(n.targetId,n),t.targetIdByQuery.set(e,n.targetId),n}))},e.prototype.getQueryData=function(e,t){var n=this.targetIdByQuery.get(t);return void 0!==n?We.resolve(this.queryDataByTarget.get(n)):this.queryCache.getQueryData(e,t)},e.prototype.releaseQuery=function(e,t){var n,r=this,i=t?"readwrite-idempotent":"readwrite-primary-idempotent";return this.persistence.runTransaction("Release query",i,(function(i){var o=r.targetIdByQuery.get(e);v(void 0!==o,"Tried to release nonexistent query: "+e),n=o;var a=r.queryDataByTarget.get(n),s=r.localViewReferences.removeReferencesForId(n);return t?We.resolve():We.forEach(s,(function(e){return r.persistence.referenceDelegate.removeReference(i,e)})).next((function(){r.persistence.referenceDelegate.removeTarget(i,a)}))})).then((function(){r.queryDataByTarget=r.queryDataByTarget.remove(n),r.targetIdByQuery.delete(e)}))},e.prototype.executeQuery=function(e,t){var n=this,r=Ee.MIN,i=Ve();return this.persistence.runTransaction("Execute query","readonly-idempotent",(function(o){return n.getQueryData(o,e).next((function(e){if(e)return r=e.lastLimboFreeSnapshotVersion,n.queryCache.getMatchingKeysForTargetId(o,e.targetId).next((function(e){i=e}))})).next((function(){return n.queryEngine.getDocumentsMatchingQuery(o,e,t?r:Ee.MIN,t?i:Ve())})).next((function(e){return{documents:e,remoteKeys:i}}))}))},e.prototype.remoteDocumentKeys=function(e){var t=this;return this.persistence.runTransaction("Remote document keys","readonly-idempotent",(function(n){return t.queryCache.getMatchingKeysForTargetId(n,e)}))},e.prototype.getActiveClients=function(){return this.persistence.getActiveClients()},e.prototype.removeCachedMutationBatchMetadata=function(e){this.mutationQueue.removeCachedMutationKeys(e)},e.prototype.setNetworkEnabled=function(e){this.persistence.setNetworkEnabled(e)},e.prototype.applyWriteToRemoteDocuments=function(e,t,n){var r=this,i=t.batch,o=i.keys(),a=We.resolve();return o.forEach((function(r){a=a.next((function(){return n.getEntry(e,r)})).next((function(e){var o=e,a=t.docVersions.get(r);v(null!==a,"ackVersions should contain every doc in the write."),(!o||o.version.compareTo(a)<0)&&((o=i.applyToRemoteDocument(r,o,t))?n.addEntry(o,t.commitVersion):v(!e,"Mutation batch "+i+" applied to document "+e+" resulted in null"))}))}
1)),a.next((function(){return r.mutationQueue.removeMutationBatch(e,i)}))},e.prototype.collectGarbage=function(e){var t=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary-idempotent",(function(n){return e.collect(n,t.queryDataByTarget)}))},e.prototype.getQueryForTarget=function(e){var t=this,n=this.queryDataByTarget.get(e);return n?Promise.resolve(n.query):this.persistence.runTransaction("Get query data","readonly-idempotent",(function(n){return t.queryCache.getQueryDataForTarget(n,e).next((function(e){return e?e.query:null}))}))},e.prototype.getNewDocumentChanges=function(){var e=this;return this.persistence.runTransaction("Get new document changes","readonly-idempotent",(function(t){return e.remoteDocuments.getNewDocumentChanges(t,e.lastDocumentChangeReadTime)})).then((function(t){var n=t.changedDocs,r=t.readTime;return e.lastDocumentChangeReadTime=r,n}))},e.prototype.synchronizeLastDocumentChangeReadTime=function(){return a.__awaiter(this,void 0,void 0,(function(){var e,t=this;return a.__generator(this,(function(n){return this.remoteDocuments instanceof jt?(e=this.remoteDocuments,[2,this.persistence.runTransaction("Synchronize last document change read time","readonly-idempotent",(function(t){return e.getLastDocumentChange(t)})).then((function(e){var n=e.readTime;t.lastDocumentChangeReadTime=n}))]):[2]}))}))},e.RESUME_TOKEN_MAX_AGE_MICROS=3e8,e}(),Xn=function(){function e(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.nextBatchId=1,this.lastStreamToken=b(),this.batchesByDocumentKey=new Ne(Hn.compareByKey)}return e.prototype.checkEmpty=function(e){return We.resolve(0===this.mutationQueue.length)},e.prototype.acknowledgeBatch=function(e,t,n){var r=t.batchId,i=this.indexOfExistingBatchId(r,"acknowledged");v(0===i,"Can only acknowledge the first batch in the mutation queue");var o=this.mutationQueue[i];return v(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),this.lastStreamToken=n,We.resolve()},e.prototype.getLastStreamToken=function(e){return We.resolve(this.lastStreamToken)},e.prototype.setLastStreamToken=function(e,t){return this.lastStreamToken=t,We.resolve()},e.prototype.addMutationBatch=function(e,t,n,r){v(0!==r.length,"Mutation batches should not be empty");var i=this.nextBatchId;(this.nextBatchId++,this.mutationQueue.length>0)&&v(this.mutationQueue[this.mutationQueue.length-1].batchId<i,"Mutation batchIDs must be monotonically increasing order");var o=new Qe(i,t,n,r);this.mutationQueue.push(o);for(var a=0,s=r;a<s.length;a++){var u=s[a];this.batchesByDocumentKey=this.batchesByDocumentKey.add(new Hn(u.key,i)),this.indexManager.addToCollectionParentIndex(e,u.key.path.popLast())}return We.resolve(o)},e.prototype.lookupMutationBatch=function(e,t){return We.resolve(this.findMutationBatch(t))},e.prototype.lookupMutationKeys=function(e,t){var n=this.findMutationBatch(t);return v(null!=n,"Failed to find local mutation batch."),We.resolve(n.keys())},e.prototype.getNextMutationBatchAfterBatchId=function(e,t){var n=t+1,r=this.indexOfBatchId(n),i=r<0?0:r;return We.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)},e.prototype.getHighestUnacknowledgedBatchId=function(){return We.resolve(0===this.mutationQueue.length?Ue:this.nextBatchId-1)},e.prototype.getAllMutationBatches=function(e){return We.resolve(this.mutationQueue.slice())},e.prototype.getAllMutationBatchesAffectingDocumentKey=function(e,t){var n=this,r=new Hn(t,0),i=new Hn(t,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([r,i],(function(e){v(t.isEqual(e.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(e.targetOrBatchId);v(null!==r,"Batches in the index must exist in the main table"),o.push(r)})),We.resolve(o)},e.prototype.getAllMutationBatchesAffectingDocumentKeys=function(e,t){var n=this,r=new Ne(J);return t.forEach((function(e){var t=new Hn(e,0),i=new Hn(e,Number.POSITIVE_INFINITY);n.batchesByDocumentKey.forEachInRange([t,i],(function(t){v(e.isEqual(t.key),"For each key, should only iterate over a single key's batches"),r=r.add(t.targetOrBatchId)}))})),We.resolve(this.findMutationBatches(r))},e.prototype.getAllMutationBatchesAffectingQuery=function(e,t){v(!t.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var n=t.path,r=n.length+1,i=n;de.isDocumentKey(i)||(i=i.child(""));var o=new Hn(new de(i),0),a=new Ne(J);
1return this.batchesByDocumentKey.forEachWhile((function(e){var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.targetOrBatchId)),!0)}),o),We.resolve(this.findMutationBatches(a))},e.prototype.findMutationBatches=function(e){var t=this,n=[];return e.forEach((function(e){var r=t.findMutationBatch(e);null!==r&&n.push(r)})),n},e.prototype.removeMutationBatch=function(e,t){var n=this;v(0===this.indexOfExistingBatchId(t.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.mutationQueue.shift();var r=this.batchesByDocumentKey;return We.forEach(t.mutations,(function(i){var o=new Hn(i.key,t.batchId);return r=r.delete(o),n.referenceDelegate.removeMutationReference(e,i.key)})).next((function(){n.batchesByDocumentKey=r}))},e.prototype.removeCachedMutationKeys=function(e){},e.prototype.containsKey=function(e,t){var n=new Hn(t,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return We.resolve(t.isEqual(r&&r.key))},e.prototype.performConsistencyCheck=function(e){return 0===this.mutationQueue.length&&v(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),We.resolve()},e.prototype.indexOfExistingBatchId=function(e,t){var n=this.indexOfBatchId(e);return v(n>=0&&n<this.mutationQueue.length,"Batches must exist to be "+t),n},e.prototype.indexOfBatchId=function(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId},e.prototype.findMutationBatch=function(e){var t=this.indexOfBatchId(e);if(t<0||t>=this.mutationQueue.length)return null;var n=this.mutationQueue[t];return v(n.batchId===e,"If found batch must match"),n},e}(),Zn=function(){function e(e){this.persistence=e,this.queries=new Gt((function(e){return e.canonicalId()})),this.lastRemoteSnapshotVersion=Ee.MIN,this.highestTargetId=0,this.highestSequenceNumber=0,this.references=new jn,this.targetCount=0,this.targetIdGenerator=st.forQueryCache()}return e.prototype.getTargetCount=function(e){return We.resolve(this.targetCount)},e.prototype.forEachTarget=function(e,t){return this.queries.forEach((function(e,n){return t(n)})),We.resolve()},e.prototype.getLastRemoteSnapshotVersion=function(e){return We.resolve(this.lastRemoteSnapshotVersion)},e.prototype.getHighestSequenceNumber=function(e){return We.resolve(this.highestSequenceNumber)},e.prototype.allocateTargetId=function(e){var t=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=t,We.resolve(t)},e.prototype.setTargetsMetadata=function(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.highestSequenceNumber&&(this.highestSequenceNumber=t),We.resolve()},e.prototype.saveQueryData=function(e){this.queries.set(e.query,e);var t=e.targetId;t>this.highestTargetId&&(this.highestTargetId=t),e.sequenceNumber>this.highestSequenceNumber&&(this.highestSequenceNumber=e.sequenceNumber)},e.prototype.addQueryData=function(e,t){return v(!this.queries.has(t.query),"Adding a query that already exists"),this.saveQueryData(t),this.targetCount+=1,We.resolve()},e.prototype.updateQueryData=function(e,t){return v(this.queries.has(t.query),"Updating a non-existent query"),this.saveQueryData(t),We.resolve()},e.prototype.removeQueryData=function(e,t){return v(this.targetCount>0,"Removing a target from an empty cache"),v(this.queries.has(t.query),"Removing a non-existent target from the cache"),this.queries.delete(t.query),this.references.removeReferencesForId(t.targetId),this.targetCount-=1,We.resolve()},e.prototype.removeTargets=function(e,t,n){var r=this,i=0,o=[];return this.queries.forEach((function(a,s){s.sequenceNumber<=t&&null===n.get(s.targetId)&&(r.queries.delete(a),o.push(r.removeMatchingKeysForTargetId(e,s.targetId)),i++)})),We.waitFor(o).next((function(){return i}))},e.prototype.getQueryCount=function(e){return We.resolve(this.targetCount)},e.prototype.getQueryData=function(e,t){var n=this.queries.get(t)||null;return We.resolve(n)},e.prototype.getQueryDataForTarget=function(e,t){return g("Not yet implemented.")},e.prototype.addMatchingKeys=function(e,t,n){this.references.addReferences(t,n);var r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((function(t){i.push(r.addReference(e,t))})),We.waitFor(i)},e.prototype.removeMatchingKeys=function(e,t,n){this.references.removeReferences(t,n);var r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((function(t){i.push(r.removeReference(e,t))})),We.waitFor(i)},e.prototype.removeMatchingKeysForTargetId=function(e,t){return this.references.removeReferencesForId(t),We.resolve()},e.prototype.getMatchingKeysForTargetId=function(e,t){var n=this.references.referencesForId(t);return We.resolve(n)},e.prototype.containsKey=function(e,t){return We.resolve(this.references.containsKey(t))},e}();var $n=function(){function e(e,t){this.indexManager=e,this.sizer=t,this.docs=new Ie(de.comparator),this.size=0}return e.prototype.addEntry=function(e,t,n){v(!n.isEqual(Ee.MIN),"Cannot add a document with a read time of zero");var r=t.key,i=this.docs.get(r),o=i?i.size:0,a=this.sizer(t);return this.docs=this.docs.insert(r,{maybeDocument:t,size:a,readTime:n}),this.size+=a-o,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())},e.prototype.removeEntry=function(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)},e.prototype.getEntry=function(e,t){var n=this.docs.get(t);return We.resolve(n?n.maybeDocument:null)},e.prototype.getEntries=function(e,t){var n=this,r=Me();return t.forEach((function(e){var t=n.docs.get(e);r=r.insert(e,t?t.maybeDocument:null)})),We.resolve(r)},e.prototype.getDocumentsMatchingQuery=function(e,t,n){v(!t.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");for(var r=Oe(),i=new de(t.path.child("")),o=this.docs.getIteratorFrom(i);o.hasNext();){var a=o.getNext(),s=a.key,u=a.value,c=u.maybeDocument,h=u.readTime;if(!t.path.isPrefixOf(s.path))break;
1h.compareTo(n)<=0||c instanceof Qt&&t.matches(c)&&(r=r.insert(c.key,c))}return We.resolve(r)},e.prototype.forEachDocumentKey=function(e,t){return We.forEach(this.docs,(function(e){return t(e)}))},e.prototype.getNewDocumentChanges=function(e,t){throw new Error("getNewDocumentChanges() is not supported with MemoryPersistence")},e.prototype.newChangeBuffer=function(t){return new e.RemoteDocumentChangeBuffer(this)},e.prototype.getSize=function(e){return We.resolve(this.size)},e.RemoteDocumentChangeBuffer=function(e){function t(t){var n=e.call(this)||this;return n.documentCache=t,n}return a.__extends(t,e),t.prototype.applyChanges=function(e){var t=this,n=[];return this.changes.forEach((function(r,i){i?n.push(t.documentCache.addEntry(e,i,t.readTime)):t.documentCache.removeEntry(r)})),We.waitFor(n)},t.prototype.getFromCache=function(e,t){return this.documentCache.getEntry(e,t)},t.prototype.getAllFromCache=function(e,t){return this.documentCache.getEntries(e,t)},t}(zt),e}(),er=function(){function e(e,t){var n=this;this.clientId=e,this.mutationQueues={},this.listenSequence=new se(0),this._started=!1,this._started=!0,this.referenceDelegate=t(this),this.queryCache=new Zn(this);this.indexManager=new Zt,this.remoteDocumentCache=new $n(this.indexManager,(function(e){return n.referenceDelegate.documentSize(e)}))}return e.createLruPersistence=function(t,n,r){return new e(t,(function(e){return new rr(e,new Dn(n),r)}))},e.createEagerPersistence=function(t){return new e(t,(function(e){return new nr(e)}))},e.prototype.shutdown=function(){return this._started=!1,Promise.resolve()},Object.defineProperty(e.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),e.prototype.getActiveClients=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){return[2,[this.clientId]]}))}))},e.prototype.setPrimaryStateListener=function(e){return e(!0)},e.prototype.setDatabaseDeletedListener=function(){},e.prototype.setNetworkEnabled=function(e){},e.prototype.getIndexManager=function(){return this.indexManager},e.prototype.getMutationQueue=function(e){var t=this.mutationQueues[e.toKey()];return t||(t=new Xn(this.indexManager,this.referenceDelegate),this.mutationQueues[e.toKey()]=t),t},e.prototype.getQueryCache=function(){return this.queryCache},e.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},e.prototype.runTransaction=function(e,t,n){var r=this;p("MemoryPersistence","Starting transaction:",e);var i=new tr(this.listenSequence.next());return this.referenceDelegate.onTransactionStarted(),n(i).next((function(e){return r.referenceDelegate.onTransactionCommitted(i).next((function(){return e}))})).toPromise().then((function(e){return i.raiseOnCommittedEvent(),e}))},e.prototype.mutationQueuesContainKey=function(e,t){return We.or(function(e){var t=[];return _(e,(function(e,n){return t.push(n)})),t}(this.mutationQueues).map((function(n){return function(){return n.containsKey(e,t)}})))},e}(),tr=function(e){function t(t){var n=e.call(this)||this;return n.currentSequenceNumber=t,n}return a.__extends(t,e),t}(Ln),nr=function(){function e(e){this.persistence=e,this.inMemoryPins=null,this._orphanedDocuments=null}return Object.defineProperty(e.prototype,"orphanedDocuments",{get:function(){if(this._orphanedDocuments)return this._orphanedDocuments;throw g("orphanedDocuments is only valid during a transaction.")},enumerable:!0,configurable:!0}),e.prototype.setInMemoryPins=function(e){this.inMemoryPins=e},e.prototype.addReference=function(e,t){return this.orphanedDocuments.delete(t),We.resolve()},e.prototype.removeReference=function(e,t){return this.orphanedDocuments.add(t),We.resolve()},e.prototype.removeMutationReference=function(e,t){return this.orphanedDocuments.add(t),We.resolve()},e.prototype.removeTarget=function(e,t){var n=this,r=this.persistence.getQueryCache();return r.getMatchingKeysForTargetId(e,t.targetId).next((function(e){e.forEach((function(e){return n.orphanedDocuments.add(e)}))})).next((function(){return r.removeQueryData(e,t)}))},e.prototype.onTransactionStarted=function(){this._orphanedDocuments=new Set},e.prototype.onTransactionCommitted=function(e){var t=this,n=this.persistence.getRemoteDocumentCache().newChangeBuffer();return We.forEach(this.orphanedDocuments,(function(r){return t.isReferenced(e,r).next((function(e){e||n.removeEntry(r)}))}
1)).next((function(){return t._orphanedDocuments=null,n.apply(e)}))},e.prototype.updateLimboDocument=function(e,t){var n=this;return this.isReferenced(e,t).next((function(e){e?n.orphanedDocuments.delete(t):n.orphanedDocuments.add(t)}))},e.prototype.documentSize=function(e){return 0},e.prototype.isReferenced=function(e,t){var n=this;return We.or([function(){return n.persistence.getQueryCache().containsKey(e,t)},function(){return n.persistence.mutationQueuesContainKey(e,t)},function(){return We.resolve(n.inMemoryPins.containsKey(t))}])},e}(),rr=function(){function e(e,t,n){this.persistence=e,this.serializer=t,this.inMemoryPins=null,this.orphanedSequenceNumbers=new Gt((function(e){return ve(e.path)})),this.garbageCollector=new Mn(this,n)}return e.prototype.onTransactionStarted=function(){},e.prototype.onTransactionCommitted=function(e){return We.resolve()},e.prototype.forEachTarget=function(e,t){return this.persistence.getQueryCache().forEachTarget(e,t)},e.prototype.getSequenceNumberCount=function(e){var t=this.orphanedDocumentCount(e);return this.persistence.getQueryCache().getTargetCount(e).next((function(e){return t.next((function(t){return e+t}))}))},e.prototype.orphanedDocumentCount=function(e){var t=0;return this.forEachOrphanedDocumentSequenceNumber(e,(function(e){t++})).next((function(){return t}))},e.prototype.forEachOrphanedDocumentSequenceNumber=function(e,t){var n=this;return We.forEach(this.orphanedSequenceNumbers,(function(r,i){return n.isPinned(e,r,i).next((function(e){return e?We.resolve():t(i)}))}))},e.prototype.setInMemoryPins=function(e){this.inMemoryPins=e},e.prototype.removeTargets=function(e,t,n){return this.persistence.getQueryCache().removeTargets(e,t,n)},e.prototype.removeOrphanedDocuments=function(e,t){var n=this,r=0,i=this.persistence.getRemoteDocumentCache(),o=i.newChangeBuffer();return i.forEachDocumentKey(e,(function(i){return n.isPinned(e,i,t).next((function(e){e||(r++,o.removeEntry(i))}))})).next((function(){return o.apply(e)})).next((function(){return r}))},e.prototype.removeMutationReference=function(e,t){return this.orphanedSequenceNumbers.set(t,e.currentSequenceNumber),We.resolve()},e.prototype.removeTarget=function(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getQueryCache().updateQueryData(e,n)},e.prototype.addReference=function(e,t){return this.orphanedSequenceNumbers.set(t,e.currentSequenceNumber),We.resolve()},e.prototype.removeReference=function(e,t){return this.orphanedSequenceNumbers.set(t,e.currentSequenceNumber),We.resolve()},e.prototype.updateLimboDocument=function(e,t){return this.orphanedSequenceNumbers.set(t,e.currentSequenceNumber),We.resolve()},e.prototype.documentSize=function(e){var t,n=this.serializer.toDbRemoteDocument(e,e.version);if(n.document)t=n.document;else if(n.unknownDocument)t=n.unknownDocument;else{if(!n.noDocument)throw g("Unknown remote document type");t=n.noDocument}return JSON.stringify(t).length},e.prototype.isPinned=function(e,t,n){var r=this;return We.or([function(){return r.persistence.mutationQueuesContainKey(e,t)},function(){return We.resolve(r.inMemoryPins.containsKey(t))},function(){return r.persistence.getQueryCache().containsKey(e,t)},function(){var e=r.orphanedSequenceNumbers.get(t);return We.resolve(void 0!==e&&e>n)}])},e.prototype.getCacheSize=function(e){return this.persistence.getRemoteDocumentCache().getSize(e)},e}(),ir=function(){function e(){}return e.prototype.setLocalDocumentsView=function(e){this.localDocumentsView=e},e.prototype.getDocumentsMatchingQuery=function(e,t,n,r){return v(void 0!==this.localDocumentsView,"setLocalDocumentsView() not called"),this.localDocumentsView.getDocumentsMatchingQuery(e,t,Ee.MIN)},e}(),or=Number,ar=or.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),sr=or.MAX_SAFE_INTEGER||Math.pow(2,53)-1,ur=or.isInteger||function(e){return"number"===typeof e&&isFinite(e)&&Math.floor(e)===e};function cr(e){return null===e||void 0===e}function hr(e){return ur(e)&&e<=sr&&e>=ar}var lr,fr=function(){function e(e,t,n,r,i){void 0===n&&(n=1e3),void 0===r&&(r=1.5),void 0===i&&(i=6e4),this.queue=e,this.timerId=t,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=i,this.currentBaseMs=0,this.timerPromise=null,this.lastAttemptTime=Date.now(),this.reset()}return e.prototype.reset=function(){this.currentBaseMs=0},e.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},e.prototype.backoffAndRun=function(e){var t=this;this.cancel();
1var n=Math.floor(this.currentBaseMs+this.jitterDelayMs()),r=Math.max(0,Date.now()-this.lastAttemptTime),i=Math.max(0,n-r);this.currentBaseMs>0&&p("ExponentialBackoff","Backing off for "+i+" ms (base delay: "+this.currentBaseMs+" ms, delay with jitter: "+n+" ms, last attempt: "+r+" ms ago)"),this.timerPromise=this.queue.enqueueAfterDelay(this.timerId,i,(function(){return t.lastAttemptTime=Date.now(),e()})),this.currentBaseMs*=this.backoffFactor,this.currentBaseMs<this.initialDelayMs&&(this.currentBaseMs=this.initialDelayMs),this.currentBaseMs>this.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},e.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},e.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},e}(),dr="PersistentStream";!function(e){e[e.Initial=0]="Initial",e[e.Starting=1]="Starting",e[e.Open=2]="Open",e[e.Error=3]="Error",e[e.Backoff=4]="Backoff"}(lr||(lr={}));var pr,mr,yr=function(){function e(e,t,n,r,i,o){this.queue=e,this.idleTimerId=n,this.connection=r,this.credentialsProvider=i,this.listener=o,this.state=lr.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new fr(e,t)}return e.prototype.isStarted=function(){return this.state===lr.Starting||this.state===lr.Open||this.state===lr.Backoff},e.prototype.isOpen=function(){return this.state===lr.Open},e.prototype.start=function(){this.state!==lr.Error?(v(this.state===lr.Initial,"Already started"),this.auth()):this.performBackoff()},e.prototype.stop=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.isStarted()?[4,this.close(lr.Initial)]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}}
1))}))},e.prototype.inhibitBackoff=function(){v(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=lr.Initial,this.backoff.reset()},e.prototype.markIdle=function(){var e=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,(function(){return e.handleIdleCloseTimer()})))},e.prototype.sendRequest=function(e){this.cancelIdleCheck(),this.stream.send(e)},e.prototype.handleIdleCloseTimer=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){return this.isOpen()?[2,this.close(lr.Initial)]:[2]}))}))},e.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},e.prototype.close=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(n){switch(n.label){case 0:return v(this.isStarted(),"Only started streams should be closed."),v(e===lr.Error||cr(t),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,e!==lr.Error?this.backoff.reset():t&&t.code===S.RESOURCE_EXHAUSTED?(m(t.toString()),m("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):t&&t.code===S.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=e,[4,this.listener.onClose(t)];case 1:return n.sent(),[2]}}))}))},e.prototype.tearDown=function(){},e.prototype.auth=function(){var e=this;v(this.state===lr.Initial,"Must be in initial state to auth"),this.state=lr.Starting;var t=this.getCloseGuardedDispatcher(this.closeCount),n=this.closeCount;this.credentialsProvider.getToken().then((function(t){e.closeCount===n&&e.startStream(t)}),(function(n){t((function(){var t=new T(S.UNKNOWN,"Fetching auth token failed: "+n.message);return e.handleStreamClose(t)}))}))},e.prototype.startStream=function(e){var t=this;v(this.state===lr.Starting,"Trying to start stream in a non-starting state");var n=this.getCloseGuardedDispatcher(this.closeCount);this.stream=this.startRpc(e),this.stream.onOpen((function(){n((function(){return v(t.state===lr.Starting,"Expected stream to be in state Starting, but was "+t.state),t.state=lr.Open,t.listener.onOpen()}))})),this.stream.onClose((function(e){n((function(){return t.handleStreamClose(e)}))})),this.stream.onMessage((function(e){n((function(){return t.onMessage(e)}))}))},e.prototype.performBackoff=function(){var e=this;v(this.state===lr.Error,"Should only perform backoff when in Error state"),this.state=lr.Backoff,this.backoff.backoffAndRun((function(){return a.__awaiter(e,void 0,void 0,(function(){return a.__generator(this,(function(e){return v(this.state===lr.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=lr.Initial,this.start(),v(this.isStarted(),"PersistentStream should have started"),[2]}))}))}))},e.prototype.handleStreamClose=function(e){return v(this.isStarted(),"Can't handle server close on non-started stream"),p(dr,"close with error: "+e),this.stream=null,this.close(lr.Error,e)},e.prototype.getCloseGuardedDispatcher=function(e){var t=this;return function(n){t.queue.enqueueAndForget((function(){return t.closeCount===e?n():(p(dr,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())}))}},e}(),gr=function(e){function t(t,n,r,i,o){var a=e.call(this,t,te.ListenStreamConnectionBackoff,te.ListenStreamIdle,n,r,o)||this;return a.serializer=i,a}return a.__extends(t,e),t.prototype.startRpc=function(e){return this.connection.openStream("Listen",e)},t.prototype.onMessage=function(e){this.backoff.reset();var t=this.serializer.fromWatchChange(e),n=this.serializer.versionFromListenResponse(e);return this.listener.onWatchChange(t,n)},t.prototype.watch=function(e){var t={};t.database=this.serializer.encodedDatabaseId,t.addTarget=this.serializer.toTarget(e);var n=this.serializer.toListenRequestLabels(e);n&&(t.labels=n),this.sendRequest(t)},t.prototype.unwatch=function(e){var t={};t.database=this.serializer.encodedDatabaseId,t.removeTarget=e,this.sendRequest(t)},t}(yr),vr=function(e){function t(t,n,r,i,o){var a=e.call(this,t,te.WriteStreamConnectionBackoff,te.WriteStreamIdle,n,r,o)||this;
1return a.serializer=i,a.handshakeComplete_=!1,a.lastStreamToken=b(),a}return a.__extends(t,e),Object.defineProperty(t.prototype,"handshakeComplete",{get:function(){return this.handshakeComplete_},enumerable:!0,configurable:!0}),t.prototype.start=function(){this.handshakeComplete_=!1,e.prototype.start.call(this)},t.prototype.tearDown=function(){this.handshakeComplete_&&this.writeMutations([])},t.prototype.startRpc=function(e){return this.connection.openStream("Write",e)},t.prototype.onMessage=function(e){if(v(!!e.streamToken,"Got a write response without a stream token"),this.lastStreamToken=e.streamToken,this.handshakeComplete_){this.backoff.reset();var t=this.serializer.fromWriteResults(e.writeResults,e.commitTime),n=this.serializer.fromVersion(e.commitTime);return this.listener.onMutationResult(n,t)}return v(!e.writeResults||0===e.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},t.prototype.writeHandshake=function(){v(this.isOpen(),"Writing handshake requires an opened stream"),v(!this.handshakeComplete_,"Handshake already completed");var e={};e.database=this.serializer.encodedDatabaseId,this.sendRequest(e)},t.prototype.writeMutations=function(e){var t=this;v(this.isOpen(),"Writing mutations requires an opened stream"),v(this.handshakeComplete_,"Handshake must be complete before writing mutations"),v(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:e.map((function(e){return t.serializer.toMutation(e)}))};this.sendRequest(n)},t}(yr),wr=function(){function e(e,t,n,r){this.queue=e,this.connection=t,this.credentials=n,this.serializer=r}return e.prototype.newPersistentWriteStream=function(e){return new vr(this.queue,this.connection,this.credentials,this.serializer,e)},e.prototype.newPersistentWatchStream=function(e){return new gr(this.queue,this.connection,this.credentials,this.serializer,e)},e.prototype.commit=function(e){var t=this,n={database:this.serializer.encodedDatabaseId,writes:e.map((function(e){return t.serializer.toMutation(e)}))};return this.invokeRPC("Commit",n).then((function(e){return t.serializer.fromWriteResults(e.writeResults,e.commitTime)}))},e.prototype.lookup=function(e){var t=this,n={database:this.serializer.encodedDatabaseId,documents:e.map((function(e){return t.serializer.toName(e)}))};return this.invokeStreamingRPC("BatchGetDocuments",n).then((function(n){var r=Re();n.forEach((function(e){var n=t.serializer.fromMaybeDocument(e);r=r.insert(n.key,n)}));var i=[];return e.forEach((function(e){var t=r.get(e);v(!!t,"Missing entity in write response for "+e),i.push(t)})),i}))},e.prototype.invokeRPC=function(e,t){var n=this;return this.credentials.getToken().then((function(r){return n.connection.invokeRPC(e,t,r)})).catch((function(e){throw e.code===S.UNAUTHENTICATED&&n.credentials.invalidateToken(),e}))},e.prototype.invokeStreamingRPC=function(e,t){var n=this;return this.credentials.getToken().then((function(r){return n.connection.invokeStreamingRPC(e,t,r)})).catch((function(e){throw e.code===S.UNAUTHENTICATED&&n.credentials.invalidateToken(),e}))},e}(),br=function(){function e(e){this.datastore=e,this.readVersions=xe(),this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}return e.prototype.lookup=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n=this;return a.__generator(this,(function(r){switch(r.label){case 0:if(this.ensureCommitNotCalled(),this.mutations.length>0)throw new T(S.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");return[4,this.datastore.lookup(e)];case 1:return(t=r.sent()).forEach((function(e){e instanceof Kt||e instanceof Qt?n.recordVersion(e):g("Document in a transaction was a "+e.constructor.name)})),[2,t]}}))}))},e.prototype.set=function(e,t){this.write(t.toMutations(e,this.precondition(e))),this.writtenDocs.add(e)},e.prototype.update=function(e,t){try{this.write(t.toMutations(e,this.preconditionForUpdate(e)))}catch(n){this.lastWriteError=n}this.writtenDocs.add(e)}
1,e.prototype.delete=function(e){this.write([new It(e,this.precondition(e))]),this.writtenDocs.add(e)},e.prototype.commit=function(){return a.__awaiter(this,void 0,void 0,(function(){var e;return a.__generator(this,(function(t){switch(t.label){case 0:if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;if(e=this.readVersions,this.mutations.forEach((function(t){e=e.remove(t.key)})),!e.isEmpty())throw new T(S.INVALID_ARGUMENT,"Every document read in a transaction must also be written.");return[4,this.datastore.commit(this.mutations)];case 1:return t.sent(),this.committed=!0,[2]}}))}))},e.prototype.recordVersion=function(e){var t;if(e instanceof Qt)t=e.version;else{if(!(e instanceof Kt))throw g("Document in a transaction was a "+e.constructor.name);t=Ee.forDeletedDoc()}var n=this.readVersions.get(e.key);if(null!==n){if(!t.isEqual(n))throw new T(S.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(e.key,t)},e.prototype.precondition=function(e){var t=this.readVersions.get(e);return!this.writtenDocs.has(e)&&t?wt.updateTime(t):wt.NONE},e.prototype.preconditionForUpdate=function(e){var t=this.readVersions.get(e);if(!this.writtenDocs.has(e)&&t){if(t.isEqual(Ee.forDeletedDoc()))throw new T(S.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return wt.updateTime(t)}return wt.exists(!0)},e.prototype.write=function(e){this.ensureCommitNotCalled(),this.mutations=this.mutations.concat(e)},e.prototype.ensureCommitNotCalled=function(){v(!this.committed,"A transaction object cannot be used after its update callback has been invoked.")},e}();!function(e){e[e.Unknown=0]="Unknown",e[e.Online=1]="Online",e[e.Offline=2]="Offline"}(pr||(pr={})),function(e){e[e.RemoteStore=0]="RemoteStore",e[e.SharedClientState=1]="SharedClientState"}(mr||(mr={}));var Sr,Tr=function(){function e(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state=pr.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}return e.prototype.handleWatchStreamStart=function(){var e=this;0===this.watchStreamFailures&&(this.setAndBroadcast(pr.Unknown),v(null===this.onlineStateTimer,"onlineStateTimer shouldn't be started yet"),this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(te.OnlineStateTimeout,1e4,(function(){return e.onlineStateTimer=null,v(e.state===pr.Unknown,"Timer should be canceled if we transitioned to a different state."),e.logClientOfflineWarningIfNecessary("Backend didn't respond within 10 seconds."),e.setAndBroadcast(pr.Offline),Promise.resolve()})))},e.prototype.handleWatchStreamFailure=function(e){this.state===pr.Online?(this.setAndBroadcast(pr.Unknown),v(0===this.watchStreamFailures,"watchStreamFailures must be 0"),v(null===this.onlineStateTimer,"onlineStateTimer must be null")):(this.watchStreamFailures++,this.watchStreamFailures>=1&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary("Connection failed 1 times. Most recent error: "+e.toString()),this.setAndBroadcast(pr.Offline)))},e.prototype.set=function(e){this.clearOnlineStateTimer(),this.watchStreamFailures=0,e===pr.Online&&(this.shouldWarnClientIsOffline=!1),this.setAndBroadcast(e)},e.prototype.setAndBroadcast=function(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))},e.prototype.logClientOfflineWarningIfNecessary=function(e){var t="Could not reach Cloud Firestore backend. "+e+"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.";this.shouldWarnClientIsOffline?(m(t),this.shouldWarnClientIsOffline=!1):p("OnlineStateTracker",t)},e.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},e}();function Er(e){switch(e){case S.OK:return g("Treated status OK as error");case S.CANCELLED:case S.UNKNOWN:case S.DEADLINE_EXCEEDED:case S.RESOURCE_EXHAUSTED:case S.INTERNAL:case S.UNAVAILABLE:case S.UNAUTHENTICATED:return!1;case S.INVALID_ARGUMENT:case S.NOT_FOUND:case S.ALREADY_EXISTS:case S.PERMISSION_DENIED:case S.FAILED_PRECONDITION:case S.ABORTED:case S.OUT_OF_RANGE:case S.UNIMPLEMENT
1ED:case S.DATA_LOSS:return!0;default:return g("Unknown status code: "+e)}}function Ir(e){if(void 0===e)return m("GRPC error has no .code"),S.UNKNOWN;switch(e){case Sr.OK:return S.OK;case Sr.CANCELLED:return S.CANCELLED;case Sr.UNKNOWN:return S.UNKNOWN;case Sr.DEADLINE_EXCEEDED:return S.DEADLINE_EXCEEDED;case Sr.RESOURCE_EXHAUSTED:return S.RESOURCE_EXHAUSTED;case Sr.INTERNAL:return S.INTERNAL;case Sr.UNAVAILABLE:return S.UNAVAILABLE;case Sr.UNAUTHENTICATED:return S.UNAUTHENTICATED;case Sr.INVALID_ARGUMENT:return S.INVALID_ARGUMENT;case Sr.NOT_FOUND:return S.NOT_FOUND;case Sr.ALREADY_EXISTS:return S.ALREADY_EXISTS;case Sr.PERMISSION_DENIED:return S.PERMISSION_DENIED;case Sr.FAILED_PRECONDITION:return S.FAILED_PRECONDITION;case Sr.ABORTED:return S.ABORTED;case Sr.OUT_OF_RANGE:return S.OUT_OF_RANGE;case Sr.UNIMPLEMENTED:return S.UNIMPLEMENTED;case Sr.DATA_LOSS:return S.DATA_LOSS;default:return g("Unknown status code: "+e)}}function Cr(e){if(void 0===e)return Sr.OK;switch(e){case S.OK:return Sr.OK;case S.CANCELLED:return Sr.CANCELLED;case S.UNKNOWN:return Sr.UNKNOWN;case S.DEADLINE_EXCEEDED:return Sr.DEADLINE_EXCEEDED;case S.RESOURCE_EXHAUSTED:return Sr.RESOURCE_EXHAUSTED;case S.INTERNAL:return Sr.INTERNAL;case S.UNAVAILABLE:return Sr.UNAVAILABLE;case S.UNAUTHENTICATED:return Sr.UNAUTHENTICATED;case S.INVALID_ARGUMENT:return Sr.INVALID_ARGUMENT;case S.NOT_FOUND:return Sr.NOT_FOUND;case S.ALREADY_EXISTS:return Sr.ALREADY_EXISTS;case S.PERMISSION_DENIED:return Sr.PERMISSION_DENIED;case S.FAILED_PRECONDITION:return Sr.FAILED_PRECONDITION;case S.ABORTED:return Sr.ABORTED;case S.OUT_OF_RANGE:return Sr.OUT_OF_RANGE;case S.UNIMPLEMENTED:return Sr.UNIMPLEMENTED;case S.DATA_LOSS:return Sr.DATA_LOSS;default:return g("Unknown status code: "+e)}}!function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS"}(Sr||(Sr={}));var Dr,_r,Nr=function(){function e(e){this.comparator=e?function(t,n){return e(t,n)||de.comparator(t.key,n.key)}:function(e,t){return de.comparator(e.key,t.key)},this.keyedMap=Oe(),this.sortedSet=new Ie(this.comparator)}return e.emptySet=function(t){return new e(t.comparator)},e.prototype.has=function(e){return null!=this.keyedMap.get(e)},e.prototype.get=function(e){return this.keyedMap.get(e)},e.prototype.first=function(){return this.sortedSet.minKey()},e.prototype.last=function(){return this.sortedSet.maxKey()},e.prototype.isEmpty=function(){return this.sortedSet.isEmpty()},e.prototype.indexOf=function(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1},Object.defineProperty(e.prototype,"size",{get:function(){return this.sortedSet.size},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e){this.sortedSet.inorderTraversal((function(t,n){return e(t),!1}))},e.prototype.add=function(e){var t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))},e.prototype.delete=function(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this},e.prototype.isEqual=function(t){if(!(t instanceof e))return!1;if(this.size!==t.size)return!1;for(var n=this.sortedSet.getIterator(),r=t.sortedSet.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(!i.isEqual(o))return!1}return!0},e.prototype.toString=function(){var e=[];return this.forEach((function(t){e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n  "+e.join("  \n")+"\n)"},e.prototype.copy=function(t,n){var r=new e;return r.comparator=this.comparator,r.keyedMap=t,r.sortedSet=n,r},e}();!function(e){e[e.Added=0]="Added",e[e.Removed=1]="Removed",e[e.Modified=2]="Modified",e[e.Metadata=3]="Metadata"}(Dr||(Dr={})),function(e){e[e.Local=0]="Local",e[e.Synced=1]="Synced"}(_r||(_r={}));var Ar,kr=function(){function e(){this.changeMap=new Ie(de.comparator)}return e.prototype.track=function(e){var t=e.doc.key,n=this.changeMap.get(t);n?e.type!==Dr.Added&&n.type===Dr.Metadata?this.changeMap=this.changeMap.insert(t,e):e.type===Dr.Metadata&&n.type!==Dr.Removed?this.changeMap=this.changeMap.insert(t,{type:n.type,doc:e.doc}):e.type===Dr.Modified&&n.type===Dr.Modified?this.changeMap=this.changeMap.insert(t,{type:Dr.Modified,doc:e.doc}):e.type===Dr.Modified&&n.type===Dr.Added?this.changeMap=this.changeMap.insert(t,{type:Dr.Added,doc:e.doc}):e.type===Dr.Removed&&n.type===Dr.Added?this.changeMap=this.changeMap.remove(t):e.type===Dr.Removed&&n.type===Dr.Modified?this.changeMap=this.changeMap.insert(t,{type:Dr.Removed,doc:n.doc}):e.type===Dr.Added&&n.type===Dr.Removed?this.changeMap=this.changeMap.insert(t,{type:Dr.Modified,doc:e.doc}):g("unsupported combination of changes: "+JSON.stringify(e)+" after "+JSON.stringify(n)):this.changeMap=this.changeMap.insert(t,e)},e.prototype.getChanges=function(){var e=[];return this.changeMap.inorderTraversal((function(t,n){e.push(n)})),e},e}(),Rr=function(){function e(e,t,n,r,i,o,a,s){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=o,this.syncStateChanged=a,this.excludesMetadataChanges=s}return e.fromInitialDocuments=function(t,n,r,i){var o=[];
1return n.forEach((function(e){o.push({type:Dr.Added,doc:e})})),new e(t,n,Nr.emptySet(n),o,r,i,!0,!1)},Object.defineProperty(e.prototype,"hasPendingWrites",{get:function(){return!this.mutatedKeys.isEmpty()},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(e){if(this.fromCache!==e.fromCache||this.syncStateChanged!==e.syncStateChanged||!this.mutatedKeys.isEqual(e.mutatedKeys)||!this.query.isEqual(e.query)||!this.docs.isEqual(e.docs)||!this.oldDocs.isEqual(e.oldDocs))return!1;var t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(var r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0},e}(),Mr=function(){function e(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}return e.createSynthesizedRemoteEventForCurrentChange=function(t,n){var r,i=((r={})[t]=Lr.createSynthesizedTargetChangeForCurrentChange(t,n),r);return new e(Ee.MIN,i,Be(),Re(),Ve())},e}(),Lr=function(){function e(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}return e.createSynthesizedTargetChangeForCurrentChange=function(t,n){return new e(b(),n,Ve(),Ve(),Ve())},e}(),Or=function(e,t,n,r){this.updatedTargetIds=e,this.removedTargetIds=t,this.key=n,this.newDoc=r},Pr=function(e,t){this.targetId=e,this.existenceFilter=t};!function(e){e[e.NoChange=0]="NoChange",e[e.Added=1]="Added",e[e.Removed=2]="Removed",e[e.Current=3]="Current",e[e.Reset=4]="Reset"}(Ar||(Ar={}));var xr=function(e,t,n,r){void 0===n&&(n=b()),void 0===r&&(r=null),this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r},qr=function(){function e(){this.pendingResponses=0,this.documentChanges=Br(),this._resumeToken=b(),this._current=!1,this._hasPendingChanges=!0}return Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"resumeToken",{get:function(){return this._resumeToken},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isPending",{get:function(){return 0!==this.pendingResponses},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasPendingChanges",{get:function(){return this._hasPendingChanges},enumerable:!0,configurable:!0}),e.prototype.updateResumeToken=function(e){e.length>0&&(this._hasPendingChanges=!0,this._resumeToken=e)},e.prototype.toTargetChange=function(){var e=Ve(),t=Ve(),n=Ve();
1return this.documentChanges.forEach((function(r,i){switch(i){case Dr.Added:e=e.add(r);break;case Dr.Modified:t=t.add(r);break;case Dr.Removed:n=n.add(r);break;default:g("Encountered invalid change type: "+i)}})),new Lr(this._resumeToken,this._current,e,t,n)},e.prototype.clearPendingChanges=function(){this._hasPendingChanges=!1,this.documentChanges=Br()},e.prototype.addDocumentChange=function(e,t){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.insert(e,t)},e.prototype.removeDocumentChange=function(e){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.remove(e)},e.prototype.recordPendingTargetRequest=function(){this.pendingResponses+=1},e.prototype.recordTargetResponse=function(){this.pendingResponses-=1},e.prototype.markCurrent=function(){this._hasPendingChanges=!0,this._current=!0},e}(),Vr=function(){function e(e){this.metadataProvider=e,this.targetStates={},this.pendingDocumentUpdates=Re(),this.pendingDocumentTargetMapping=Fr(),this.pendingTargetResets=new Ne(J)}return e.prototype.handleDocumentChange=function(e){for(var t=0,n=e.updatedTargetIds;t<n.length;t++){var r=n[t];e.newDoc instanceof Qt?this.addDocumentToTarget(r,e.newDoc):e.newDoc instanceof Kt&&this.removeDocumentFromTarget(r,e.key,e.newDoc)}for(var i=0,o=e.removedTargetIds;i<o.length;i++){r=o[i];this.removeDocumentFromTarget(r,e.key,e.newDoc)}},e.prototype.handleTargetChange=function(e){var t=this;this.forEachTarget(e,(function(n){var r=t.ensureTargetState(n);switch(e.state){case Ar.NoChange:t.isActiveTarget(n)&&r.updateResumeToken(e.resumeToken);break;case Ar.Added:r.recordTargetResponse(),r.isPending||r.clearPendingChanges(),r.updateResumeToken(e.resumeToken);break;case Ar.Removed:r.recordTargetResponse(),r.isPending||t.removeTarget(n),v(!e.cause,"WatchChangeAggregator does not handle errored targets");break;case Ar.Current:t.isActiveTarget(n)&&(r.markCurrent(),r.updateResumeToken(e.resumeToken));break;case Ar.Reset:t.isActiveTarget(n)&&(t.resetTarget(n),r.updateResumeToken(e.resumeToken));break;default:g("Unknown target watch change state: "+e.state)}}))},e.prototype.forEachTarget=function(e,t){e.targetIds.length>0?e.targetIds.forEach(t):D(this.targetStates,t)},e.prototype.handleExistenceFilter=function(e){var t=e.targetId,n=e.existenceFilter.count,r=this.queryDataForActiveTarget(t);if(r){var i=r.query;if(i.isDocumentQuery())if(0===n){var o=new de(i.path);this.removeDocumentFromTarget(t,o,new Kt(o,Ee.forDeletedDoc()))}else v(1===n,"Single document existence filter with count: "+n);else this.getCurrentDocumentCountForTarget(t)!==n&&(this.resetTarget(t),this.pendingTargetResets=this.pendingTargetResets.add(t))}},e.prototype.createRemoteEvent=function(e){var t=this,n={};D(this.targetStates,(function(r,i){var o=t.queryDataForActiveTarget(r);if(o){if(i.current&&o.query.isDocumentQuery()){var a=new de(o.query.path);null!==t.pendingDocumentUpdates.get(a)||t.targetContainsDocument(r,a)||t.removeDocumentFromTarget(r,a,new Kt(a,e))}i.hasPendingChanges&&(n[r]=i.toTargetChange(),i.clearPendingChanges())}}));var r=Ve();this.pendingDocumentTargetMapping.forEach((function(e,n){var i=!0;n.forEachWhile((function(e){var n=t.queryDataForActiveTarget(e);return!n||n.purpose===vn.LimboResolution||(i=!1,!1)})),i&&(r=r.add(e))}));var i=new Mr(e,n,this.pendingTargetResets,this.pendingDocumentUpdates,r);return this.pendingDocumentUpdates=Re(),this.pendingDocumentTargetMapping=Fr(),this.pendingTargetResets=new Ne(J),i},e.prototype.addDocumentToTarget=function(e,t){if(this.isActiveTarget(e)){var n=this.targetContainsDocument(e,t.key)?Dr.Modified:Dr.Added;this.ensureTargetState(e).addDocumentChange(t.key,n),this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(t.key,t),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(t.key,this.ensureDocumentTargetMapping(t.key).add(e))}},e.prototype.removeDocumentFromTarget=function(e,t,n){if(this.isActiveTarget(e)){var r=this.ensureTargetState(e);this.targetContainsDocument(e,t)?r.addDocumentChange(t,Dr.Removed):r.removeDocumentChange(t),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(t,this.ensureDocumentTargetMapping(t).delete(e)),n&&(this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(t,n))}},e.prototype.removeTarget=function(e){delete this.targetStates[e]},e.prototype.getCurrentDocumentCountForTarget=function(e){var t=this.ensureTargetState(e).toTargetChange();return this.metadataProvider.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size},e.prototype.recordPendingTargetRequest=function(e){this.ensureTargetState(e).recordPendingTargetRequest
1()},e.prototype.ensureTargetState=function(e){return this.targetStates[e]||(this.targetStates[e]=new qr),this.targetStates[e]},e.prototype.ensureDocumentTargetMapping=function(e){var t=this.pendingDocumentTargetMapping.get(e);return t||(t=new Ne(J),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e,t)),t},e.prototype.isActiveTarget=function(e){var t=null!==this.queryDataForActiveTarget(e);return t||p("WatchChangeAggregator","Detected inactive target",e),t},e.prototype.queryDataForActiveTarget=function(e){var t=this.targetStates[e];return t&&t.isPending?null:this.metadataProvider.getQueryDataForTarget(e)},e.prototype.resetTarget=function(e){var t=this;v(!this.targetStates[e].isPending,"Should only reset active targets"),this.targetStates[e]=new qr,this.metadataProvider.getRemoteKeysForTarget(e).forEach((function(n){t.removeDocumentFromTarget(e,n,null)}))},e.prototype.targetContainsDocument=function(e,t){return this.metadataProvider.getRemoteKeysForTarget(e).has(t)},e}();function Fr(){return new Ie(de.comparator)}function Br(){return new Ie(de.comparator)}var Ur="RemoteStore",Qr=function(){function e(e,t,n,r,i){var o=this;this.localStore=e,this.datastore=t,this.writePipeline=[],this.listenTargets={},this.watchChangeAggregator=null,this.networkEnabled=!1,this.isPrimary=!1,this.connectivityMonitor=i,this.connectivityMonitor.addCallback((function(e){n.enqueueAndForget((function(){return a.__awaiter(o,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.canUseNetwork()?(p(Ur,"Restarting streams for network reachability change."),[4,this.restartNetwork()]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}}
1))}))}))})),this.onlineStateTracker=new Tr(n,r),this.watchStream=this.datastore.newPersistentWatchStream({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)}),this.writeStream=this.datastore.newPersistentWriteStream({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})}return e.prototype.start=function(){return this.enableNetwork()},e.prototype.enableNetwork=function(){return a.__awaiter(this,void 0,void 0,(function(){var e;return a.__generator(this,(function(t){switch(t.label){case 0:return this.networkEnabled=!0,this.canUseNetwork()?(e=this.writeStream,[4,this.localStore.getLastStreamToken()]):[3,3];case 1:return e.lastStreamToken=t.sent(),this.shouldStartWatchStream()?this.startWatchStream():this.onlineStateTracker.set(pr.Unknown),[4,this.fillWritePipeline()];case 2:t.sent(),t.label=3;case 3:return[2]}}
1))}))},e.prototype.disableNetwork=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return e.sent(),this.onlineStateTracker.set(pr.Offline),[2]}}))}))},e.prototype.disableNetworkInternal=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return[4,this.writeStream.stop()];case 1:return e.sent(),[4,this.watchStream.stop()];case 2:return e.sent(),this.writePipeline.length>0&&(p(Ur,"Stopping write stream with "+this.writePipeline.length+" pending writes"),this.writePipeline=[]),this.cleanUpWatchStreamState(),[2]}}))}))},e.prototype.shutdown=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return p(Ur,"RemoteStore shutting down."),this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return e.sent(),this.connectivityMonitor.shutdown(),this.onlineStateTracker.set(pr.Unknown),[2]}}))}))},e.prototype.listen=function(e){v(!I(this.listenTargets,e.targetId),"listen called with duplicate targetId!"),this.listenTargets[e.targetId]=e,this.shouldStartWatchStream()?this.startWatchStream():this.watchStream.isOpen()&&this.sendWatchRequest(e)},e.prototype.unlisten=function(e){v(I(this.listenTargets,e),"unlisten called without assigned target ID!"),delete this.listenTargets[e],this.watchStream.isOpen()&&this.sendUnwatchRequest(e),N(this.listenTargets)&&(this.watchStream.isOpen()?this.watchStream.markIdle():this.canUseNetwork()&&this.onlineStateTracker.set(pr.Unknown))},e.prototype.getQueryDataForTarget=function(e){return this.listenTargets[e]||null},e.prototype.getRemoteKeysForTarget=function(e){return this.syncEngine.getRemoteKeysForTarget(e)},e.prototype.sendWatchRequest=function(e){this.watchChangeAggregator.recordPendingTargetRequest(e.targetId),this.watchStream.watch(e)},e.prototype.sendUnwatchRequest=function(e){this.watchChangeAggregator.recordPendingTargetRequest(e),this.watchStream.unwatch(e)},e.prototype.startWatchStream=function(){v(this.shouldStartWatchStream(),"startWatchStream() called when shouldStartWatchStream() is false."),this.watchChangeAggregator=new Vr(this),this.watchStream.start(),this.onlineStateTracker.handleWatchStreamStart()},e.prototype.shouldStartWatchStream=function(){return this.canUseNetwork()&&!this.watchStream.isStarted()&&!N(this.listenTargets)},e.prototype.canUseNetwork=function(){return this.isPrimary&&this.networkEnabled},e.prototype.cleanUpWatchStreamState=function(){this.watchChangeAggregator=null},e.prototype.onWatchStreamOpen=function(){return a.__awaiter(this,void 0,void 0,(function(){var e=this;return a.__generator(this,(function(t){return D(this.listenTargets,(function(t,n){e.sendWatchRequest(n)})),[2]}))}))},e.prototype.onWatchStreamClose=function(e){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(t){return void 0===e&&v(!this.shouldStartWatchStream(),"Watch stream was stopped gracefully while still needed."),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.onlineStateTracker.handleWatchStreamFailure(e),this.startWatchStream()):this.onlineStateTracker.set(pr.Unknown),[2]}))}
1))},e.prototype.onWatchStreamChange=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){var n;return a.__generator(this,(function(r){switch(r.label){case 0:return this.onlineStateTracker.set(pr.Online),e instanceof xr&&e.state===Ar.Removed&&e.cause?[2,this.handleTargetError(e)]:(e instanceof Or?this.watchChangeAggregator.handleDocumentChange(e):e instanceof Pr?this.watchChangeAggregator.handleExistenceFilter(e):(v(e instanceof xr,"Expected watchChange to be an instance of WatchTargetChange"),this.watchChangeAggregator.handleTargetChange(e)),t.isEqual(Ee.MIN)?[3,3]:[4,this.localStore.getLastRemoteSnapshotVersion()]);case 1:return n=r.sent(),t.compareTo(n)>=0?[4,this.raiseWatchSnapshot(t)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},e.prototype.raiseWatchSnapshot=function(e){var t=this;v(!e.isEqual(Ee.MIN),"Can't raise event for unknown SnapshotVersion");var n=this.watchChangeAggregator.createRemoteEvent(e);return D(n.targetChanges,(function(n,r){if(r.resumeToken.length>0){var i=t.listenTargets[n];i&&(t.listenTargets[n]=i.withResumeToken(r.resumeToken,e))}})),n.targetMismatches.forEach((function(e){var n=t.listenTargets[e];if(n){t.listenTargets[e]=n.withResumeToken(b(),n.snapshotVersion),t.sendUnwatchRequest(e);var r=new Cn(n.query,e,vn.ExistenceFilterMismatch,n.sequenceNumber);t.sendWatchRequest(r)}})),this.syncEngine.applyRemoteEvent(n)},e.prototype.handleTargetError=function(e){var t=this;v(!!e.cause,"Handling target error without a cause");var n=e.cause,r=Promise.resolve();return e.targetIds.forEach((function(e){r=r.then((function(){return a.__awaiter(t,void 0,void 0,(function(){return a.__generator(this,(function(t){return I(this.listenTargets,e)?(delete this.listenTargets[e],this.watchChangeAggregator.removeTarget(e),[2,this.syncEngine.rejectListen(e,n)]):[2]}))}))}))})),r},e.prototype.fillWritePipeline=function(){return a.__awaiter(this,void 0,void 0,(function(){var e,t;return a.__generator(this,(function(n){switch(n.label){case 0:return this.canAddToWritePipeline()?(e=this.writePipeline.length>0?this.writePipeline[this.writePipeline.length-1].batchId:Ue,[4,this.localStore.nextMutationBatch(e)]):[3,4];case 1:return null!==(t=n.sent())?[3,2]:(0===this.writePipeline.length&&this.writeStream.markIdle(),[3,4]);case 2:return this.addToWritePipeline(t),[4,this.fillWritePipeline()];case 3:n.sent(),n.label=4;case 4:return this.shouldStartWriteStream()&&this.startWriteStream(),[2]}}))}))},e.prototype.canAddToWritePipeline=function(){return this.canUseNetwork()&&this.writePipeline.length<10},e.prototype.outstandingWrites=function(){return this.writePipeline.length},e.prototype.addToWritePipeline=function(e){v(this.canAddToWritePipeline(),"addToWritePipeline called when pipeline is full"),this.writePipeline.push(e),this.writeStream.isOpen()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(e.mutations)},e.prototype.shouldStartWriteStream=function(){return this.canUseNetwork()&&!this.writeStream.isStarted()&&this.writePipeline.length>0},e.prototype.startWriteStream=function(){v(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},e.prototype.onWriteStreamOpen=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){return this.writeStream.writeHandshake(),[2]}))}))},e.prototype.onWriteHandshakeComplete=function(){var e=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then((function(){for(var t=0,n=e.writePipeline;t<n.length;t++){var r=n[t];e.writeStream.writeMutations(r.mutations)}})).catch(Un)},e.prototype.onMutationResult=function(e,t){var n=this;v(this.writePipeline.length>0,"Got result for empty write pipeline");var r=this.writePipeline.shift(),i=Ke.from(r,e,t,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then((function(){return n.fillWritePipeline()}))},e.prototype.onWriteStreamClose=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t=this;return a.__generator(this,(function(n){return void 0===e&&v(!this.shouldStartWriteStream(),"Write stream was stopped gracefully while still needed."),e&&this.writePipeline.length>0?(void 0,[2,(this.writeStream.handshakeComplete?this.handleWriteError(e):this.handleHandshakeError(e)).then((function(){t.shouldStartWriteStream()&&t.startWriteStream()}))]):[2]}))}))},e.prototype.handleHandshakeError=function(e){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(t){return Er(e.code)?(p(Ur,"RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=b(),[2,this.localStore.setLastStreamToken(b()).catch(Un)]):[2]}))}))},e.prototype.handleWriteError=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n=this;return a.__generator(this,(function(r){return Er(i=e.code)&&i!==S.ABORTED?(t=this.writePipeline.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(t.batchId,e).then((function(){return n.fillWritePipeline()}))]):[2];var i}))}))},e.prototype.createTransaction=function(){return new br(this.datastore)},e.prototype.restartNetwork=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return e.sent(),this.onlineStateTracker.set(pr.Unknown),[4,this.enableNetwork()];case 2:return e.sent(),[2]}}))}))},e.prototype.handleCredentialChange=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.canUseNetwork()?(p(Ur,"RemoteStore restarting streams for new credential"),[4,this.restartNetwork()]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}}
1))}))},e.prototype.applyPrimaryState=function(e){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(t){switch(t.label){case 0:return this.isPrimary=e,e&&this.networkEnabled?[4,this.enableNetwork()]:[3,2];case 1:return t.sent(),[3,4];case 2:return e?[3,4]:[4,this.disableNetworkInternal()];case 3:t.sent(),this.onlineStateTracker.set(pr.Unknown),t.label=4;case 4:return[2]}}))}))},e}(),Kr=function(){function e(e,t){if(k("GeoPoint",arguments,2),O("GeoPoint","number",1,e),O("GeoPoint","number",2,t),!isFinite(e)||e<-90||e>90)throw new T(S.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new T(S.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}return Object.defineProperty(e.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"longitude",{get:function(){return this._long},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(e){return this._lat===e._lat&&this._long===e._long},e.prototype._compareTo=function(e){return J(this._lat,e._lat)||J(this._long,e._long)},e}(),Wr=function(){function e(e,t,n,r,i,o,a){void 0===t&&(t=null),void 0===n&&(n=[]),void 0===r&&(r=[]),void 0===i&&(i=null),void 0===o&&(o=null),void 0===a&&(a=null),this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.startAt=o,this.endAt=a,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}return e.atPath=function(t){return new e(t)},Object.defineProperty(e.prototype,"orderBy",{get:function(){if(null===this.memoizedOrderBy){var e=this.getInequalityFilterField(),t=this.getFirstOrderByField();if(null!==e&&null===t)e.isKeyField()?this.memoizedOrderBy=[ni]:this.memoizedOrderBy=[new ti(e),ni];else{v(null===e||null!==t&&e.isEqual(t),"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:$r.ASCENDING;this.memoizedOrderBy.push(a===$r.ASCENDING?ni:ri)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),e.prototype.addFilter=function(t){v(null==this.getInequalityFilterField()||!(t instanceof jr)||!t.isInequality()||t.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),v(!this.isDocumentQuery(),"No filtering allowed for document query");var n=this.filters.concat([t]);return new e(this.path,this.collectionGroup,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},e.prototype.addOrderBy=function(t){v(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([t]);return new e(this.path,this.collectionGroup,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},e.prototype.withLimit=function(t){return new e(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),t,this.startAt,this.endAt)},e.prototype.withStartAt=function(t){return new e(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,t,this.endAt)},e.prototype.withEndAt=function(t){return new e(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,t)},e.prototype.asCollectionQueryAtPath=function(t){return new e(t,null,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,this.endAt)},e.prototype.matchesAllDocuments=function(){return 0===this.filters.length&&null===this.limit&&null==this.startAt&&null==this.endAt&&(0===this.explicitOrderBy.length||1===this.explicitOrderBy.length&&this.explicitOrderBy[0].field.isKeyField())},e.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var e=this.path.canonicalString();this.isCollectionGroupQuery()&&(e+="|cg:"+this.collectionGroup),e+="|f:";for(var t=0,n=this.filters;t<n.length;t++){e+=n[t].canonicalId(),e+=","}e+="|ob:";for(var r=0,i=this.orderBy;r<i.length;r++){e+=i[r].canonicalId(),e+=","}cr(this.limit)||(e+="|l:",e+=this.limit),this.startAt&&(e+="|lb:",e+=this.startAt.canonicalId()),this.endAt&&(e+="|ub:",e+=this.endAt.canonicalId()),this.memoizedCanonicalId=e}return this.memoizedCanonicalId}
1,e.prototype.toString=function(){var e="Query("+this.path.canonicalString();return this.isCollectionGroupQuery()&&(e+=" collectionGroup="+this.collectionGroup),this.filters.length>0&&(e+=", filters: ["+this.filters.join(", ")+"]"),cr(this.limit)||(e+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(e+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(e+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(e+=", endAt: "+this.endAt.canonicalId()),e+")"},e.prototype.isEqual=function(e){if(this.limit!==e.limit)return!1;if(this.orderBy.length!==e.orderBy.length)return!1;for(var t=0;t<this.orderBy.length;t++)if(!this.orderBy[t].isEqual(e.orderBy[t]))return!1;if(this.filters.length!==e.filters.length)return!1;for(t=0;t<this.filters.length;t++)if(!this.filters[t].isEqual(e.filters[t]))return!1;return this.collectionGroup===e.collectionGroup&&(!!this.path.isEqual(e.path)&&(!!(null!==this.startAt?this.startAt.isEqual(e.startAt):null===e.startAt)&&(null!==this.endAt?this.endAt.isEqual(e.endAt):null===e.endAt)))},e.prototype.docComparator=function(e,t){for(var n=!1,r=0,i=this.orderBy;r<i.length;r++){var o=i[r],a=o.compare(e,t);if(0!==a)return a;n=n||o.field.isKeyField()}return v(n,"orderBy used that doesn't compare on key field"),0},e.prototype.matches=function(e){return this.matchesPathAndCollectionGroup(e)&&this.matchesOrderBy(e)&&this.matchesFilters(e)&&this.matchesBounds(e)},e.prototype.hasLimit=function(){return!cr(this.limit)},e.prototype.getFirstOrderByField=function(){return this.explicitOrderBy.length>0?this.explicitOrderBy[0].field:null},e.prototype.getInequalityFilterField=function(){for(var e=0,t=this.filters;e<t.length;e++){var n=t[e];if(n instanceof jr&&n.isInequality())return n.field}return null},e.prototype.findFilterOperator=function(e){for(var t=0,n=this.filters;t<n.length;t++){var r=n[t];if(r instanceof jr&&e.indexOf(r.op)>=0)return r.op}return null},e.prototype.isDocumentQuery=function(){return de.isDocumentKey(this.path)&&null===this.collectionGroup&&0===this.filters.length},e.prototype.isCollectionGroupQuery=function(){return null!==this.collectionGroup},e.prototype.matchesPathAndCollectionGroup=function(e){var t=e.key.path;return null!==this.collectionGroup?e.key.hasCollectionId(this.collectionGroup)&&this.path.isPrefixOf(t):de.isDocumentKey(this.path)?this.path.isEqual(t):this.path.isImmediateParentOf(t)},e.prototype.matchesOrderBy=function(e){for(var t=0,n=this.explicitOrderBy;t<n.length;t++){var r=n[t];if(!r.field.isKeyField()&&null===e.field(r.field))return!1}return!0},e.prototype.matchesFilters=function(e){for(var t=0,n=this.filters;t<n.length;t++){if(!n[t].matches(e))return!1}return!0},e.prototype.matchesBounds=function(e){return!(this.startAt&&!this.startAt.sortsBeforeDocument(this.orderBy,e))&&(!this.endAt||!this.endAt.sortsBeforeDocument(this.orderBy,e))},e.prototype.assertValidBound=function(e){v(e.position.length<=this.orderBy.length,"Bound is longer than orderBy")},e}(),Gr=function(){},zr=function(){function e(e){this.name=e}return e.fromString=function(t){switch(t){case"<":return e.LESS_THAN;case"<=":return e.LESS_THAN_OR_EQUAL;case"==":return e.EQUAL;case">=":return e.GREATER_THAN_OR_EQUAL;case">":return e.GREATER_THAN;case"array-contains":return e.ARRAY_CONTAINS;case"in":return e.IN;case"array-contains-any":return e.ARRAY_CONTAINS_ANY;default:return g("Unknown FieldFilter operator: "+t)}},e.prototype.toString=function(){return this.name},e.prototype.isEqual=function(e){return this.name===e.name},e.LESS_THAN=new e("<"),e.LESS_THAN_OR_EQUAL=new e("<="),e.EQUAL=new e("=="),e.GREATER_THAN=new e(">"),e.GREATER_THAN_OR_EQUAL=new e(">="),e.ARRAY_CONTAINS=new e("array-contains"),e.IN=new e("in"),e.ARRAY_CONTAINS_ANY=new e("array-contains-any"),e}(),jr=function(e){function t(t,n,r){var i=e.call(this)||this;return i.field=t,i.op=n,i.value=r,i}return a.__extends(t,e),t.create=function(e,n,r){if(e.isKeyField())return n===zr.IN?(v(r instanceof Bt,"Comparing on key with IN, but filter value not an ArrayValue"),v(r.internalValue.every((function(e){return e instanceof qt})),"Comparing on key with IN, but an array value was not a RefValue"),new Yr(e,r)):(v(r instanceof qt,"Comparing on key, but filter value not a RefValue"),v(n!==zr.ARRAY_CONTAINS&&n!==zr.ARRAY_CONTAINS_ANY,"'"+n.toString()+"' queries don't make sense on document keys."),new Hr(e,n,r));if(r.isEqual(_t.INSTANCE)){if(n!==zr.EQUAL)throw new T(S.INVALID_ARGUMENT,"Invalid query. Null supports only equality comparisons.");return new t(e,n,r)}if(r.isEqual(Mt.NAN)){if(n!==zr.EQUAL)throw new T(S.INVALID_ARGUMENT,"Invalid query. NaN supports only equality comparisons.");return new t(e,n,r)}return n===zr.ARRAY_CONTAINS?new Jr(e,r):n===zr.IN?(v(r instanceof Bt,"IN filter has invali
1d value: "+r.toString()),new Xr(e,r)):n===zr.ARRAY_CONTAINS_ANY?(v(r instanceof Bt,"ARRAY_CONTAINS_ANY filter has invalid value: "+r.toString()),new Zr(e,r)):new t(e,n,r)},t.prototype.matches=function(e){var t=e.field(this.field);return null!==t&&this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},t.prototype.matchesComparison=function(e){switch(this.op){case zr.LESS_THAN:return e<0;case zr.LESS_THAN_OR_EQUAL:return e<=0;case zr.EQUAL:return 0===e;case zr.GREATER_THAN:return e>0;case zr.GREATER_THAN_OR_EQUAL:return e>=0;default:return g("Unknown FieldFilter operator: "+this.op)}},t.prototype.isInequality=function(){return[zr.LESS_THAN,zr.LESS_THAN_OR_EQUAL,zr.GREATER_THAN,zr.GREATER_THAN_OR_EQUAL].indexOf(this.op)>=0},t.prototype.canonicalId=function(){return this.field.canonicalString()+this.op.toString()+this.value.toString()},t.prototype.isEqual=function(e){return e instanceof t&&(this.op.isEqual(e.op)&&this.field.isEqual(e.field)&&this.value.isEqual(e.value))},t.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},t}(Gr),Hr=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a.__extends(t,e),t.prototype.matches=function(e){var t=this.value,n=de.comparator(e.key,t.key);return this.matchesComparison(n)},t}(jr),Yr=function(e){function t(t,n){var r=e.call(this,t,zr.IN,n)||this;return r.value=n,r}return a.__extends(t,e),t.prototype.matches=function(e){return this.value.internalValue.some((function(t){return e.key.isEqual(t.key)}))},t}(jr),Jr=function(e){function t(t,n){return e.call(this,t,zr.ARRAY_CONTAINS,n)||this}return a.__extends(t,e),t.prototype.matches=function(e){var t=e.field(this.field);return t instanceof Bt&&t.contains(this.value)},t}(jr),Xr=function(e){function t(t,n){var r=e.call(this,t,zr.IN,n)||this;return r.value=n,r}return a.__extends(t,e),t.prototype.matches=function(e){var t=this.value,n=e.field(this.field);return null!==n&&t.contains(n)},t}(jr),Zr=function(e){function t(t,n){var r=e.call(this,t,zr.ARRAY_CONTAINS_ANY,n)||this;return r.value=n,r}return a.__extends(t,e),t.prototype.matches=function(e){var t=this,n=e.field(this.field);return n instanceof Bt&&n.internalValue.some((function(e){return t.value.contains(e)}))},t}(jr),$r=function(){function e(e){this.name=e}return e.prototype.toString=function(){return this.name},e.ASCENDING=new e("asc"),e.DESCENDING=new e("desc"),e}(),ei=function(){function e(e,t){this.position=e,this.before=t}return e.prototype.canonicalId=function(){for(var e=this.before?"b:":"a:",t=0,n=this.position;t<n.length;t++){e+=n[t].toString()}return e},e.prototype.sortsBeforeDocument=function(e,t){v(this.position.length<=e.length,"Bound has more components than query's orderBy");for(var n=0,r=0;r<this.position.length;r++){var i=e[r],o=this.position[r];if(i.field.isKeyField())v(o instanceof qt,"Bound has a non-key value where the key path is being used."),n=de.comparator(o.key,t.key);else{var a=t.field(i.field);v(null!==a,"Field should exist since document matched the orderBy already."),n=o.compareTo(a)}if(i.dir===$r.DESCENDING&&(n*=-1),0!==n)break}return this.before?n<=0:n<0},e.prototype.isEqual=function(e){if(null===e)return!1;if(this.before!==e.before||this.position.length!==e.position.length)return!1;for(var t=0;t<this.position.length;t++){var n=this.position[t],r=e.position[t];if(!n.isEqual(r))return!1}return!0},e}(),ti=function(){function e(e,t){this.field=e,void 0===t&&(t=$r.ASCENDING),this.dir=t,this.isKeyOrderBy=e.isKeyField()}return e.prototype.compare=function(e,t){var n=this.isKeyOrderBy?Qt.compareByKey(e,t):Qt.compareByField(this.field,e,t);switch(this.dir){case $r.ASCENDING:return n;case $r.DESCENDING:return-1*n;default:return g("Unknown direction: "+this.dir)}},e.prototype.canonicalId=function(){return this.field.canonicalString()+this.dir.toString()},e.prototype.toString=function(){return this.field.canonicalString()+" ("+this.dir+")"},e.prototype.isEqual=function(e){return this.dir===e.dir&&this.field.isEqual(e.field)},e}(),ni=new ti(fe.keyField(),$r.ASCENDING),ri=new ti(fe.keyField(),$r.DESCENDING),ii=function(){function e(){}return e.prototype.applyToLocalView=function(e,t){return new Pt(t,e)},e.prototype.applyToRemoteDocument=function(e,t){return t},e.prototype.computeBaseValue=function(e){return null},e.prototype.isEqual=function(t){return t instanceof e},e.instance=new e,e}(),oi=function(){function e(e){this.elements=e}return e.prototype.applyToLocalView=function(e,t){return this.apply(e)},e.prototype.applyToRemoteDocument=function(e,t){return this.apply(e)},e.prototype.apply=function(e){for(var t=ui(e),n=function(e){t.find((function(t){return t.isEqual(e)}
1))||t.push(e)},r=0,i=this.elements;r<i.length;r++){n(i[r])}return new Bt(t)},e.prototype.computeBaseValue=function(e){return null},e.prototype.isEqual=function(t){return t instanceof e&&X(t.elements,this.elements)},e}(),ai=function(){function e(e){this.elements=e}return e.prototype.applyToLocalView=function(e,t){return this.apply(e)},e.prototype.applyToRemoteDocument=function(e,t){return this.apply(e)},e.prototype.apply=function(e){for(var t=ui(e),n=function(e){t=t.filter((function(t){return!t.isEqual(e)}))},r=0,i=this.elements;r<i.length;r++){n(i[r])}return new Bt(t)},e.prototype.computeBaseValue=function(e){return null},e.prototype.isEqual=function(t){return t instanceof e&&X(t.elements,this.elements)},e}(),si=function(){function e(e){this.operand=e}return e.prototype.applyToLocalView=function(e,t){var n=this.computeBaseValue(e);if(n instanceof Rt&&this.operand instanceof Rt){var r=n.internalValue+this.operand.internalValue;return new Rt(r)}r=n.internalValue+this.operand.internalValue;return new Mt(r)},e.prototype.applyToRemoteDocument=function(e,t){return v(null!==t,"Didn't receive transformResult for NUMERIC_ADD transform"),t},e.prototype.computeBaseValue=function(e){return e instanceof At?e:new Rt(0)},e.prototype.isEqual=function(t){return t instanceof e&&this.operand.isEqual(t.operand)},e}();function ui(e){return e instanceof Bt?e.internalValue.slice():[]}var ci=function(){function e(e){this.count=e}return e.prototype.isEqual=function(e){return e&&e.count===this.count},e}(),hi=function(){var e={};return e[$r.ASCENDING.name]="ASCENDING",e[$r.DESCENDING.name]="DESCENDING",e}(),li=function(){var e={};return e[zr.LESS_THAN.name]="LESS_THAN",e[zr.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",e[zr.GREATER_THAN.name]="GREATER_THAN",e[zr.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",e[zr.EQUAL.name]="EQUAL",e[zr.ARRAY_CONTAINS.name]="ARRAY_CONTAINS",e[zr.IN.name]="IN",e[zr.ARRAY_CONTAINS_ANY.name]="ARRAY_CONTAINS_ANY",e}(),fi=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function di(e,t){v(!cr(e),t+" is missing")}function pi(e){return"number"===typeof e?e:"string"===typeof e?Number(e):g("can't parse "+e)}var mi=function(){function e(e,t){this.databaseId=e,this.options=t}return e.prototype.emptyByteString=function(){return this.options.useProto3Json?"":new Uint8Array(0)},e.prototype.unsafeCastProtoByteString=function(e){return e},e.prototype.fromRpcStatus=function(e){var t=void 0===e.code?S.UNKNOWN:Ir(e.code);return new T(t,e.message||"")},e.prototype.toInt32Value=function(e){return this.options.useProto3Json||cr(e)?e:{value:e}},e.prototype.fromInt32Value=function(e){var t;return cr(t="object"===typeof e?e.value:e)?null:t},e.prototype.toTimestamp=function(e){return this.options.useProto3Json?new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")+"."+("000000000"+e.nanoseconds).slice(-9)+"Z":{seconds:""+e.seconds,nanos:e.nanoseconds}},e.prototype.fromTimestamp=function(e){if("string"===typeof e)return this.fromIso8601String(e);v(!!e,"Cannot deserialize null or undefined timestamp.");var t=pi(e.seconds||"0"),n=e.nanos||0;return new Te(t,n)},e.prototype.fromIso8601String=function(e){var t=0,n=fi.exec(e);if(v(!!n,"invalid timestamp: "+e),n[1]){var r=n[1];r=(r+"000000000").substr(0,9),t=Number(r)}var i=new Date(e),o=Math.floor(i.getTime()/1e3);return new Te(o,t)},e.prototype.toBytes=function(e){return this.options.useProto3Json?e.toBase64():this.unsafeCastProtoByteString(e.toUint8Array())},e.prototype.fromBlob=function(e){return"string"===typeof e?(v(this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),ne.fromBase64String(e)):(v(!this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),ne.fromUint8Array(e))},e.prototype.toVersion=function(e){return this.toTimestamp(e.toTimestamp())},e.prototype.fromVersion=function(e){return v(!!e,"Trying to deserialize version that isn't set"),Ee.fromTimestamp(this.fromTimestamp(e))},e.prototype.toResourceName=function(e,t){return this.fullyQualifiedPrefixPath(e).child("documents").child(t).canonicalString()},e.prototype.fromResourceName=function(e){var t=he.fromString(e);return v(this.isValidResourceName(t),"Tried to deserialize invalid key "+t.toString()),t},e.prototype.toName=function(e){return this.toResourceName(this.databaseId,e.path)},e.prototype.fromName=function(e){var t=this.fromResourceName(e);return v(t.get(1)===this.databaseId.projectId,"Tried to deserialize key from different project: "+t.get(1)+" vs "+this.databaseId.projectId),v(!t.get(3)&&!this.databaseId.database||t.get(3)===this.databaseId.database,"Tried to deserialize key from different database: "+t.get(3)+" vs "+this.databaseId.database),new de(this.extractLocalPathFromResourceName(t))},e.prototype.toQueryPath=function(e){return this.toResourceName(this.databaseId,e)},e.prototype.fromQueryPath=function(e){var t=this.fromResourceName(e);return 4===t.length?he.EMPTY_PATH:this.extractLocalPathFromResourceName(t)},Object.defineProperty(e.prototype,"encodedDatabaseId",{get:function(){return new he(["projects",this.databaseId.projectId,"databases",this.databaseId.database]).canonicalString()},enumerable:!0,configurable:!0}),e.prototype.fullyQualifiedPrefixPath=function(e){return new he(["projects",e.projectId,"databases",e.database])},e.prototype.extractLocalPathFromResourceName=function(e){return v(e.length>4&&"documents"===e.get(4),"tried to deserialize invalid key "+e.toString()),e.popFirst(5)},e.prototype.isValidResourceName=function(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)},e.prototype.toValue=function(e){if(e instanceof _t)return{nullValue:"NULL_VALUE"};if(e instanceof Nt)return{booleanValue:e.value()};if(e instanceof Rt)return{integerValue:""+e.value()};if(e instanceof Mt){var t=e.value();if(this.options.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:e.value()}}return e instanceof Lt?{stringValue:e.value()}:e instanceof Ft?{mapValue:this.toMapValue(e)}:e instanceof Bt?{arrayValue:this.toArrayValue(e)}
1:e instanceof Ot?{timestampValue:this.toTimestamp(e.internalValue)}:e instanceof Vt?{geoPointValue:{latitude:e.value().latitude,longitude:e.value().longitude}}:e instanceof xt?{bytesValue:this.toBytes(e.value())}:e instanceof qt?{referenceValue:this.toResourceName(e.databaseId,e.key.path)}:g("Unknown FieldValue "+JSON.stringify(e))},e.prototype.fromValue=function(e){var t=this;if("nullValue"in e)return _t.INSTANCE;if("booleanValue"in e)return Nt.of(e.booleanValue);if("integerValue"in e)return new Rt(pi(e.integerValue));if("doubleValue"in e){if(this.options.useProto3Json){if("NaN"===e.doubleValue)return Mt.NAN;if("Infinity"===e.doubleValue)return Mt.POSITIVE_INFINITY;if("-Infinity"===e.doubleValue)return Mt.NEGATIVE_INFINITY}return new Mt(e.doubleValue)}if("stringValue"in e)return new Lt(e.stringValue);if("mapValue"in e)return this.fromFields(e.mapValue.fields||{});if("arrayValue"in e){di(e.arrayValue,"arrayValue");var n=e.arrayValue.values||[];return new Bt(n.map((function(e){return t.fromValue(e)})))}if("timestampValue"in e)return di(e.timestampValue,"timestampValue"),new Ot(this.fromTimestamp(e.timestampValue));if("geoPointValue"in e){di(e.geoPointValue,"geoPointValue");var r=e.geoPointValue.latitude||0,i=e.geoPointValue.longitude||0;return new Vt(new Kr(r,i))}if("bytesValue"in e){di(e.bytesValue,"bytesValue");var o=this.fromBlob(e.bytesValue);return new xt(o)}if("referenceValue"in e){di(e.referenceValue,"referenceValue");var a=this.fromResourceName(e.referenceValue),s=new ae(a.get(1),a.get(3)),u=new de(this.extractLocalPathFromResourceName(a));return new qt(s,u)}return g("Unknown Value proto "+JSON.stringify(e))},e.prototype.toMutationDocument=function(e,t){return{name:this.toName(e),fields:this.toFields(t)}},e.prototype.toDocument=function(e){return v(!e.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(e.key),fields:this.toFields(e.data()),updateTime:this.toTimestamp(e.version.toTimestamp())}},e.prototype.fromDocument=function(e,t){var n=this,r=this.fromName(e.name),i=this.fromVersion(e.updateTime);return new Qt(r,i,{hasCommittedMutations:!!t},void 0,e,(function(e){return n.fromValue(e)}))},e.prototype.toFields=function(e){var t=this,n={};return e.forEach((function(e,r){n[e]=t.toValue(r)})),n},e.prototype.fromFields=function(e){var t=this,n=e,r=Ft.EMPTY;return _(n,(function(e,n){r=r.set(new fe([e]),t.fromValue(n))})),r},e.prototype.toMapValue=function(e){return{fields:this.toFields(e)}},e.prototype.toArrayValue=function(e){var t=this,n=[];return e.forEach((function(e){n.push(t.toValue(e))})),{values:n}},e.prototype.fromFound=function(e){var t=this;v(!!e.found,"Tried to deserialize a found document from a missing document."),di(e.found.name,"doc.found.name"),di(e.found.updateTime,"doc.found.updateTime");var n=this.fromName(e.found.name),r=this.fromVersion(e.found.updateTime);return new Qt(n,r,{},void 0,e.found,(function(e){return t.fromValue(e)}))},e.prototype.fromMissing=function(e){v(!!e.missing,"Tried to deserialize a missing document from a found document."),v(!!e.readTime,"Tried to deserialize a missing document without a read time.");var t=this.fromName(e.missing),n=this.fromVersion(e.readTime);return new Kt(t,n)},e.prototype.fromMaybeDocument=function(e){return"found"in e?this.fromFound(e):"missing"in e?this.fromMissing(e):g("invalid batch get response: "+JSON.stringify(e))},e.prototype.toWatchTargetChangeState=function(e){switch(e){case Ar.Added:return"ADD";case Ar.Current:return"CURRENT";case Ar.NoChange:return"NO_CHANGE";case Ar.Removed:return"REMOVE";case Ar.Reset:return"RESET";default:return g("Unknown WatchTargetChangeState: "+e)}},e.prototype.toTestWatchChange=function(e){if(e instanceof Pr)return{filter:{count:e.existenceFilter.count,targetId:e.targetId}};if(e instanceof Or){if(e.newDoc instanceof Qt){var t=e.newDoc;return{documentChange:{document:{name:this.toName(t.key),fields:this.toFields(t.data()),updateTime:this.toVersion(t.version)},targetIds:e.updatedTargetIds,removedTargetIds:e.removedTargetIds}}}if(e.newDoc instanceof Kt){t=e.newDoc;return{documentDelete:{document:this.toName(t.key),readTime:this.toVersion(t.version),removedTargetIds:e.removedTargetIds}}}if(null===e.newDoc)return{documentRemove:{document:this.toName(e.key),removedTargetIds:e.removedTargetIds}}}if(e instanceof xr){var n=void 0;return e.cause&&(n={code:Cr(e.cause.code),message:e.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(e.state),targetIds:e.targetIds,resumeToken:this.unsafeCastProtoByteString(e.resumeToken),cause:n}}}
1return g("Unrecognized watch change: "+JSON.stringify(e))},e.prototype.fromWatchChange=function(e){var t,n=this;if("targetChange"in e){di(e.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(e.targetChange.targetChangeType||"NO_CHANGE"),i=e.targetChange.targetIds||[],o=e.targetChange.resumeToken||this.emptyByteString(),a=e.targetChange.cause,s=a&&this.fromRpcStatus(a);t=new xr(r,i,o,s||null)}else if("documentChange"in e){di(e.documentChange,"documentChange"),di(e.documentChange.document,"documentChange.name"),di(e.documentChange.document.name,"documentChange.document.name"),di(e.documentChange.document.updateTime,"documentChange.document.updateTime");var u=e.documentChange,c=this.fromName(u.document.name),h=this.fromVersion(u.document.updateTime),l=new Qt(c,h,{},void 0,u.document,(function(e){return n.fromValue(e)})),f=u.targetIds||[],d=u.removedTargetIds||[];t=new Or(f,d,l.key,l)}else if("documentDelete"in e){di(e.documentDelete,"documentDelete"),di(e.documentDelete.document,"documentDelete.document");var p=e.documentDelete;c=this.fromName(p.document),h=p.readTime?this.fromVersion(p.readTime):Ee.forDeletedDoc(),l=new Kt(c,h),d=p.removedTargetIds||[];t=new Or([],d,l.key,l)}else if("documentRemove"in e){di(e.documentRemove,"documentRemove"),di(e.documentRemove.document,"documentRemove");var m=e.documentRemove;c=this.fromName(m.document),d=m.removedTargetIds||[];t=new Or([],d,c,null)}else{if(!("filter"in e))return g("Unknown change type "+JSON.stringify(e));di(e.filter,"filter"),di(e.filter.targetId,"filter.targetId");var y=e.filter,v=y.count||0,w=new ci(v),b=y.targetId;t=new Pr(b,w)}return t},e.prototype.fromWatchTargetChangeState=function(e){return"NO_CHANGE"===e?Ar.NoChange:"ADD"===e?Ar.Added:"REMOVE"===e?Ar.Removed:"CURRENT"===e?Ar.Current:"RESET"===e?Ar.Reset:g("Got unexpected TargetChange.state: "+e)},e.prototype.versionFromListenResponse=function(e){if(!("targetChange"in e))return Ee.MIN;var t=e.targetChange;return t.targetIds&&t.targetIds.length?Ee.MIN:t.readTime?this.fromVersion(t.readTime):Ee.MIN},e.prototype.toMutation=function(e){var t,n=this;if(e instanceof St)t={update:this.toMutationDocument(e.key,e.value)};else if(e instanceof It)t={delete:this.toName(e.key)};else if(e instanceof Tt)t={update:this.toMutationDocument(e.key,e.data),updateMask:this.toDocumentMask(e.fieldMask)};else{if(!(e instanceof Et))return g("Unknown mutation type "+e.type);t={transform:{document:this.toName(e.key),fieldTransforms:e.fieldTransforms.map((function(e){return n.toFieldTransform(e)}))}}}return e.precondition.isNone||(t.currentDocument=this.toPrecondition(e.precondition)),t},e.prototype.fromMutation=function(e){var t=this,n=e.currentDocument?this.fromPrecondition(e.currentDocument):wt.NONE;if(e.update){di(e.update.name,"name");var r=this.fromName(e.update.name),i=this.fromFields(e.update.fields||{});if(e.updateMask){var o=this.fromDocumentMask(e.updateMask);return new Tt(r,i,o,n)}return new St(r,i,n)}if(e.delete){r=this.fromName(e.delete);return new It(r,n)}if(e.transform){r=this.fromName(e.transform.document);var a=e.transform.fieldTransforms.map((function(e){return t.fromFieldTransform(e)}));return v(!0===n.exists,'Transforms only support precondition "exists == true"'),new Et(r,a)}return g("unknown mutation proto: "+JSON.stringify(e))},e.prototype.toPrecondition=function(e){return v(!e.isNone,"Can't serialize an empty precondition"),void 0!==e.updateTime?{updateTime:this.toVersion(e.updateTime)}:void 0!==e.exists?{exists:e.exists}:g("Unknown precondition")},e.prototype.fromPrecondition=function(e){return void 0!==e.updateTime?wt.updateTime(this.fromVersion(e.updateTime)):void 0!==e.exists?wt.exists(e.exists):wt.NONE},e.prototype.fromWriteResult=function(e,t){var n=this,r=e.updateTime?this.fromVersion(e.updateTime):this.fromVersion(t);r.isEqual(Ee.MIN)&&(r=this.fromVersion(t));var i=null;return e.transformResults&&e.transformResults.length>0&&(i=e.transformResults.map((function(e){return n.fromValue(e)}))),new yt(r,i)},e.prototype.fromWriteResults=function(e,t){var n=this;return e&&e.length>0?(v(void 0!==t,"Received a write result without a commit time"),e.map((function(e){return n.fromWriteResult(e,t)}))):[]},e.prototype.toFieldTransform=function(e){var t=this,n=e.transform;if(n instanceof ii)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof oi)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:n.elements.map((function(e){return t.toValue(e)}))}};if(n instanceof ai)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:n.elements.map((function(e){return t.toValue(e)}))}};if(n instanceof si)return{fieldPath:e.field.canonicalString(),increment:this.toValue(n.operand)};throw g("Unknown transform: "+e.transform)},e.prototype.fromFieldTransform=function(e){var t=this,n=null;if("setToServerValue"in e)v("REQUEST_TIME"===e.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(e)),n=ii.instance;else if("appendMissingElements"in e){var r=e.appendMissingElements.values||[];n=new oi(r.map((function(e){return t.fromValue(e)})))}else if("removeAllFromArray"in e){r=e.removeAllFromArray.values||[];n=new ai(r.map((function(e){return t.fromValue(e)})))}else if("increment"in e){var i=this.fromValue(e.increment);v(i instanceof At,"NUMERIC_ADD transform requires a NumberValue"),n=new si(i)}else g("Unknown transform proto: "+JSON.stringify(e));var o=fe.fromServerFormat(e.fieldPath);return new mt(o,n)},e.prototype.toDocumentsTarget=function(e){return{documents:[this.toQueryPath(e.path)]}},e.prototype.fromDocumentsTarget=function(e){var t=e.documents.length;v(1===t,"DocumentsTarget contained other than 1 document: "+t);var n=e.documents[0];return Wr.atPath(this.fromQueryPath(n))},e.prototype.toQueryTarget=function(e){var t={structuredQuery:{}},n=e.path;null!==e.collectionGroup?(v(n.length%2===0,"Collection Group queries should be within a document path or root."),t.parent=this.toQueryPath(n),t.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(v(n.length%2!==0,"Document queries with filters are not supported."),t.parent=this.toQueryPath(n.popLast()),t.structuredQuery.from=[{collectionId:n.lastSegment()}]);var r=this.toFilter(e.filters);r&&(t.structuredQuery.where=r);var i=this.toOrder(e.orderBy);i&&(t.structuredQuery.orderBy=i);var o=this.toInt32Value(e.limit);return null!==o&&(t.structuredQuery.limit=o),e.startAt&&(t.structuredQuery.startAt=this.toCursor(e.startAt)),e.endAt&&(t.structuredQuery.endAt=this.toCursor(e.endAt)),t},e.prototype.fromQueryTarget=function(e){var t=this.fromQueryPath(e.parent),n=e.structuredQuery,r
1=n.from?n.from.length:0,i=null;if(r>0){v(1===r,"StructuredQuery.from with more than one collection is not supported.");var o=n.from[0];o.allDescendants?i=o.collectionId:t=t.child(o.collectionId)}var a=[];n.where&&(a=this.fromFilter(n.where));var s=[];n.orderBy&&(s=this.fromOrder(n.orderBy));var u=null;n.limit&&(u=this.fromInt32Value(n.limit));var c=null;n.startAt&&(c=this.fromCursor(n.startAt));var h=null;return n.endAt&&(h=this.fromCursor(n.endAt)),new Wr(t,i,s,a,u,c,h)},e.prototype.toListenRequestLabels=function(e){var t=this.toLabel(e.purpose);return null==t?null:{"goog-listen-tags":t}},e.prototype.toLabel=function(e){switch(e){case vn.Listen:return null;case vn.ExistenceFilterMismatch:return"existence-filter-mismatch";case vn.LimboResolution:return"limbo-document";default:return g("Unrecognized query purpose: "+e)}},e.prototype.toTarget=function(e){var t,n=e.query;return(t=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)}).targetId=e.targetId,e.resumeToken.length>0&&(t.resumeToken=this.unsafeCastProtoByteString(e.resumeToken)),t},e.prototype.toFilter=function(e){var t=this;if(0!==e.length){var n=e.map((function(e){return e instanceof jr?t.toUnaryOrFieldFilter(e):g("Unrecognized filter: "+JSON.stringify(e))}));return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},e.prototype.fromFilter=function(e){var t=this;return e?void 0!==e.unaryFilter?[this.fromUnaryFilter(e)]:void 0!==e.fieldFilter?[this.fromFieldFilter(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map((function(e){return t.fromFilter(e)})).reduce((function(e,t){return e.concat(t)})):g("Unknown filter: "+JSON.stringify(e)):[]},e.prototype.toOrder=function(e){var t=this;if(0!==e.length)return e.map((function(e){return t.toPropertyOrder(e)}))},e.prototype.fromOrder=function(e){var t=this;return e.map((function(e){return t.fromPropertyOrder(e)}))},e.prototype.toCursor=function(e){var t=this;return{before:e.before,values:e.position.map((function(e){return t.toValue(e)}))}},e.prototype.fromCursor=function(e){var t=this,n=!!e.before,r=e.values.map((function(e){return t.fromValue(e)}));return new ei(r,n)},e.prototype.toDirection=function(e){return hi[e.name]},e.prototype.fromDirection=function(e){switch(e){case"ASCENDING":return $r.ASCENDING;case"DESCENDING":return $r.DESCENDING;default:return}},e.prototype.toOperatorName=function(e){return li[e.name]},e.prototype.fromOperatorName=function(e){switch(e){case"EQUAL":return zr.EQUAL;case"GREATER_THAN":return zr.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return zr.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return zr.LESS_THAN;case"LESS_THAN_OR_EQUAL":return zr.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return zr.ARRAY_CONTAINS;case"IN":return zr.IN;case"ARRAY_CONTAINS_ANY":return zr.ARRAY_CONTAINS_ANY;case"OPERATOR_UNSPECIFIED":return g("Unspecified operator");default:return g("Unknown operator")}},e.prototype.toFieldPathReference=function(e){return{fieldPath:e.canonicalString()}},e.prototype.fromFieldPathReference=function(e){return fe.fromServerFormat(e.fieldPath)},e.prototype.toPropertyOrder=function(e){return{field:this.toFieldPathReference(e.field),direction:this.toDirection(e.dir)}},e.prototype.fromPropertyOrder=function(e){return new ti(this.fromFieldPathReference(e.field),this.fromDirection(e.direction))},e.prototype.fromFieldFilter=function(e){return jr.create(this.fromFieldPathReference(e.fieldFilter.field),this.fromOperatorName(e.fieldFilter.op),this.fromValue(e.fieldFilter.value))},e.prototype.toUnaryOrFieldFilter=function(e){if(e.op===zr.EQUAL){if(e.value.isEqual(Mt.NAN))return{unaryFilter:{field:this.toFieldPathReference(e.field),op:"IS_NAN"}};if(e.value.isEqual(_t.INSTANCE))return{unaryFilter:{field:this.toFieldPathReference(e.field),op:"IS_NULL"}}}return{fieldFilter:{field:this.toFieldPathReference(e.field),op:this.toOperatorName(e.op),value:this.toValue(e.value)}}},e.prototype.fromUnaryFilter=function(e){switch(e.unaryFilter.op){case"IS_NAN":var t=this.fromFieldPathReference(e.unaryFilter.field);return jr.create(t,zr.EQUAL,Mt.NAN);case"IS_NULL":var n=this.fromFieldPathReference(e.unaryFilter.field);return jr.create(n,zr.EQUAL,_t.INSTANCE);case"OPERATOR_UNSPECIFIED":return g("Unspecified filter");default:return g("Unknown filter")}},e.prototype.toDocumentMask=function(e){var t=[];return e.fields.forEach((function(e){return t.push(e.canonicalString())})),{fieldPaths:t}},e.prototype.fromDocumentMask=function(e){var t=(e.fieldPaths||[]).map((function(e){return fe.fromServerFormat(e)}));return pt.fromArray(t)},e}(),yi=function(){this.viewSnap=null,this.targetId=0,this.listeners=[]},gi=function(){function e(e){this.syncEngine=e,this.queries=new Gt((function(e){return e.canonicalId()})),this.onlineState=pr.Unknown,this.snapshotsInSyncListeners=new Set,this.syncEngine.subscribe(this)}return e.prototype.listen=function(e){var t=e.query,n=!1,r=this.queries.get(t);(r||(n=!0,r=new yi,this.queries.set(t,r)),r.listeners.push(e),v(!e.applyOnlineStateChange(this.onlineState),"applyOnlineStateChange() shouldn't raise an event for brand-new listeners."),r.viewSnap)&&(e.onViewSnapsh
1ot(r.viewSnap)&&this.raiseSnapshotsInSyncEvent());return n?this.syncEngine.listen(t).then((function(e){return r.targetId=e,e})):Promise.resolve(r.targetId)},e.prototype.unlisten=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n,r,i;return a.__generator(this,(function(o){return t=e.query,n=!1,(r=this.queries.get(t))&&(i=r.listeners.indexOf(e))>=0&&(r.listeners.splice(i,1),n=0===r.listeners.length),n?(this.queries.delete(t),[2,this.syncEngine.unlisten(t)]):[2]}))}))},e.prototype.onWatchChange=function(e){for(var t=!1,n=0,r=e;n<r.length;n++){var i=r[n],o=i.query,a=this.queries.get(o);if(a){for(var s=0,u=a.listeners;s<u.length;s++){u[s].onViewSnapshot(i)&&(t=!0)}a.viewSnap=i}}t&&this.raiseSnapshotsInSyncEvent()},e.prototype.onWatchError=function(e,t){var n=this.queries.get(e);if(n)for(var r=0,i=n.listeners;r<i.length;r++){i[r].onError(t)}this.queries.delete(e)},e.prototype.onOnlineStateChange=function(e){this.onlineState=e;var t=!1;this.queries.forEach((function(n,r){for(var i=0,o=r.listeners;i<o.length;i++){o[i].applyOnlineStateChange(e)&&(t=!0)}})),t&&this.raiseSnapshotsInSyncEvent()},e.prototype.addSnapshotsInSyncListener=function(e){this.snapshotsInSyncListeners.add(e),e.next()},e.prototype.removeSnapshotsInSyncListener=function(e){this.snapshotsInSyncListeners.delete(e)},e.prototype.raiseSnapshotsInSyncEvent=function(){this.snapshotsInSyncListeners.forEach((function(e){e.next()}))},e}(),vi=function(){function e(e,t,n){this.query=e,this.queryObserver=t,this.raisedInitialEvent=!1,this.snap=null,this.onlineState=pr.Unknown,this.options=n||{}}return e.prototype.onViewSnapshot=function(e){if(v(e.docChanges.length>0||e.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeMetadataChanges){for(var t=[],n=0,r=e.docChanges;n<r.length;n++){var i=r[n];i.type!==Dr.Metadata&&t.push(i)}e=new Rr(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}var o=!1;return this.raisedInitialEvent?this.shouldRaiseEvent(e)&&(this.queryObserver.next(e),o=!0):this.shouldRaiseInitialEvent(e,this.onlineState)&&(this.raiseInitialEvent(e),o=!0),this.snap=e,o},e.prototype.onError=function(e){this.queryObserver.error(e)},e.prototype.applyOnlineStateChange=function(e){this.onlineState=e;var t=!1;return this.snap&&!this.raisedInitialEvent&&this.shouldRaiseInitialEvent(this.snap,e)&&(this.raiseInitialEvent(this.snap),t=!0),t},e.prototype.shouldRaiseInitialEvent=function(e,t){if(v(!this.raisedInitialEvent,"Determining whether to raise first event but already had first event"),!e.fromCache)return!0;var n=t!==pr.Offline;return this.options.waitForSyncWhenOnline&&n?(v(e.fromCache,"Waiting for sync, but snapshot is not from cache"),!1):!e.docs.isEmpty()||t===pr.Offline},e.prototype.shouldRaiseEvent=function(e){if(e.docChanges.length>0)return!0;var t=this.snap&&this.snap.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges},e.prototype.raiseInitialEvent=function(e){v(!this.raisedInitialEvent,"Trying to raise initial events for second time"),e=Rr.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.raisedInitialEvent=!0,this.queryObserver.next(e)},e}(),wi=function(){function e(e,t,n,r){this.targetId=e,this.fromCache=t,this.addedKeys=n,this.removedKeys=r}return e.fromSnapshot=function(t,n){for(var r=Ve(),i=Ve(),o=0,a=n.docChanges;o<a.length;o++){var s=a[o];switch(s.type){case Dr.Added:r=r.add(s.doc.key);break;case Dr.Removed:i=i.add(s.doc.key)}}return new e(t,n.fromCache,r,i)},e}(),bi=function(e){this.key=e},Si=function(e){this.key=e},Ti=function(){function e(e,t){this.query=e,this._syncedDocuments=t,this.syncState=null,this.current=!1,this.limboDocuments=Ve(),this.mutatedKeys=Ve(),this.documentSet=new Nr(e.docComparator.bind(e))}return Object.defineProperty(e.prototype,"syncedDocuments",{get:function(){return this._syncedDocuments},enumerable:!0,configurable:!0}),e.prototype.computeDocChanges=function(e,t){var n=this,r=t?t.changeSet:new kr,i=t?t.documentSet:this.documentSet,o=t?t.mutatedKeys:this.mutatedKeys,a=i,s=!1,u=this.query.hasLimit()&&i.size===this.query.limit?i.last(
1):null;if(e.inorderTraversal((function(e,t){var c=i.get(e),h=t instanceof Qt?t:null;h&&(v(e.isEqual(h.key),"Mismatching keys found in document changes: "+e+" != "+h.key),h=n.query.matches(h)?h:null);var l=!!c&&n.mutatedKeys.has(c.key),f=!!h&&(h.hasLocalMutations||n.mutatedKeys.has(h.key)&&h.hasCommittedMutations),d=!1;c&&h?c.data().isEqual(h.data())?l!==f&&(r.track({type:Dr.Metadata,doc:h}),d=!0):n.shouldWaitForSyncedDocument(c,h)||(r.track({type:Dr.Modified,doc:h}),d=!0,u&&n.query.docComparator(h,u)>0&&(s=!0)):!c&&h?(r.track({type:Dr.Added,doc:h}),d=!0):c&&!h&&(r.track({type:Dr.Removed,doc:c}),d=!0,u&&(s=!0));d&&(h?(a=a.add(h),o=f?o.add(e):o.delete(e)):(a=a.delete(e),o=o.delete(e)))})),this.query.hasLimit())for(;a.size>this.query.limit;){var c=a.last();a=a.delete(c.key),o=o.delete(c.key),r.track({type:Dr.Removed,doc:c})}return v(!s||!t,"View was refilled using docs that themselves needed refilling."),{documentSet:a,changeSet:r,needsRefill:s,mutatedKeys:o}},e.prototype.shouldWaitForSyncedDocument=function(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations},e.prototype.applyChanges=function(e,t,n){var r=this;v(!e.needsRefill,"Cannot apply changes that need a refill");var i=this.documentSet;this.documentSet=e.documentSet,this.mutatedKeys=e.mutatedKeys;var o=e.changeSet.getChanges();o.sort((function(e,t){return function(e,t){var n=function(e){switch(e){case Dr.Added:return 1;case Dr.Modified:case Dr.Metadata:return 2;case Dr.Removed:return 0;default:return g("Unknown ChangeType: "+e)}};return n(e)-n(t)}(e.type,t.type)||r.query.docComparator(e.doc,t.doc)})),this.applyTargetChange(n);var a=t?this.updateLimboDocuments():[],s=0===this.limboDocuments.size&&this.current?_r.Synced:_r.Local,u=s!==this.syncState;return this.syncState=s,0!==o.length||u?{snapshot:new Rr(this.query,e.documentSet,i,o,e.mutatedKeys,s===_r.Local,u,!1),limboChanges:a}:{limboChanges:a}},e.prototype.applyOnlineStateChange=function(e){return this.current&&e===pr.Offline?(this.current=!1,this.applyChanges({documentSet:this.documentSet,changeSet:new kr,mutatedKeys:this.mutatedKeys,needsRefill:!1},!1)):{limboChanges:[]}},e.prototype.shouldBeInLimbo=function(e){return!this._syncedDocuments.has(e)&&(!!this.documentSet.has(e)&&!this.documentSet.get(e).hasLocalMutations)},e.prototype.applyTargetChange=function(e){var t=this;e&&(e.addedDocuments.forEach((function(e){return t._syncedDocuments=t._syncedDocuments.add(e)})),e.modifiedDocuments.forEach((function(e){return v(t._syncedDocuments.has(e),"Modified document "+e+" not found in view.")})),e.removedDocuments.forEach((function(e){return t._syncedDocuments=t._syncedDocuments.delete(e)})),this.current=e.current)},e.prototype.updateLimboDocuments=function(){var e=this;if(!this.current)return[];var t=this.limboDocuments;this.limboDocuments=Ve(),this.documentSet.forEach((function(t){e.shouldBeInLimbo(t.key)&&(e.limboDocuments=e.limboDocuments.add(t.key))}));var n=[];return t.forEach((function(t){e.limboDocuments.has(t)||n.push(new Si(t))})),this.limboDocuments.forEach((function(e){t.has(e)||n.push(new bi(e))})),n},e.prototype.synchronizeWithPersistedState=function(e){this._syncedDocuments=e.remoteKeys,this.limboDocuments=Ve();var t=this.computeDocChanges(e.documents);return this.applyChanges(t,!0)},e.prototype.computeInitialSnapshot=function(){return Rr.fromInitialDocuments(this.query,this.documentSet,this.mutatedKeys,this.syncState===_r.Local)},e}();var Ei=function(){function e(e,t,n,r){this.asyncQueue=e,this.remoteStore=t,this.updateFunction=n,this.deferred=r,this.retries=5,this.backoff=new fr(this.asyncQueue,te.RetryTransaction)}return e.prototype.run=function(){this.runWithBackOff()},e.prototype.runWithBackOff=function(){var e=this;this.backoff.backoffAndRun((function(){return a.__awaiter(e,void 0,void 0,(function(){var e,t,n=this;return a.__generator(this,(function(r){return e=this.remoteStore.createTransaction(),(t=this.tryRunUpdateFunction(e))&&t.then((function(t){n.asyncQueue.enqueueAndForget((function(){return e.commit().then((function(){n.deferred.resolve(t)})).catch((function(e){n.handleTransactionError(e)}))}))})).catch((function(e){n.handleTransactionError(e)})),[2]}))}
1))}))},e.prototype.tryRunUpdateFunction=function(e){try{var t=this.updateFunction(e);return!cr(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(m){return this.deferred.reject(m),null}},e.prototype.handleTransactionError=function(e){var t=this;this.retries>0&&this.isRetryableTransactionError(e)?(this.retries-=1,this.asyncQueue.enqueueAndForget((function(){return t.runWithBackOff(),Promise.resolve()}))):this.deferred.reject(e)},e.prototype.isRetryableTransactionError=function(e){if("FirebaseError"===e.name){var t=e.code;return"aborted"===t||"failed-precondition"===t||!Er(t)}return!1},e}(),Ii="SyncEngine",Ci=function(e,t,n){this.query=e,this.targetId=t,this.view=n},Di=function(e){this.key=e,this.receivedDocument=!1},_i=function(){function e(e,t,n,r){this.localStore=e,this.remoteStore=t,this.sharedClientState=n,this.currentUser=r,this.syncEngineListener=null,this.queryViewsByQuery=new Gt((function(e){return e.canonicalId()})),this.queryViewsByTarget={},this.limboTargetsByKey=new Ie(de.comparator),this.limboResolutionsByTarget={},this.limboDocumentRefs=new jn,this.mutationUserCallbacks={},this.pendingWritesCallbacks=new Map,this.limboTargetIdGenerator=st.forSyncEngine(),this.isPrimary=void 0,this.onlineState=pr.Unknown}return Object.defineProperty(e.prototype,"isPrimaryClient",{get:function(){return!0===this.isPrimary},enumerable:!0,configurable:!0}),e.prototype.subscribe=function(e){v(null!==e,"SyncEngine listener cannot be null"),v(null===this.syncEngineListener,"SyncEngine already has a subscriber."),this.syncEngineListener=e},e.prototype.listen=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n,r,i,o;return a.__generator(this,(function(a){switch(a.label){case 0:return this.assertSubscribed("listen()"),(r=this.queryViewsByQuery.get(e))?(t=r.targetId,this.sharedClientState.addLocalQueryTarget(t),n=r.view.computeInitialSnapshot(),[3,4]):[3,1];case 1:return[4,this.localStore.allocateQuery(e)];case 2:return i=a.sent(),o=this.sharedClientState.addLocalQueryTarget(i.targetId),t=i.targetId,[4,this.initializeViewAndComputeSnapshot(i,"current"===o)];case 3:n=a.sent(),this.isPrimary&&this.remoteStore.listen(i),a.label=4;case 4:return this.syncEngineListener.onWatchChange([n]),[2,t]}}))}))},e.prototype.initializeViewAndComputeSnapshot=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){var n,r,i,o,s,u,c;return a.__generator(this,(function(a){switch(a.label){case 0:return n=e.query,[4,this.localStore.executeQuery(n,!0)];case 1:return r=a.sent(),i=new Ti(n,r.remoteKeys),o=i.computeDocChanges(r.documents),s=Lr.createSynthesizedTargetChangeForCurrentChange(e.targetId,t&&this.onlineState!==pr.Offline),v(0===(u=i.applyChanges(o,!0===this.isPrimary,s)).limboChanges.length,"View returned limbo docs before target ack from the server."),v(!!u.snapshot,"applyChanges for new view should always return a snapshot"),c=new Ci(n,e.targetId,i),this.queryViewsByQuery.set(n,c),this.queryViewsByTarget[e.targetId]=c,[2,u.snapshot]}}))}))},e.prototype.synchronizeViewAndComputeSnapshot=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n;return a.__generator(this,(function(r){switch(r.label){case 0:return[4,this.localStore.executeQuery(e.query,!0)];case 1:return t=r.sent(),n=e.view.synchronizeWithPersistedState(t),this.isPrimary&&this.updateTrackedLimbos(e.targetId,n.limboChanges),[2,n]}}))}))},e.prototype.unlisten=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n=this;return a.__generator(this,(function(r){switch(r.label){case 0:return this.assertSubscribed("unlisten()"),v(!!(t=this.queryViewsByQuery.get(e)),"Trying to unlisten on query not found:"+e),this.isPrimary?(this.sharedClientState.removeLocalQueryTarget(t.targetId),this.sharedClientState.isActiveQueryTarget(t.targetId)?[3,2]:[4,this.localStore.releaseQuery(e,!1).then((function(){n.sharedClientState.clearQueryState(t.targetId),n.remoteStore.unlisten(t.targetId),n.removeAndCleanupQuery(t)})).catch(Un)]):[3,3];case 1:r.sent(),r.label=2;case 2:return[3,5];case 3:return this.removeAndCleanupQuery(t),[4,this.localStore.releaseQuery(e,!0)];case 4:r.sent(),r.label=5;case 5:return[2]}}
1))}))},e.prototype.write=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){var n;return a.__generator(this,(function(r){switch(r.label){case 0:return this.assertSubscribed("write()"),[4,this.localStore.localWrite(e)];case 1:return n=r.sent(),this.sharedClientState.addPendingMutation(n.batchId),this.addMutationCallback(n.batchId,t),[4,this.emitNewSnapsAndNotifyLocalStore(n.changes)];case 2:return r.sent(),[4,this.remoteStore.fillWritePipeline()];case 3:return r.sent(),[2]}}))}))},e.prototype.runTransaction=function(e,t,n){new Ei(e,this.remoteStore,t,n).run()},e.prototype.applyRemoteEvent=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n=this;return a.__generator(this,(function(r){switch(r.label){case 0:this.assertSubscribed("applyRemoteEvent()"),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.localStore.applyRemoteEvent(e)];case 2:return t=r.sent(),_(e.targetChanges,(function(e,t){var r=n.limboResolutionsByTarget[Number(e)];r&&(v(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,"Limbo resolution for single document contains multiple changes."),t.addedDocuments.size>0?r.receivedDocument=!0:t.modifiedDocuments.size>0?v(r.receivedDocument,"Received change for limbo target document without add."):t.removedDocuments.size>0&&(v(r.receivedDocument,"Received remove for limbo target document without add."),r.receivedDocument=!1))})),[4,this.emitNewSnapsAndNotifyLocalStore(t,e)];case 3:return r.sent(),[3,6];case 4:return[4,Un(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}
1))}))},e.prototype.applyOnlineStateChange=function(e,t){if(this.isPrimary&&t===mr.RemoteStore||!this.isPrimary&&t===mr.SharedClientState){this.assertSubscribed("applyOnlineStateChange()");var n=[];this.queryViewsByQuery.forEach((function(t,r){var i=r.view.applyOnlineStateChange(e);v(0===i.limboChanges.length,"OnlineState should not affect limbo documents."),i.snapshot&&n.push(i.snapshot)})),this.syncEngineListener.onOnlineStateChange(e),this.syncEngineListener.onWatchChange(n),this.onlineState=e,this.isPrimary&&this.sharedClientState.setOnlineState(e)}},e.prototype.rejectListen=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){var n,r,i,o,s,u,c=this;return a.__generator(this,(function(a){switch(a.label){case 0:return this.assertSubscribed("rejectListens()"),this.sharedClientState.updateQueryState(e,"rejected",t),n=this.limboResolutionsByTarget[e],(r=n&&n.key)?(this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboResolutionsByTarget[e],i=(i=new Ie(de.comparator)).insert(r,new Kt(r,Ee.forDeletedDoc())),o=Ve().add(r),s=new Mr(Ee.MIN,{},new Ne(J),i,o),[2,this.applyRemoteEvent(s)]):[3,1];case 1:return v(!!(u=this.queryViewsByTarget[e]),"Unknown targetId: "+e),[4,this.localStore.releaseQuery(u.query,!1).then((function(){return c.removeAndCleanupQuery(u)})).catch(Un)];case 2:a.sent(),this.syncEngineListener.onWatchError(u.query,t),a.label=3;case 3:return[2]}}
1))}))},e.prototype.applyBatchState=function(e,t,n){return a.__awaiter(this,void 0,void 0,(function(){var r;return a.__generator(this,(function(i){switch(i.label){case 0:return this.assertSubscribed("applyBatchState()"),[4,this.localStore.lookupMutationDocuments(e)];case 1:return null===(r=i.sent())?(p(Ii,"Cannot apply mutation batch with id: "+e),[2]):"pending"!==t?[3,3]:[4,this.remoteStore.fillWritePipeline()];case 2:return i.sent(),[3,4];case 3:"acknowledged"===t||"rejected"===t?(this.processUserCallback(e,n||null),this.localStore.removeCachedMutationBatchMetadata(e)):g("Unknown batchState: "+t),i.label=4;case 4:return[4,this.emitNewSnapsAndNotifyLocalStore(r)];case 5:return i.sent(),[2]}}))}))},e.prototype.applySuccessfulWrite=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n;return a.__generator(this,(function(r){switch(r.label){case 0:this.assertSubscribed("applySuccessfulWrite()"),t=e.batch.batchId,this.processUserCallback(t,null),this.triggerPendingWritesCallbacks(t),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.localStore.acknowledgeBatch(e)];case 2:return n=r.sent(),this.sharedClientState.updateMutationState(t,"acknowledged"),[4,this.emitNewSnapsAndNotifyLocalStore(n)];case 3:return r.sent(),[3,6];case 4:return[4,Un(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}
1))}))},e.prototype.rejectFailedWrite=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){var n;return a.__generator(this,(function(r){switch(r.label){case 0:this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(e,t),this.triggerPendingWritesCallbacks(e),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.localStore.rejectBatch(e)];case 2:return n=r.sent(),this.sharedClientState.updateMutationState(e,"rejected",t),[4,this.emitNewSnapsAndNotifyLocalStore(n)];case 3:return r.sent(),[3,6];case 4:return[4,Un(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}))}))},e.prototype.registerPendingWritesCallback=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n;return a.__generator(this,(function(r){switch(r.label){case 0:return this.remoteStore.canUseNetwork()||p(Ii,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),[4,this.localStore.getHighestUnacknowledgedBatchId()];case 1:return(t=r.sent())===Ue?(e.resolve(),[2]):((n=this.pendingWritesCallbacks.get(t)||[]).push(e),this.pendingWritesCallbacks.set(t,n),[2])}}))}))},e.prototype.triggerPendingWritesCallbacks=function(e){(this.pendingWritesCallbacks.get(e)||[]).forEach((function(e){e.resolve()})),this.pendingWritesCallbacks.delete(e)},e.prototype.rejectOutstandingPendingWritesCallbacks=function(e){this.pendingWritesCallbacks.forEach((function(t){t.forEach((function(t){t.reject(new T(S.CANCELLED,e))}))})),this.pendingWritesCallbacks.clear()},e.prototype.addMutationCallback=function(e,t){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new Ie(J)),n=n.insert(e,t),this.mutationUserCallbacks[this.currentUser.toKey()]=n},e.prototype.processUserCallback=function(e,t){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(e);r&&(v(e===n.minKey(),"Mutation callbacks processed out-of-order?"),t?r.reject(t):r.resolve(),n=n.remove(e)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},e.prototype.removeAndCleanupQuery=function(e){var t=this;if(this.sharedClientState.removeLocalQueryTarget(e.targetId),this.queryViewsByQuery.delete(e.query),delete this.queryViewsByTarget[e.targetId],this.isPrimary){var n=this.limboDocumentRefs.referencesForId(e.targetId);this.limboDocumentRefs.removeReferencesForId(e.targetId),n.forEach((function(e){t.limboDocumentRefs.containsKey(e)||t.removeLimboTarget(e)}))}},e.prototype.removeLimboTarget=function(e){var t=this.limboTargetsByKey.get(e);null!==t&&(this.remoteStore.unlisten(t),this.limboTargetsByKey=this.limboTargetsByKey.remove(e),delete this.limboResolutionsByTarget[t])},e.prototype.updateTrackedLimbos=function(e,t){for(var n=0,r=t;n<r.length;n++){var i=r[n];if(i instanceof bi)this.limboDocumentRefs.addReference(i.key,e),this.trackLimboChange(i);else if(i instanceof Si){p(Ii,"Document no longer in limbo: "+i.key),this.limboDocumentRefs.removeReference(i.key,e),this.limboDocumentRefs.containsKey(i.key)||this.removeLimboTarget(i.key)}else g("Unknown limbo change: "+JSON.stringify(i))}},e.prototype.trackLimboChange=function(e){var t=e.key;if(!this.limboTargetsByKey.get(t)){p(Ii,"New document in limbo: "+t);var n=this.limboTargetIdGenerator.next(),r=Wr.atPath(t.path);this.limboResolutionsByTarget[n]=new Di(t),this.remoteStore.listen(new Cn(r,n,vn.LimboResolution,se.INVALID)),this.limboTargetsByKey=this.limboTargetsByKey.insert(t,n)}},e.prototype.currentLimboDocs=function(){return this.limboTargetsByKey},e.prototype.emitNewSnapsAndNotifyLocalStore=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){var n,r,i,o=this;return a.__generator(this,(function(a){switch(a.label){case 0:return n=[],r=[],i=[],this.queryViewsByQuery.forEach((function(a,s){i.push(Promise.resolve().then((function(){var t=s.view.computeDocChanges(e);return t.needsRefill?o.localStore.executeQuery(s.query,!1).then((function(e){var n=e.documents;return s.view.computeDocChanges(n,t)})):t})).then((function(e){var i=t&&t.targetChanges[s.targetId],a=s.view.applyChanges(e,!0===o.isPrimary,i);if(o.updateTrackedLimbos(s.targetId,a.limboChanges),a.snapshot){o.isPrimary&&o.sharedCl
1ientState.updateQueryState(s.targetId,a.snapshot.fromCache?"not-current":"current"),n.push(a.snapshot);var u=wi.fromSnapshot(s.targetId,a.snapshot);r.push(u)}})))})),[4,Promise.all(i)];case 1:return a.sent(),this.syncEngineListener.onWatchChange(n),[4,this.localStore.notifyLocalViewChanges(r)];case 2:return a.sent(),[2]}}))}))},e.prototype.assertSubscribed=function(e){v(null!==this.syncEngineListener,"Trying to call "+e+" before calling subscribe().")},e.prototype.handleCredentialChange=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n;return a.__generator(this,(function(r){switch(r.label){case 0:return t=!this.currentUser.isEqual(e),this.currentUser=e,t?(this.rejectOutstandingPendingWritesCallbacks("'waitForPendingWrites' promise is rejected due to a user change."),[4,this.localStore.handleUserChange(e)]):[3,3];case 1:return n=r.sent(),this.sharedClientState.handleUserChange(e,n.removedBatchIds,n.addedBatchIds),[4,this.emitNewSnapsAndNotifyLocalStore(n.affectedDocuments)];case 2:r.sent(),r.label=3;case 3:return[4,this.remoteStore.handleCredentialChange()];case 4:return r.sent(),[2]}}))}))},e.prototype.applyPrimaryState=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n,r,i,o,s,u,c=this;return a.__generator(this,(function(a){switch(a.label){case 0:return!0!==e||!0===this.isPrimary?[3,3]:(this.isPrimary=!0,[4,this.remoteStore.applyPrimaryState(!0)]);case 1:return a.sent(),t=this.sharedClientState.getAllActiveQueryTargets(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(t.toArray())];case 2:for(n=a.sent(),r=0,i=n;r<i.length;r++)o=i[r],this.remoteStore.listen(o);return[3,7];case 3:return!1!==e||!1===this.isPrimary?[3,7]:(this.isPrimary=!1,s=[],u=Promise.resolve(),D(this.queryViewsByTarget,(function(e,t){c.sharedClientState.isLocalQueryTarget(e)?s.push(e):u=u.then((function(){return c.unlisten(t.query)})),c.remoteStore.unlisten(t.targetId)})),[4,u]);case 4:return a.sent(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(s)];case 5:return a.sent(),this.resetLimboDocuments(),[4,this.remoteStore.applyPrimaryState(!1)];case 6:a.sent(),a.label=7;case 7:return[2]}}
1))}))},e.prototype.resetLimboDocuments=function(){var e=this;D(this.limboResolutionsByTarget,(function(t){e.remoteStore.unlisten(t)})),this.limboDocumentRefs.removeAllReferences(),this.limboResolutionsByTarget=[],this.limboTargetsByKey=new Ie(de.comparator)},e.prototype.synchronizeQueryViewsAndRaiseSnapshots=function(e){return a.__awaiter(this,void 0,void 0,(function(){var t,n,r,i,o,s,u,c,h;return a.__generator(this,(function(a){switch(a.label){case 0:t=[],n=[],r=0,i=e,a.label=1;case 1:return r<i.length?(o=i[r],s=void 0,(u=this.queryViewsByTarget[o])?[4,this.localStore.releaseQuery(u.query,!0)]:[3,5]):[3,11];case 2:return a.sent(),[4,this.localStore.allocateQuery(u.query)];case 3:return s=a.sent(),[4,this.synchronizeViewAndComputeSnapshot(u)];case 4:return(c=a.sent()).snapshot&&n.push(c.snapshot),[3,9];case 5:return v(!0===this.isPrimary,"A secondary tab should never have an active query without an active view."),[4,this.localStore.getQueryForTarget(o)];case 6:return v(!!(h=a.sent()),"Query data for target "+o+" not found"),[4,this.localStore.allocateQuery(h)];case 7:return s=a.sent(),[4,this.initializeViewAndComputeSnapshot(s,!1)];case 8:a.sent(),a.label=9;case 9:t.push(s),a.label=10;case 10:return r++,[3,1];case 11:return this.syncEngineListener.onWatchChange(n),[2,t]}}))}))},e.prototype.getActiveClients=function(){return this.localStore.getActiveClients()},e.prototype.applyTargetState=function(e,t,n){return a.__awaiter(this,void 0,void 0,(function(){var r,i,o;return a.__generator(this,(function(a){switch(a.label){case 0:if(this.isPrimary)return p(Ii,"Ignoring unexpected query state notification."),[2];if(!this.queryViewsByTarget[e])return[3,7];switch(t){case"current":case"not-current":return[3,1];case"rejected":return[3,4]}return[3,6];case 1:return[4,this.localStore.getNewDocumentChanges()];case 2:return r=a.sent(),i=Mr.createSynthesizedRemoteEventForCurrentChange(e,"current"===t),[4,this.emitNewSnapsAndNotifyLocalStore(r,i)];case 3:return a.sent(),[3,7];case 4:return o=this.queryViewsByTarget[e],this.removeAndCleanupQuery(o),[4,this.localStore.releaseQuery(o.query,!0)];case 5:return a.sent(),this.syncEngineListener.onWatchError(o.query,n),[3,7];case 6:g("Unexpected target state: "+t),a.label=7;case 7:return[2]}}
1))}))},e.prototype.applyActiveTargetsChange=function(e,t){return a.__awaiter(this,void 0,void 0,(function(){var n,r,i,o,s,u,c,h,l,f=this;return a.__generator(this,(function(d){switch(d.label){case 0:if(!this.isPrimary)return[2];n=0,r=e,d.label=1;case 1:return n<r.length?(l=r[n],v(!this.queryViewsByTarget[l],"Trying to add an already active target"),[4,this.localStore.getQueryForTarget(l)]):[3,6];case 2:return v(!!(i=d.sent()),"Query data for active target "+l+" not found"),[4,this.localStore.allocateQuery(i)];case 3:return o=d.sent(),[4,this.initializeViewAndComputeSnapshot(o,!1)];case 4:d.sent(),this.remoteStore.listen(o),d.label=5;case 5:return n++,[3,1];case 6:s=function(e){var t;return a.__generator(this,(function(n){switch(n.label){case 0:return(t=u.queryViewsByTarget[e])?[4,u.localStore.releaseQuery(t.query,!1).then((function(){f.remoteStore.unlisten(e),f.removeAndCleanupQuery(t)})).catch(Un)]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}}))},u=this,c=0,h=t,d.label=7;case 7:return c<h.length?(l=h[c],[5,s(l)]):[3,10];case 8:d.sent(),d.label=9;case 9:return c++,[3,7];case 10:return[2]}}
1))}))},e.prototype.enableNetwork=function(){return this.localStore.setNetworkEnabled(!0),this.remoteStore.enableNetwork()},e.prototype.disableNetwork=function(){return this.localStore.setNetworkEnabled(!1),this.remoteStore.disableNetwork()},e.prototype.getRemoteKeysForTarget=function(e){var t=this.limboResolutionsByTarget[e];return t&&t.receivedDocument?Ve().add(t.key):this.queryViewsByTarget[e]?this.queryViewsByTarget[e].view.syncedDocuments:Ve()},e}(),Ni=function(){function e(e){this.uid=e}return e.prototype.isAuthenticated=function(){return null!=this.uid},e.prototype.toKey=function(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"},e.prototype.isEqual=function(e){return e.uid===this.uid},e.UNAUTHENTICATED=new e(null),e.GOOGLE_CREDENTIALS=new e("google-credentials-uid"),e.FIRST_PARTY=new e("first-party-uid"),e}(),Ai="SharedClientState",ki=function(){function e(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r,v(void 0!==r===("rejected"===n),"MutationMetadata must contain an error iff state is 'rejected'")}return e.fromWebStorageEntry=function(t,n,r){var i=JSON.parse(r),o="object"===typeof i&&-1!==["pending","acknowledged","rejected"].indexOf(i.state)&&(void 0===i.error||"object"===typeof i.error),a=void 0;return o&&i.error&&(o="string"===typeof i.error.message&&"string"===typeof i.error.code)&&(a=new T(i.error.code,i.error.message)),o?new e(t,n,i.state,a):(m(Ai,"Failed to parse mutation state for ID '"+n+"': "+r),null)},e.prototype.toWebStorageJSON=function(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)},e}(),Ri=function(){function e(e,t,n){this.targetId=e,this.state=t,this.error=n,v(void 0!==n===("rejected"===t),"QueryTargetMetadata must contain an error iff state is 'rejected'")}return e.fromWebStorageEntry=function(t,n){var r=JSON.parse(n),i="object"===typeof r&&-1!==["not-current","current","rejected"].indexOf(r.state)&&(void 0===r.error||"object"===typeof r.error),o=void 0;return i&&r.error&&(i="string"===typeof r.error.message&&"string"===typeof r.error.code)&&(o=new T(r.error.code,r.error.message)),i?new e(t,r.state,o):(m(Ai,"Failed to parse target state for ID '"+t+"': "+n),null)},e.prototype.toWebStorageJSON=function(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)},e}(),Mi=function(){function e(e,t){this.clientId=e,this.activeTargetIds=t}return e.fromWebStorageEntry=function(t,n){for(var r=JSON.parse(n),i="object"===typeof r&&r.activeTargetIds instanceof Array,o=Be(),a=0;i&&a<r.activeTargetIds.length;++a)i=hr(r.activeTargetIds[a]),o=o.add(r.activeTargetIds[a]);return i?new e(t,o):(m(Ai,"Failed to parse client data for instance '"+t+"': "+n),null)},e}(),Li=function(){function e(e,t){this.clientId=e,this.onlineState=t}return e.fromWebStorageEntry=function(t){var n=JSON.parse(t);return"object"===typeof n&&n.onlineState in pr&&"string"===typeof n.clientId?new e(n.clientId,pr[n.onlineState]):(m(Ai,"Failed to parse online state: "+t),null)},e}(),Oi=function(){function e(){this.activeTargetIds=Be()}return e.prototype.addQueryTarget=function(e){v(!this.activeTargetIds.has(e),"Target with ID '"+e+"' already active."),this.activeTargetIds=this.activeTargetIds.add(e)},e.prototype.removeQueryTarget=function(e){this.activeTargetIds=this.activeTargetIds.delete(e)},e.prototype.toWebStorageJSON=function(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)},e}(),Pi=function(){function e(t,n,r,i,o){if(this.queue=t,this.platform=n,this.persistenceKey=r,this.localClientId=i,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.activeClients={},this.storageListener=this.handleWebStorageEvent.bind(this),this.started=!1,this.earlyEvents=[],!e.isAvailable(this.platform))throw new T(S.UNIMPLEMENTED,"LocalStorage is not available on this platform.");var a=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.platform.window.localStorage,this.currentUser=o,this.localClientStorageKey=this.toWeb
1StorageClientStateKey(this.localClientId),this.sequenceNumberKey="firestore_sequence_number_"+r,this.activeClients[this.localClientId]=new Oi,this.clientStateKeyRe=new RegExp("^firestore_clients_"+a+"_([^_]*)$"),this.mutationBatchKeyRe=new RegExp("^firestore_mutations_"+a+"_(\\d+)(?:_(.*))?$"),this.queryTargetKeyRe=new RegExp("^firestore_targets_"+a+"_(\\d+)$"),this.onlineStateKey="firestore_online_state_"+r,this.platform.window.addEventListener("storage",this.storageListener)}return e.isAvailable=function(e){return!(!e.window||null==e.window.localStorage)},e.prototype.start=function(){return a.__awaiter(this,void 0,void 0,(function(){var e,t,n,r,i,o,s,u,c,h,l,f=this;return a.__generator(this,(function(a){switch(a.label){case 0:return v(!this.started,"WebStorageSharedClientState already started"),v(null!==this.syncEngine,"syncEngine property must be set before calling start()"),v(null!==this.onlineStateHandler,"onlineStateHandler property must be set before calling start()"),[4,this.syncEngine.getActiveClients()];case 1:for(e=a.sent(),t=0,n=e;t<n.length;t++)(r=n[t])!==this.localClientId&&(i=this.getItem(this.toWebStorageClientStateKey(r)))&&(o=Mi.fromWebStorageEntry(r,i))&&(this.activeClients[o.clientId]=o);for(this.persistClientState(),(s=this.storage.getItem(this.onlineStateKey))&&(u=this.fromWebStorageOnlineState(s))&&this.handleOnlineStateEvent(u),c=0,h=this.earlyEvents;c<h.length;c++)l=h[c],this.handleWebStorageEvent(l);return this.earlyEvents=[],this.platform.window.addEventListener("unload",(function(){return f.shutdown()})),this.started=!0,[2]}}))}))},e.prototype.writeSequenceNumber=function(e){this.setItem(this.sequenceNumberKey,JSON.stringify(e))},e.prototype.getAllActiveQueryTargets=function(){var e=Be();return _(this.activeClients,(function(t,n){e=e.unionWith(n.activeTargetIds)})),e},e.prototype.isActiveQueryTarget=function(e){for(var t in this.activeClients)if(this.activeClients.hasOwnProperty(t)&&this.activeClients[t].activeTargetIds.has(e))return!0;return!1},e.prototype.addPendingMutation=function(e){this.persistMutationState(e,"pending")},e.prototype.updateMutationState=function(e,t,n){this.persistMutationState(e,t,n),this.removeMutationState(e)},e.prototype.addLocalQueryTarget=function(e){var t="not-current";if(this.isActiveQueryTarget(e)){var n=this.storage.getItem(this.toWebStorageQueryTargetMetadataKey(e));if(n){var r=Ri.fromWebStorageEntry(e,n);r&&(t=r.state)}}return this.localClientState.addQueryTarget(e),this.persistClientState(),t},e.prototype.removeLocalQueryTarget=function(e){this.localClientState.removeQueryTarget(e),this.persistClientState()},e.prototype.isLocalQueryTarget=function(e){return this.localClientState.activeTargetIds.has(e)},e.prototype.clearQueryState=function(e){this.removeItem(this.toWebStorageQueryTargetMetadataKey(e))},e.prototype.updateQueryState=function(e,t,n){this.persistQueryTargetState(e,t,n)},e.prototype.handleUserChange=function(e,t,n){var r=this;t.forEach((function(e){r.removeMutationState(e)})),this.currentUser=e,n.forEach((function(e){r.addPendingMutation(e)}))},e.prototype.setOnlineState=function(e){this.persistOnlineState(e)},e.prototype.shutdown=function(){this.started&&(this.platform.window.removeEventListener("storage",this.storageListener),this.removeItem(this.localClientStorageKey),this.started=!1)},e.prototype.getItem=function(e){var t=this.storage.getItem(e);return p(Ai,"READ",e,t),t},e.prototype.setItem=function(e,t){p(Ai,"SET",e,t),this.storage.setItem(e,t)},e.prototype.removeItem=function(e){p(Ai,"REMOVE",e),this.storage.removeItem(e)},e.prototype.handleWebStorageEvent=function(e){var t=this;if(e.storageArea===this.storage){if(p(Ai,"EVENT",e.key,e.newValue),e.key===this.localClientStorageKey)return void m("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.queue.enqueueAndForget((function(){return a.__awaiter(t,void 0,void 0,(function(){var t,n,r,i,o,s;return a.__generator(this,(function(a){if(!this.started)return this.earlyEvents.push(e),[2];if(null===e.key)return[2];if(this.clientStateKeyRe.test(e.key)){if(null==e.newValue)return n=this.fromWebStorageClientStateKey(e.ke
1y),[2,this.handleClientStateEvent(n,null)];if(t=this.fromWebStorageClientState(e.key,e.newValue))return[2,this.handleClientStateEvent(t.clientId,t)]}else if(this.mutationBatchKeyRe.test(e.key)){if(null!==e.newValue&&(r=this.fromWebStorageMutationMetadata(e.key,e.newValue)))return[2,this.handleMutationBatchEvent(r)]}else if(this.queryTargetKeyRe.test(e.key)){if(null!==e.newValue&&(i=this.fromWebStorageQueryTargetMetadata(e.key,e.newValue)))return[2,this.handleQueryTargetEvent(i)]}else if(e.key===this.onlineStateKey){if(null!==e.newValue&&(o=this.fromWebStorageOnlineState(e.newValue)))return[2,this.handleOnlineStateEvent(o)]}else e.key===this.sequenceNumberKey&&(v(!!this.sequenceNumberHandler,"Missing sequenceNumberHandler"),(s=function(e){var t=se.INVALID;if(null!=e)try{var n=JSON.parse(e);v("number"===typeof n,"Found non-numeric sequence number"),t=n}catch(r){m(Ai,"Failed to read sequence number from WebStorage",r)}return t}(e.newValue))!==se.INVALID&&this.sequenceNumberHandler(s));return[2]}))}))}))}},Object.defineProperty(e.prototype,"localClientState",{get:function(){return this.activeClients[this.localClientId]},enumerable:!0,configurable:!0}),e.prototype.persistClientState=function(){this.setItem(this.localClientStorageKey,this.localClientState.toWebStorageJSON())},e.prototype.persistMutationState=function(e,t,n){var r=new ki(this.currentUser,e,t,n),i=this.toWebStorageMutationBatchKey(e);this.setItem(i,r.toWebStorageJSON())},e.prototype.removeMutationState=function(e){var t=this.toWebStorageMutationBatchKey(e);this.removeItem(t)},e.prototype.persistOnlineState=function(e){var t={clientId:this.localClientId,onlineState:pr[e]};this.storage.setItem(this.onlineStateKey,JSON.stringify(t))},e.prototype.persistQueryTargetState=function(e,t,n){var r=this.toWebStorageQueryTargetMetadataKey(e),i=new Ri(e,t,n);this.setItem(r,i.toWebStorageJSON())},e.prototype.toWebStorageClientStateKey=function(e){return v(-1===e.indexOf("_"),"Client key cannot contain '_', but was '"+e+"'"),"firestore_clients_"+this.persistenceKey+"_"+e},e.prototype.toWebStorageQueryTargetMetadataKey=function(e){return"firestore_targets_"+this.persistenceKey+"_"+e},e.prototype.toWebStorageMutationBatchKey=function(e){var t="firestore_mutations_"+this.persistenceKey+"_"+e;return this.currentUser.isAuthenticated()&&(t+="_"+this.currentUser.uid),t},e.prototype.fromWebStorageClientStateKey=function(e){var t=this.clientStateKeyRe.exec(e);return t?t[1]:null},e.prototype.fromWebStorageClientState=function(e,t){var n=this.fromWebStorageClientStateKey(e);return v(null!==n,"Cannot parse client state key '"+e+"'"),Mi.fromWebStorageEntry(n,t)},e.prototype.fromWebStorageMutationMetadata=function(e,t){var n=this.mutationBatchKeyRe.exec(e);v(null!==n,"Cannot parse mutation batch key '"+e+"'");var r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return ki.fromWebStorageEntry(new Ni(i),r,t)},e.prototype.fromWebStorageQueryTargetMetadata=function(e,t){var n=this.queryTargetKeyRe.exec(e);v(null!==n,"Cannot parse query target key '"+e+"'");var r=Number(n[1]);return Ri.fromWebStorageEntry(r,t)},e.prototype.fromWebStorageOnlineState=function(e){return Li.fromWebStorageEntry(e)},e.prototype.handleMutationBatchEvent=function(e){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(t){return e.user.uid!==this.currentUser.uid?(p(Ai,"Ignoring mutation for non-active user "+e.user.uid),[2]):[2,this.syncEngine.applyBatchState(e.batchId,e.state,e.error)]}))}))},e.prototype.handleQueryTargetEvent=function(e){return this.syncEngine.applyTargetState(e.targetId,e.state,e.error)},e.prototype.handleClientStateEvent=function(e,t){var n=this,r=this.getAllActiveQueryTargets();t?this.activeClients[e]=t:delete this.activeClients[e];var i=this.getAllActiveQueryTargets(),o=[],s=[];return i.forEach((function(e){return a.__awaiter(n,void 0,void 0,(function(){return a.__generator(this,(function(t){return r.has(e)||o.push(e),[2]}))}))})),r.forEach((function(e){return a.__awaiter(n,void 0,void 0,(function(){return a.__generator(this,(function(t){return i.has(e)||s.push(e),[2]}))}))})),this.syncEngine.applyActiveTargetsChange(o,s)},e.prototype.handleOnlineStateEvent=function(e){this.activeClients[e.clientId]&&this.onlineStateHandler(e.onlineState)},e}();var xi=function(){function e(){this.localState=new Oi,this.queryState={},this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null}return e.prototype.addPendingMutation=function(e){},e.prototype.updateMutationState=function(e,t,n){},e.prototype.addLocalQueryTarget=function(e){return this.localState.addQueryTarget(e),this.queryState[e]||"not-current"},e.prototype.updateQueryState=function(e,t,n){this.queryState[e]=t},e.prototype.removeLocalQueryTarget=function(e){this.localState.removeQueryTarget(e)},e.prototype.isLocalQueryTarget=function(e){return this.localState.activeTargetIds.has(e)},e.prototype.clearQueryState=function(e){delete this.queryState[e]},e.prototype.getAllActiveQueryTargets=function(){return this.localState.activeTargetIds},e.prototype.isActiveQueryTarget=function(e){return this.localState.activeTargetIds.has(e)},e.prototype.start=function(){return this.localState=new Oi,Promise.resolve()},e.prototype.handleUserChange=function(e,t,n){},e.prototype.setOnlineState=function(e){},e.prototype.shutdown=function(){},e.prototype.writeSequenceNumber=function(e){},e}(),qi="FirestoreClient",Vi=function(){function e(e,t){this.cacheSizeBytes=e,this.synchronizeTabs=t}return e.prototype.lruParams=function(){return kn.withCacheSize(this.cacheSizeBytes)},e}(),Fi=function(){},Bi=function(){function e(e,t,n,r){this.platform=e,this.databaseInfo=t,this.credentials=n,this.asyncQueue=r,this.clientId=Y.newId()}return e.prototype.start=function(e){var t=this;this.verifyNotTerminated();var n=new pe,r=new pe,i=!1;return this.credentials.setChangeListener((function(o){i?t.asyncQueue.enqueueAndForget((function(){return t.handleCredentialChange(o)})):(i=!0,t.initializePersistence(e,r,o).then((function(e){return t.initializeRest(o,e)})).then(n.resolve,n.reject))})),this.asyncQueue.enqueueAndForget((function(){return n.promise})),r.promise},e.prototype.enableNetwork=function(){var e=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue((function(){return e.syncEngine.enableNetwork()}))},e.prototype.initializePersistence=function(e,t,n){var r=this;return e instanceof Vi?this.startIndexedDbPersistence(n,e).then((function(e){return t.resolve(),e})).catch((function(e){if(t.reject(e),!r.canFallback(e))throw e;return console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+e),r.startMemoryPersistence()})):(t.resolve(),this.startMemoryPersistence())},e.prototype.canFallback=function(e){return e instanceof T?e.code===S.FAILED_PRECONDITION||e.code===S.UNIMPLEMENT
1ED:!("undefined"!==typeof DOMException&&e instanceof DOMException)||(22===e.code||20===e.code||11===e.code)},e.prototype.verifyNotTerminated=function(){if(this.asyncQueue.isShuttingDown)throw new T(S.FAILED_PRECONDITION,"The client has already been terminated.")},e.prototype.startIndexedDbPersistence=function(e,t){var n=this,r=Bn.buildStoragePrefix(this.databaseInfo),i=new mi(this.databaseInfo.databaseId,{useProto3Json:!0});return Promise.resolve().then((function(){return a.__awaiter(n,void 0,void 0,(function(){var n,o;return a.__generator(this,(function(a){switch(a.label){case 0:if(t.synchronizeTabs&&!Pi.isAvailable(this.platform))throw new T(S.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");return n=t.lruParams(),this.sharedClientState=t.synchronizeTabs?new Pi(this.asyncQueue,this.platform,r,this.clientId,e):new xi,[4,Bn.createIndexedDbPersistence({allowTabSynchronization:t.synchronizeTabs,persistenceKey:r,clientId:this.clientId,platform:this.platform,queue:this.asyncQueue,serializer:i,lruParams:n,sequenceNumberSyncer:this.sharedClientState})];case 1:return o=a.sent(),this.persistence=o,[2,o.referenceDelegate.garbageCollector]}}))}))}))},e.prototype.startMemoryPersistence=function(){return this.persistence=er.createEagerPersistence(this.clientId),this.sharedClientState=new xi,Promise.resolve(null)},e.prototype.initializeRest=function(e,t){var n=this;return p(qi,"Initializing. user=",e.uid),this.platform.loadConnection(this.databaseInfo).then((function(r){return a.__awaiter(n,void 0,void 0,(function(){var n,i,o,s,u,c,h=this;return a.__generator(this,(function(l){switch(l.label){case 0:return n=new ir,this.localStore=new Jn(this.persistence,n,e),[4,this.localStore.start()];
1case 1:return l.sent(),t&&(this.lruScheduler=new Rn(t,this.asyncQueue,this.localStore)),i=this.platform.newConnectivityMonitor(),o=this.platform.newSerializer(this.databaseInfo.databaseId),s=new wr(this.asyncQueue,r,this.credentials,o),u=function(e){return h.syncEngine.applyOnlineStateChange(e,mr.RemoteStore)},c=function(e){return h.syncEngine.applyOnlineStateChange(e,mr.SharedClientState)},this.remoteStore=new Qr(this.localStore,s,this.asyncQueue,u,i),this.syncEngine=new _i(this.localStore,this.remoteStore,this.sharedClientState,e),this.sharedClientState.onlineStateHandler=c,this.remoteStore.syncEngine=this.syncEngine,this.sharedClientState.syncEngine=this.syncEngine,this.eventMgr=new gi(this.syncEngine),[4,this.sharedClientState.start()];case 2:return l.sent(),[4,this.remoteStore.start()];case 3:return l.sent(),[4,this.persistence.setPrimaryStateListener((function(e){return a.__awaiter(h,void 0,void 0,(function(){return a.__generator(this,(function(t){switch(t.label){case 0:return[4,this.syncEngine.applyPrimaryState(e)];case 1:return t.sent(),this.lruScheduler&&(e&&!this.lruScheduler.started?this.lruScheduler.start():e||this.lruScheduler.stop()),[2]}}))}))}))];case 4:return l.sent(),[4,this.persistence.setDatabaseDeletedListener((function(){return a.__awaiter(h,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return[4,this.terminate()];case 1:return e.sent(),[2]}}))}))}))];case 5:return l.sent(),[2]}}))}))}))},e.prototype.handleCredentialChange=function(e){return this.asyncQueue.verifyOperationInProgress(),p(qi,"Credential Changed. Current user: "+e.uid),this.syncEngine.handleCredentialChange(e)},e.prototype.disableNetwork=function(){var e=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue((function(){return e.syncEngine.disableNetwork()}))},e.prototype.terminate=function(){var e=this;return this.asyncQueue.enqueueAndInitiateShutdown((function(){return a.__awaiter(e,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.lruScheduler&&this.lruScheduler.stop(),[4,this.remoteStore.shutdown()];case 1:return e.sent(),[4,this.sharedClientState.shutdown()];case 2:return e.sent(),[4,this.persistence.shutdown()];case 3:return e.sent(),this.credentials.removeChangeListener(),[2]}}))}))}))},e.prototype.waitForPendingWrites=function(){var e=this;this.verifyNotTerminated();var t=new pe;return this.asyncQueue.enqueueAndForget((function(){return e.syncEngine.registerPendingWritesCallback(t)})),t.promise},e.prototype.listen=function(e,t,n){var r=this;this.verifyNotTerminated();var i=new vi(e,t,n);return this.asyncQueue.enqueueAndForget((function(){return r.eventMgr.listen(i)})),i},e.prototype.unlisten=function(e){var t=this;this.clientTerminated||this.asyncQueue.enqueueAndForget((function(){return t.eventMgr.unlisten(e)}))},e.prototype.getDocumentFromLocalCache=function(e){var t=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue((function(){return t.localStore.readDocument(e)})).then((function(e){if(e instanceof Qt)return e;if(e instanceof Kt)return null;throw new T(S.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")}))},e.prototype.getDocumentsFromLocalCache=function(e){var t=this;return this.verifyNotTerminated(),this.asyncQueue.enqueue((function(){return a.__awaiter(t,void 0,void 0,(function(){var t,n,r;return a.__generator(this,(function(i){switch(i.label){case 0:return[4,this.localStore.executeQuery(e,!0)];case 1:return t=i.sent(),n=new Ti(e,t.remoteKeys),r=n.computeDocChanges(t.documents),[2,n.applyChanges(r,!1).snapshot]}}))}))}))},e.prototype.write=function(e){var t=this;this.verifyNotTerminated();var n=new pe;return this.asyncQueue.enqueueAndForget((function(){return t.syncEngine.write(e,n)})),n.promise},e.prototype.databaseId=function(){return this.databaseInfo.databaseId},e.prototype.addSnapshotsInSyncListener=function(e){var t=this;this.verifyNotTerminated(),this.asyncQueue.enqueueAndForget((function(){return t.eventMgr.addSnapsh
1otsInSyncListener(e),Promise.resolve()}))},e.prototype.removeSnapshotsInSyncListener=function(e){this.clientTerminated||this.eventMgr.removeSnapshotsInSyncListener(e)},Object.defineProperty(e.prototype,"clientTerminated",{get:function(){return this.asyncQueue.isShuttingDown},enumerable:!0,configurable:!0}),e.prototype.transaction=function(e){var t=this;this.verifyNotTerminated();var n=new pe;return this.asyncQueue.enqueueAndForget((function(){return t.syncEngine.runTransaction(t.asyncQueue,e,n),Promise.resolve()})),n.promise},e}(),Ui=function(){function e(e){this.observer=e,this.muted=!1}return e.prototype.next=function(e){this.scheduleEvent(this.observer.next,e)},e.prototype.error=function(e){this.scheduleEvent(this.observer.error,e)},e.prototype.mute=function(){this.muted=!0},e.prototype.scheduleEvent=function(e,t){var n=this;this.muted||setTimeout((function(){n.muted||e(t)}),0)},e}(),Qi=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];L("FieldPath",e,"fieldNames",1);for(var n=0;n<e.length;++n)if(O("FieldPath","string",n,e[n]),0===e[n].length)throw new T(S.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new fe(e)}return e.documentId=function(){return e._DOCUMENT_ID},e.prototype.isEqual=function(t){if(!(t instanceof e))throw z("isEqual","FieldPath",1,t);return this._internalPath.isEqual(t._internalPath)},e._DOCUMENT_ID=new e(fe.keyField().canonicalString()),e}(),Ki=new RegExp("[~\\*/\\[\\]]");var Wi=function(e,t){this.user=t,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+e}},Gi=function(){function e(){this.changeListener=null}return e.prototype.getToken=function(){return Promise.resolve(null)},e.prototype.invalidateToken=function(){},e.prototype.setChangeListener=function(e){v(!this.changeListener,"Can only call setChangeListener() once."),this.changeListener=e,e(Ni.UNAUTHENTICATED)},e.prototype.removeChangeListener=function(){v(null!==this.changeListener,"removeChangeListener() when no listener registered"),this.changeListener=null},e}(),zi=function(){function e(e){var t=this;this.app=e,this.tokenListener=null,this.currentUser=Ni.UNAUTHENTICATED,this.tokenCounter=0,this.changeListener=null,this.forceRefresh=!1,this.tokenListener=function(){t.tokenCounter++,t.currentUser=t.getUser(),t.changeListener&&t.changeListener(t.currentUser)},this.currentUser=this.getUser(),this.tokenCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return e.prototype.getToken=function(){var e=this;v(null!=this.tokenListener,"getToken cannot be called after listener removed.");var t=this.tokenCounter,n=this.forceRefresh;return this.forceRefresh=!1,this.app.INTERNAL.getToken(n).then((function(n){if(e.tokenCounter!==t)throw new T(S.ABORTED,"getToken aborted due to token change.");return n?(v("string"===typeof n.accessToken,"Invalid tokenData returned from getToken():"+n),new Wi(n.accessToken,e.currentUser)):null}))},e.prototype.invalidateToken=function(){this.forceRefresh=!0},e.prototype.setChangeListener=function(e){v(!this.changeListener,"Can only call setChangeListener() once."),this.changeListener=e,e(this.currentUser)},e.prototype.removeChangeListener=function(){v(null!=this.tokenListener,"removeChangeListener() called twice"),v(null!==this.changeListener,"removeChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.changeListener=null},e.prototype.getUser=function(){var e=this.app.INTERNAL.getUid();return v(null===e||"string"===typeof e,"Received invalid UID: "+e),new Ni(e)},e}(),ji=function(){function e(e,t){this.gapi=e,this.sessionIndex=t,this.type="FirstParty",this.user=Ni.FIRST_PARTY}return Object.defineProperty(e.prototype,"authHeaders",{get:function(){var e={"X-Goog-AuthUser":this.sessionIndex},t=this.gapi.auth.getAuthHeaderValueForFirstParty([]);return t&&(e.Authorization=t),e},enumerable:!0,configurable:!0}),e}(),Hi=function(){function e(e,t){this.gapi=e,this.sessionIndex=t}return e.prototype.getToken=function(){return Promise.resolve(new ji(this.gapi,this.sessionIndex))},e.prototype.setChangeListener=function(e){e(Ni.FIRST_PARTY)},e.prototype.removeChangeListener=function(){},e.prototype.invalidateToken=function(){},e}();function Yi(e){if(!e)return new Gi;switch(e.type){case"gapi":var t=e.client;return v(!("object"!==typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty),"unexpected gapi interface"),new Hi(t,e.sessionIndex||"0");case"provider":return e.client;default:throw new T(S.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invali
1d credential type")}}function Ji(e){return function(e,t){if("object"!==typeof e||null===e)return!1;for(var n=e,r=0,i=t;r<i.length;r++){var o=i[r];if(o in n&&"function"===typeof n[o])return!0}return!1}(e,["next","error","complete"])}var Xi,Zi=function(){function e(e){this._methodName=e}return e.delete=function(){return A("FieldValue.delete",arguments),$i.instance},e.serverTimestamp=function(){return A("FieldValue.serverTimestamp",arguments),eo.instance},e.arrayUnion=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return R("FieldValue.arrayUnion",arguments,1),new to(e)},e.arrayRemove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return R("FieldValue.arrayRemove",arguments,1),new no(e)},e.increment=function(e){return O("FieldValue.increment","number",1,e),k("FieldValue.increment",arguments,1),new ro(e)},e.prototype.isEqual=function(e){return this===e},e}(),$i=function(e){function t(){return e.call(this,"FieldValue.delete")||this}return a.__extends(t,e),t.instance=new t,t}(Zi),eo=function(e){function t(){return e.call(this,"FieldValue.serverTimestamp")||this}return a.__extends(t,e),t.instance=new t,t}(Zi),to=function(e){function t(t){var n=e.call(this,"FieldValue.arrayUnion")||this;return n._elements=t,n}return a.__extends(t,e),t}(Zi),no=function(e){function t(t){var n=e.call(this,"FieldValue.arrayRemove")||this;return n._elements=t,n}return a.__extends(t,e),t}(Zi),ro=function(e){function t(t){var n=e.call(this,"FieldValue.increment")||this;return n._operand=t,n}return a.__extends(t,e),t}(Zi),io=E(Zi,"Use FieldValue.<field>() instead."),oo=/^__.*__$/,ao=function(){function e(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}return e.prototype.toMutations=function(e,t){var n=[];return null!==this.fieldMask?n.push(new Tt(e,this.data,this.fieldMask,t)):n.push(new St(e,this.data,t)),this.fieldTransforms.length>0&&n.push(new Et(e,this.fieldTransforms)),n},e}(),so=function(){function e(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}return e.prototype.toMutations=function(e,t){var n=[new Tt(e,this.data,this.fieldMask,t)];return this.fieldTransforms.length>0&&n.push(new Et(e,this.fieldTransforms)),n},e}();function uo(e){switch(e){case Xi.Set:case Xi.MergeSet:case Xi.Update:return!0;case Xi.Argument:return!1;default:throw g("Unexpected case for UserDataSource: "+e)}}!function(e){e[e.Set=0]="Set",e[e.Update=1]="Update",e[e.MergeSet=2]="MergeSet",e[e.Argument=3]="Argument"}(Xi||(Xi={}));var co=function(){function e(e,t,n,r,i,o){this.dataSource=e,this.methodName=t,this.path=n,this.arrayElement=r,void 0===i&&this.validatePath(),this.arrayElement=void 0!==r&&r,this.fieldTransforms=i||[],this.fieldMask=o||[]}return e.prototype.childContextForField=function(t){var n=null==this.path?null:this.path.child(t),r=new e(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(t),r},e.prototype.childContextForFieldPath=function(t){var n=null==this.path?null:this.path.child(t),r=new e(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},e.prototype.childContextForArray=function(t){return new e(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},e.prototype.createError=function(e){var t=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path.toString()+")";return new T(S.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+e+t)},e.prototype.contains=function(e){return void 0!==this.fieldMask.find((function(t){return e.isPrefixOf(t)}))||void 0!==this.fieldTransforms.find((function(t){return e.isPrefixOf(t.field)}))},e.prototype.validatePath=function(){if(null!==this.path)for(var e=0;e<this.path.length;e++)this.validatePathSegment(this.path.get(e))},e.prototype.validatePathSegment=function(e){if(uo(this.dataSource)&&oo.test(e))throw this.createError("Document fields cannot begin and end with __")},e}(),ho=function(e,t){this.databaseId=e,this.key=t},lo=function(){function e(e){this.preConverter=e}return e.prototype.parseSetData=function(e,t){var n=new co(Xi.Set,e,fe.EMPTY_PATH);po("Data must be an object, but it was:",n,t);var r=this.parseData(t,n);return new ao(r,null,n.fieldTransforms)},e.prototype.parseMergeData=function(e,t,n){var r=new co(Xi.MergeSet,e,fe.EMPTY_PATH);po("Data must be an object, but it was:",r,t);var i,o,a=this.parseData(t,r);if(n){for(var s=new Ne(fe.comparator),u=0,c=n;u<c.length;u++){var h=c[u],l=void 0;if(h instanceof Qi)l=h._internalPath;else{if("string"!==typeof h)throw g("Expected stringOrFieldPath to be a string or a FieldPath");l=yo(e,h)}if(!r.contains(l))throw new T(S.INVALID_ARGUMENT,"Field '"+l+"' is specified in your field mask but missing from your input data.");s=s.add(l)}i=pt.fromSet(s),o=r.fieldTransforms.filter((function(e){return i.covers(e.field)}))}else i=pt.fromArray(r.fieldMask),o=r.fieldTransforms;return new ao(a,i,o)}
1,e.prototype.parseUpdateData=function(e,t){var n=this,r=new co(Xi.Update,e,fe.EMPTY_PATH);po("Data must be an object, but it was:",r,t);var i=new Ne(fe.comparator),o=Ft.EMPTY;_(t,(function(t,a){var s=yo(e,t),u=r.childContextForFieldPath(s);if((a=n.runPreConverter(a,u))instanceof $i)i=i.add(s);else{var c=n.parseData(a,u);null!=c&&(i=i.add(s),o=o.set(s,c))}}));var a=pt.fromSet(i);return new so(o,a,r.fieldTransforms)},e.prototype.parseUpdateVarargs=function(e,t,n,r){var i=new co(Xi.Update,e,fe.EMPTY_PATH),o=[mo(e,t)],a=[n];if(r.length%2!==0)throw new T(S.INVALID_ARGUMENT,"Function "+e+"() 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(mo(e,r[s])),a.push(r[s+1]);var u=new Ne(fe.comparator),c=Ft.EMPTY;for(s=0;s<o.length;++s){var h=o[s],l=i.childContextForFieldPath(h),f=this.runPreConverter(a[s],l);if(f instanceof $i)u=u.add(h);else{var d=this.parseData(f,l);null!=d&&(u=u.add(h),c=c.set(h,d))}}var p=pt.fromSet(u);return new so(c,p,i.fieldTransforms)},e.prototype.parseQueryValue=function(e,t){var n=new co(Xi.Argument,e,fe.EMPTY_PATH),r=this.parseData(t,n);return v(null!=r,"Parsed data should not be null."),v(0===n.fieldTransforms.length,"Field transforms should have been disallowed."),r},e.prototype.runPreConverter=function(e,t){try{return this.preConverter(e)}catch(r){var n=go(r);throw t.createError(n)}},e.prototype.parseData=function(e,t){if(fo(e=this.runPreConverter(e,t)))return po("Unsupported field value:",t,e),this.parseObject(e,t);if(e instanceof Zi)return this.parseSentinelFieldValue(e,t),null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.arrayElement)throw t.createError("Nested arrays are not supported");return this.parseArray(e,t)}return this.parseScalarValue(e,t)},e.prototype.parseObject=function(e,t){var n=this,r=new Ie(J);return N(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):_(e,(function(e,i){var o=n.parseData(i,t.childContextForField(e));null!=o&&(r=r.insert(e,o))})),new Ft(r)},e.prototype.parseArray=function(e,t){for(var n=[],r=0,i=0,o=e;i<o.length;i++){var a=o[i],s=this.parseData(a,t.childContextForArray(r));null==s&&(s=_t.INSTANCE),n.push(s),r++}return new Bt(n)},e.prototype.parseSentinelFieldValue=function(e,t){if(!uo(t.dataSource))throw t.createError(e._methodName+"() can only be used with update() and set()");if(null===t.path)throw t.createError(e._methodName+"() is not currently supported inside arrays");if(e instanceof $i){if(t.dataSource!==Xi.MergeSet)throw t.dataSource===Xi.Update?(v(t.path.length>0,"FieldValue.delete() at the top level should have already been handled."),t.createError("FieldValue.delete() can only appear at the top level of your update data")):t.createError("FieldValue.delete() cannot be used with set() unless you pass {merge:true}");t.fieldMask.push(t.path)}else if(e instanceof eo)t.fieldTransforms.push(new mt(t.path,ii.instance));else if(e instanceof to){var n=this.parseArrayTransformElements(e._methodName,e._elements),r=new oi(n);t.fieldTransforms.push(new mt(t.path,r))}else if(e instanceof no){n=this.parseArrayTransformElements(e._methodName,e._elements);var i=new ai(n);t.fieldTransforms.push(new mt(t.path,i))}else if(e instanceof ro){var o=this.parseQueryValue("FieldValue.increment",e._operand),a=new si(o);t.fieldTransforms.push(new mt(t.path,a))}else g("Unknown FieldValue type: "+e)},e.prototype.parseScalarValue=function(e,t){if(null===e)return _t.INSTANCE;if("number"===typeof e)return hr(e)?new Rt(e):new Mt(e);if("boolean"===typeof e)return Nt.of(e);if("string"===typeof e)return new Lt(e);if(e instanceof Date)return new Ot(Te.fromDate(e));if(e instanceof Te)return new Ot(new Te(e.seconds,1e3*Math.floor(e.nanoseconds/1e3)));if(e instanceof Kr)return new Vt(e);
1if(e instanceof ne)return new xt(e);if(e instanceof ho)return new qt(e.databaseId,e.key);throw t.createError("Unsupported field value: "+K(e))},e.prototype.parseArrayTransformElements=function(e,t){var n=this;return t.map((function(t,r){var i=new co(Xi.Argument,e,fe.EMPTY_PATH);return n.parseData(t,i.childContextForArray(r))}))},e}();function fo(e){return"object"===typeof e&&null!==e&&!(e instanceof Array)&&!(e instanceof Date)&&!(e instanceof Te)&&!(e instanceof Kr)&&!(e instanceof ne)&&!(e instanceof ho)&&!(e instanceof Zi)}function po(e,t,n){if(!fo(n)||!Q(n)){var r=K(n);throw"an object"===r?t.createError(e+" a custom object"):t.createError(e+" "+r)}}function mo(e,t){if(t instanceof Qi)return t._internalPath;if("string"===typeof t)return yo(e,t);throw new T(S.INVALID_ARGUMENT,"Function "+e+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function yo(e,t){try{return function(e){if(e.search(Ki)>=0)throw new T(S.INVALID_ARGUMENT,"Invalid field path ("+e+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(Qi.bind.apply(Qi,a.__spreadArrays([void 0],e.split("."))))}catch(t){throw new T(S.INVALID_ARGUMENT,"Invalid field path ("+e+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}(t)._internalPath}catch(r){var n=go(r);throw new T(S.INVALID_ARGUMENT,"Function "+e+"() called with invalid data. "+n)}}function go(e){return e instanceof Error?e.message:e.toString()}var vo=kn.COLLECTION_DISABLED,wo=function(){function e(e){if(void 0===e.host){if(void 0!==e.ssl)throw new T(S.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=true}else x("settings","non-empty string","host",e.host),this.host=e.host,q("settings","boolean","ssl",e.ssl),this.ssl=C(e.ssl,true);if(G("settings",e,["host","ssl","credentials","timestampsInSnapshots","cacheSizeBytes","experimentalForceLongPolling"]),q("settings","object","credentials",e.credentials),this.credentials=e.credentials,q("settings","boolean","timestampsInSnapshots",e.timestampsInSnapshots),!0===e.timestampsInSnapshots?m("\n  The timestampsInSnapshots setting now defaults to true and you no\n  longer need to explicitly set it. In a future release, the setting\n  will be removed entirely and so it is recommended that you remove it\n  from your firestore.settings() call now."):!1===e.timestampsInSnapshots&&m("\n  The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\n  YOUR CODE.\n\n  To hide this warning, stop using the timestampsInSnapshots setting in your\n  firestore.settings({ ... }) call.\n\n  Once you remove the setting, Timestamps stored in Cloud Firestore will be\n  read back as Firebase Timestamp objects instead of as system Date objects.\n  So you will also need to update code expecting a Date to instead expect a\n  Timestamp. For example:\n\n  // Old:\n  const date = snapshot.get('created_at');\n  // New:\n  const timestamp = snapshot.get('created_at'); const date =\n  timestamp.toDate();\n\n  Please audit all existing usages of Date when you enable the new\n  behavior."),this.timestampsInSnapshots=C(e.timestampsInSnapshots,true),q("settings","number","cacheSizeBytes",e.cacheSizeBytes),void 0===e.cacheSizeBytes)this.cacheSizeBytes=kn.DEFAULT_CACHE_SIZE_BYTES;else{if(e.cacheSizeBytes!==vo&&e.cacheSizeBytes<kn.MINIMUM_CACHE_SIZE_BYTES)throw new T(S.INVALID_ARGUMENT,"cacheSizeBytes must be at least "+kn.MINIMUM_CACHE_SIZE_BYTES);this.cacheSizeBytes=e.cacheSizeBytes}q("settings","boolean","experimentalForceLongPolling",e.experimentalForceLongPolling),this.forceLongPolling=void 0!==e.experimentalForceLongPolling&&e.experimentalForceLongPolling}return e.prototype.isEqual=function(e){return this.host===e.host&&this.ssl===e.ssl&&this.timestampsInSnapshots===e.timestampsInSnapshots&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.forceLongPolling===e.forceLongPolling},e}(),bo=function(){function e(t){var n=this;if(this._firebaseApp=null,this._queue=new ye,this.INTERNAL={delete:function(){return a.__awaiter(n,void 0,void 0,(function(){return a.__generator(this,(function(e){switch(e.label){case 0:return this.ensureClientConfigured(),[4,this._firestoreClient.terminate()];case 1:return e.sent(),[2]}}))}))}},"object"===typeof t.options){var r=t;this._firebaseApp=r,this._databaseId=e.databaseIdFromApp(r),this._persistenceKey=r.name,this._credentials=new zi(r)}else{var i=t;if(!i.projectId)throw new T(S.INVALID_ARGUMENT,"Must provide projectId");this._databaseId=new ae(i.projectId,i.database),this._persistenceKey="[DEFAULT]",this._credentials=new Gi}this._settings=new wo({}),this._dataConverter=this.createDataConverter(this._databaseId)}return e.prototype.settings=function(e){if(k("Firestore.settings",arguments,1
1),O("Firestore.settings","object",1,e),I(e,"persistence"))throw new T(S.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var t=new wo(e);if(this._firestoreClient&&!this._settings.isEqual(t))throw new T(S.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._settings=t,void 0!==t.credentials&&(this._credentials=Yi(t.credentials))},e.prototype.enableNetwork=function(){return this.ensureClientConfigured(),this._firestoreClient.enableNetwork()},e.prototype.disableNetwork=function(){return this.ensureClientConfigured(),this._firestoreClient.disableNetwork()},e.prototype.enablePersistence=function(e){if(this._firestoreClient)throw new T(S.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");var t=!1;return e&&(void 0!==e.experimentalTabSynchronization&&m("The 'experimentalTabSynchronization' setting has been renamed to 'synchronizeTabs'. In a future release, the setting will be removed and it is recommended that you update your firestore.enablePersistence() call to use 'synchronizeTabs'."),t=C(void 0!==e.synchronizeTabs?e.synchronizeTabs:e.experimentalTabSynchronization,false)),this.configureClient(new Vi(this._settings.cacheSizeBytes,t))},e.prototype.clearPersistence=function(){var e=this,t=Bn.buildStoragePrefix(this.makeDatabaseInfo()),n=new pe;return this._queue.enqueueAndForgetEvenAfterShutdown((function(){return a.__awaiter(e,void 0,void 0,(function(){var e;return a.__generator(this,(function(r){switch(r.label){case 0:if(r.trys.push([0,2,,3]),void 0!==this._firestoreClient&&!this._firestoreClient.clientTerminated)throw new T(S.FAILED_PRECONDITION,"Persistence cannot be cleared after this Firestore instance is initialized.");return[4,Bn.clearPersistence(t)];case 1:return r.sent(),n.resolve(),[3,3];case 2:return e=r.sent(),n.reject(e),[3,3];case 3:return[2]}}
1))}))})),n.promise},e.prototype.terminate=function(){return this.app._removeServiceInstance("firestore"),this.INTERNAL.delete()},Object.defineProperty(e.prototype,"_isTerminated",{get:function(){return this.ensureClientConfigured(),this._firestoreClient.clientTerminated},enumerable:!0,configurable:!0}),e.prototype.waitForPendingWrites=function(){return this.ensureClientConfigured(),this._firestoreClient.waitForPendingWrites()},e.prototype.onSnapshotsInSync=function(e){if(this.ensureClientConfigured(),Ji(e))return this.onSnapshotsInSyncInternal(e);O("Firestore.onSnapshotsInSync","function",1,e);var t={next:e};return this.onSnapshotsInSyncInternal(t)},e.prototype.onSnapshotsInSyncInternal=function(e){var t=this,n=new Ui({next:function(){e.next&&e.next()},error:function(e){throw g("Uncaught Error in onSnapshotsInSync")}});return this._firestoreClient.addSnapshotsInSyncListener(n),function(){n.mute(),t._firestoreClient.removeSnapshotsInSyncListener(n)}},e.prototype.ensureClientConfigured=function(){return this._firestoreClient||this.configureClient(new Fi),this._firestoreClient},e.prototype.makeDatabaseInfo=function(){return new ie(this._databaseId,this._persistenceKey,this._settings.host,this._settings.ssl,this._settings.forceLongPolling)},e.prototype.configureClient=function(e){v(!!this._settings.host,"FirestoreSettings.host is not set"),v(!this._firestoreClient,"configureClient() called multiple times");var t=this.makeDatabaseInfo();return this._firestoreClient=new Bi(w.getPlatform(),t,this._credentials,this._queue),this._firestoreClient.start(e)},e.prototype.createDataConverter=function(e){return new lo((function(t){if(t instanceof Eo){var n=e,r=t.firestore._databaseId;if(!r.isEqual(n))throw new T(S.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new ho(e,t._key)}return t}))},e.databaseIdFromApp=function(e){var t=e.options;if(!I(t,"projectId"))throw new T(S.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');var n=t.projectId;if(!n||"string"!==typeof n)throw new T(S.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new ae(n)},Object.defineProperty(e.prototype,"app",{get:function(){if(!this._firebaseApp)throw new T(S.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._firebaseApp},enumerable:!0,configurable:!0}),e.prototype.collection=function(e){return k("Firestore.collection",arguments,1),O("Firestore.collection","non-empty string",1,e),this.ensureClientConfigured(),new Ao(he.fromString(e),this)},e.prototype.doc=function(e){return k("Firestore.doc",arguments,1),O("Firestore.doc","non-empty string",1,e),this.ensureClientConfigured(),Eo.forPath(he.fromString(e),this)},e.prototype.collectionGroup=function(e){if(k("Firestore.collectionGroup",arguments,1),O("Firestore.collectionGroup","non-empty string",1,e),e.indexOf("/")>=0)throw new T(S.INVALID_ARGUMENT,"Invalid collection ID '"+e+"' passed to function Firestore.collectionGroup(). Collection IDs must not contain '/'.");return this.ensureClientConfigured(),new _o(new Wr(he.EMPTY_PATH,e),this)},e.prototype.runTransaction=function(e){var t=this;return k("Firestore.runTransaction",arguments,1),O("Firestore.runTransaction","function",1,e),this.ensureClientConfigured().transaction((function(n){return e(new So(t,n))}))},e.prototype.batch=function(){return this.ensureClientConfigured(),new To(this)},Object.defineProperty(e,"logLevel",{get:function(){switch(f()){case i.DEBUG:return"debug";case i.ERROR:return"error";case i.SILENT:return"silent";default:return g("Unknown log level: "+f())}},enumerable:!0,configurable:!0}),e.setLogLevel=function(e){switch(k("Firestore.setLogLevel",arguments,1),O("Firestore.setLogLevel","non-empty string",1,e),e){case"debug":d(i.DEBUG);break;case"error":d(i.ERROR);break;case"silent":d(i.SILENT);break;default:throw new T(S.INVALID_ARGUMENT,"Invalid log level: "+e)}},e.prototype._areTimestampsInSnapshotsEnabled=function(){return this._settings.timestampsInSnapshots},e}(),So=function(){function e(e,t){this._firestore=e,this._transaction=t}return e.prototype.get=function(e){var t=this;
1k("Transaction.get",arguments,1);var n=Lo("Transaction.get",e,this._firestore);return this._transaction.lookup([n._key]).then((function(e){if(!e||1!==e.length)return g("Mismatch in docs returned from document lookup.");var r=e[0];if(r instanceof Kt)return new Co(t._firestore,n._key,null,!1,!1);if(r instanceof Qt)return new Co(t._firestore,n._key,r,!1,!1);throw g("BatchGetDocumentsRequest returned unexpected document type: "+r.constructor.name)}))},e.prototype.set=function(e,t,n){M("Transaction.set",arguments,2,3);var r=Lo("Transaction.set",e,this._firestore),i=(n=ko("Transaction.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("Transaction.set",t,n.mergeFields):this._firestore._dataConverter.parseSetData("Transaction.set",t);return this._transaction.set(r._key,i),this},e.prototype.update=function(e,t,n){for(var r,i,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return"string"===typeof t||t instanceof Qi?(R("Transaction.update",arguments,3),r=Lo("Transaction.update",e,this._firestore),i=this._firestore._dataConverter.parseUpdateVarargs("Transaction.update",t,n,o)):(k("Transaction.update",arguments,2),r=Lo("Transaction.update",e,this._firestore),i=this._firestore._dataConverter.parseUpdateData("Transaction.update",t)),this._transaction.update(r._key,i),this},e.prototype.delete=function(e){k("Transaction.delete",arguments,1);var t=Lo("Transaction.delete",e,this._firestore);return this._transaction.delete(t._key),this},e}(),To=function(){function e(e){this._firestore=e,this._mutations=[],this._committed=!1}return e.prototype.set=function(e,t,n){M("WriteBatch.set",arguments,2,3),this.verifyNotCommitted();var r=Lo("WriteBatch.set",e,this._firestore),i=(n=ko("WriteBatch.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("WriteBatch.set",t,n.mergeFields):this._firestore._dataConverter.parseSetData("WriteBatch.set",t);return this._mutations=this._mutations.concat(i.toMutations(r._key,wt.NONE)),this},e.prototype.update=function(e,t,n){for(var r,i,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return this.verifyNotCommitted(),"string"===typeof t||t instanceof Qi?(R("WriteBatch.update",arguments,3),r=Lo("WriteBatch.update",e,this._firestore),i=this._firestore._dataConverter.parseUpdateVarargs("WriteBatch.update",t,n,o)):(k("WriteBatch.update",arguments,2),r=Lo("WriteBatch.update",e,this._firestore),i=this._firestore._dataConverter.parseUpdateData("WriteBatch.update",t)),this._mutations=this._mutations.concat(i.toMutations(r._key,wt.exists(!0))),this},e.prototype.delete=function(e){k("WriteBatch.delete",arguments,1),this.verifyNotCommitted();var t=Lo("WriteBatch.delete",e,this._firestore);return this._mutations=this._mutations.concat(new It(t._key,wt.NONE)),this},e.prototype.commit=function(){return a.__awaiter(this,void 0,void 0,(function(){return a.__generator(this,(function(e){return this.verifyNotCommitted(),this._committed=!0,this._mutations.length>0?[2,this._firestore.ensureClientConfigured().write(this._mutations)]:[2]}))}))},e.prototype.verifyNotCommitted=function(){if(this._committed)throw new T(S.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},e}(),Eo=function(){function e(e,t){this._key=e,this.firestore=t,this._firestoreClient=this.firestore.ensureClientConfigured()}return e.forPath=function(t,n){if(t.length%2!==0)throw new T(S.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+t.canonicalString()+" has "+t.length);return new e(new de(t),n)},Object.defineProperty(e.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return new Ao(this._key.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this._key.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.collection=function(e){if(k("DocumentReference.collection",arguments,1),O("DocumentReference.collection","non-empty string",1,e),!e)throw new T(S.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var t=he.fromString(e);
1return new Ao(this._key.path.child(t),this.firestore)},e.prototype.isEqual=function(t){if(!(t instanceof e))throw z("isEqual","DocumentReference",1,t);return this.firestore===t.firestore&&this._key.isEqual(t._key)},e.prototype.set=function(e,t){M("DocumentReference.set",arguments,1,2);var n=(t=ko("DocumentReference.set",t)).merge||t.mergeFields?this.firestore._dataConverter.parseMergeData("DocumentReference.set",e,t.mergeFields):this.firestore._dataConverter.parseSetData("DocumentReference.set",e);return this._firestoreClient.write(n.toMutations(this._key,wt.NONE))},e.prototype.update=function(e,t){for(var n,r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];return"string"===typeof e||e instanceof Qi?(R("DocumentReference.update",arguments,2),n=this.firestore._dataConverter.parseUpdateVarargs("DocumentReference.update",e,t,r)):(k("DocumentReference.update",arguments,1),n=this.firestore._dataConverter.parseUpdateData("DocumentReference.update",e)),this._firestoreClient.write(n.toMutations(this._key,wt.exists(!0)))},e.prototype.delete=function(){return k("DocumentReference.delete",arguments,0),this._firestoreClient.write([new It(this._key,wt.NONE)])},e.prototype.onSnapshot=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];M("DocumentReference.onSnapshot",arguments,1,4);var n,r={includeMetadataChanges:!1},i=0;"object"!==typeof e[i]||Ji(e[i])||(G("DocumentReference.onSnapshot",r=e[i],["includeMetadataChanges"]),q("DocumentReference.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++);var o={includeMetadataChanges:r.includeMetadataChanges};return Ji(e[i])?n=e[i]:(O("DocumentReference.onSnapshot","function",i,e[i]),P("DocumentReference.onSnapshot","function",i+1,e[i+1]),P("DocumentReference.onSnapshot","function",i+2,e[i+2]),n={next:e[i],error:e[i+1],complete:e[i+2]}),this.onSnapshotInternal(o,n)},e.prototype.onSnapshotInternal=function(e,t){var n=this,r=function(e){console.error("Uncaught Error in onSnapshot:",e)};t.error&&(r=t.error.bind(t));var i=new Ui({next:function(e){if(t.next){v(e.docs.size<=1,"Too many documents returned on a document query");var r=e.docs.get(n._key);t.next(new Co(n.firestore,n._key,r,e.fromCache,e.hasPendingWrites))}},error:r}),o=this._firestoreClient.listen(Wr.atPath(this._key.path),i,e);return function(){i.mute(),n._firestoreClient.unlisten(o)}},e.prototype.get=function(e){var t=this;return M("DocumentReference.get",arguments,0,1),Mo("DocumentReference.get",e),new Promise((function(n,r){e&&"cache"===e.source?t.firestore.ensureClientConfigured().getDocumentFromLocalCache(t._key).then((function(e){n(new Co(t.firestore,t._key,e,!0,e instanceof Qt&&e.hasLocalMutations))}),r):t.getViaSnapshotListener(n,r,e)}))},e.prototype.getViaSnapshotListener=function(e,t,n){var r=this.onSnapshotInternal({includeMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(i){r(),!i.exists&&i.metadata.fromCache?t(new T(S.UNAVAILABLE,"Failed to get document because the client is offline.")):i.exists&&i.metadata.fromCache&&n&&"server"===n.source?t(new T(S.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):e(i)},error:t})},e}(),Io=function(){function e(e,t){this.hasPendingWrites=e,this.fromCache=t}return e.prototype.isEqual=function(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache},e}(),Co=function(){function e(e,t,n,r,i){this._firestore=e,this._key=t,this._document=n,this._fromCache=r,this._hasPendingWrites=i}return e.prototype.data=function(e){return M("DocumentSnapshot.data",arguments,0,1),e=Ro("DocumentSnapshot.data",e),this._document?this.convertObject(this._document.data(),Ct.fromSnapshotOptions(e,this._firestore._areTimestampsInSnapshotsEnabled())):void 0},e.prototype.get=function(e,t){if(M("DocumentSnapshot.get",arguments,1,2),t=Ro("DocumentSnapshot.get",t),this._document){var n=this._document.data().field(mo("DocumentSnapshot.get",e));if(null!==n)return this.convertValue(n,Ct.fromSnapshotOptions(t,this._firestore._areTimestampsInSnapshotsEnabled()))}},Object.defineProperty(e.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ref",{get:function(){return new Eo(this._key,this._firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"exists",{get:function(){return null!==this._document},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"metadata",{get:function(){return new Io(this._hasPendingWrites,this._fromCache)},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){if(!(t instanceof e))throw z("isEqual","DocumentSnapshot",1,t);return this._firestore===t._firestore&&this._fromCache===t._fromCache&&this._key.isEqual(t._key)&&(null===this._document?null===t._document:this._document.isEqual(t._document))},e.prototype.convertObject=function(e,t){var n=this,r={};return e.forEach((function(e,i){r[e]=n.convertValue(i,t)})),r},e.prototype.convertValue=function(e,t){if(e instanceof Ft)return this.convertObject(e,t);if(e instanceof Bt)return this.convertArray(e,t);if(e instanceof qt){var n=e.value(t),r=this._firestore.ensureClientConfigured().databaseId();return e.databaseId.isEqual(r)||m("Document "+this._key.path+" contains a document reference within a different database ("+e.databaseId.projectId+"/"+e.databaseId.database+") which is not supported. It will be treated as a reference in the current database ("+r.projectId+"/"+r.database+") instead."),new Eo(n,this._firestore)}return e.value(t)},e.prototype.convertArray=function(e,t){var n=this;return e.internalValue.map((function(e){return n.convertValue(e,t)}))},e}(),Do=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a.__extends(t,e),t.prototype.data=function(t){var n=e.prototype.data.call(this,t);return v("object"===typeof n,"Document in a QueryDocumentSnapshot should exist"),n},t}(Co),_o=function(){function e(e,t){this._query=e,this.firestore=t}return e.prototype.where=function(t,n,r){if(k("Query.where",arguments,3),W("Query.where",3,r),"in"!==n&&"array-contains-any"!==n){var i=["<","<=","==",">=",">","array-contains"];B("Query.where",i,2,n)}var o,a=mo("Query.where",t),s=zr.fromString(n);
1if(a.isKeyField()){if(s===zr.ARRAY_CONTAINS||s===zr.ARRAY_CONTAINS_ANY)throw new T(S.INVALID_ARGUMENT,"Invalid Query. You can't perform '"+s.toString()+"' queries on FieldPath.documentId().");if(s===zr.IN){this.validateDisjunctiveFilterElements(r,s);for(var u=[],c=0,h=r;c<h.length;c++){var l=h[c];u.push(this.parseDocumentIdValue(l))}o=new Bt(u)}else o=this.parseDocumentIdValue(r)}else s!==zr.IN&&s!==zr.ARRAY_CONTAINS_ANY||this.validateDisjunctiveFilterElements(r,s),o=this.firestore._dataConverter.parseQueryValue("Query.where",r);var f=jr.create(a,s,o);return this.validateNewFilter(f),new e(this._query.addFilter(f),this.firestore)},e.prototype.orderBy=function(t,n){var r;if(M("Query.orderBy",arguments,1,2),P("Query.orderBy","non-empty string",2,n),void 0===n||"asc"===n)r=$r.ASCENDING;else{if("desc"!==n)throw new T(S.INVALID_ARGUMENT,"Function Query.orderBy() has unknown direction '"+n+"', expected 'asc' or 'desc'.");r=$r.DESCENDING}if(null!==this._query.startAt)throw new T(S.INVALID_ARGUMENT,"Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");if(null!==this._query.endAt)throw new T(S.INVALID_ARGUMENT,"Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");var i=mo("Query.orderBy",t),o=new ti(i,r);return this.validateNewOrderBy(o),new e(this._query.addOrderBy(o),this.firestore)},e.prototype.limit=function(t){if(k("Query.limit",arguments,1),O("Query.limit","number",1,t),t<=0)throw new T(S.INVALID_ARGUMENT,"Invalid Query. Query limit ("+t+") is invalid. Limit must be positive.");return new e(this._query.withLimit(t),this.firestore)},e.prototype.startAt=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];R("Query.startAt",arguments,1);var i=this.boundFromDocOrFields("Query.startAt",t,n,!0);return new e(this._query.withStartAt(i),this.firestore)},e.prototype.startAfter=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];R("Query.startAfter",arguments,1);var i=this.boundFromDocOrFields("Query.startAfter",t,n,!1);return new e(this._query.withStartAt(i),this.firestore)},e.prototype.endBefore=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];R("Query.endBefore",arguments,1);var i=this.boundFromDocOrFields("Query.endBefore",t,n,!0);return new e(this._query.withEndAt(i),this.firestore)},e.prototype.endAt=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];R("Query.endAt",arguments,1);var i=this.boundFromDocOrFields("Query.endAt",t,n,!1);return new e(this._query.withEndAt(i),this.firestore)},e.prototype.isEqual=function(t){if(!(t instanceof e))throw z("isEqual","Query",1,t);return this.firestore===t.firestore&&this._query.isEqual(t._query)},e.prototype.boundFromDocOrFields=function(e,t,n,r){if(W(e,1,t),t instanceof Co){if(n.length>0)throw new T(S.INVALID_ARGUMENT,"Too many arguments provided to "+e+"().");var i=t;if(!i.exists)throw new T(S.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+e+"().");return this.boundFromDocument(e,i._document,r)}var o=[t].concat(n);return this.boundFromFields(e,o,r)},e.prototype.boundFromDocument=function(e,t,n){for(var r=[],i=0,o=this._query.orderBy;i<o.length;i++){var a=o[i];if(a.field.isKeyField())r.push(new qt(this.firestore._databaseId,t.key));else{var s=t.field(a.field);if(s instanceof Pt)throw new T(S.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+a.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===s){var u=a.field.canonicalString();throw new T(S.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 ei(r,n)},e.prototype.boundFromFields=function(e,t,n){var r=this._query.explicitOrderBy;if(t.length>r.length)throw new T(S.INVALID_ARGUMENT,"Too many arguments provided to "+e+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var i=[],o=0;o<t.length;o++){var a=t[o];
1if(r[o].field.isKeyField()){if("string"!==typeof a)throw new T(S.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in "+e+"(), but got a "+typeof a);if(!this._query.isCollectionGroupQuery()&&-1!==a.indexOf("/"))throw new T(S.INVALID_ARGUMENT,"Invalid query. When querying a collection and ordering by FieldPath.documentId(), the value passed to "+e+"() must be a plain document ID, but '"+a+"' contains a slash.");var s=this._query.path.child(he.fromString(a));if(!de.isDocumentKey(s))throw new T(S.INVALID_ARGUMENT,"Invalid query. When querying a collection group and ordering by FieldPath.documentId(), the value passed to "+e+"() must result in a valid document path, but '"+s+"' is not because it contains an odd number of segments.");var u=new de(s);i.push(new qt(this.firestore._databaseId,u))}else{var c=this.firestore._dataConverter.parseQueryValue(e,a);i.push(c)}}return new ei(i,n)},e.prototype.onSnapshot=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];M("Query.onSnapshot",arguments,1,4);var n,r={},i=0;return"object"!==typeof e[i]||Ji(e[i])||(G("Query.onSnapshot",r=e[i],["includeMetadataChanges"]),q("Query.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++),Ji(e[i])?n=e[i]:(O("Query.onSnapshot","function",i,e[i]),P("Query.onSnapshot","function",i+1,e[i+1]),P("Query.onSnapshot","function",i+2,e[i+2]),n={next:e[i],error:e[i+1],complete:e[i+2]}),this.onSnapshotInternal(r,n)},e.prototype.onSnapshotInternal=function(e,t){var n=this,r=function(e){console.error("Uncaught Error in onSnapshot:",e)};t.error&&(r=t.error.bind(t));var i=new Ui({next:function(e){t.next&&t.next(new No(n.firestore,n._query,e))},error:r}),o=this.firestore.ensureClientConfigured(),a=o.listen(this._query,i,e);return function(){i.mute(),o.unlisten(a)}},e.prototype.get=function(e){var t=this;return M("Query.get",arguments,0,1),Mo("Query.get",e),new Promise((function(n,r){e&&"cache"===e.source?t.firestore.ensureClientConfigured().getDocumentsFromLocalCache(t._query).then((function(e){n(new No(t.firestore,t._query,e))}),r):t.getViaSnapshotListener(n,r,e)}))},e.prototype.getViaSnapshotListener=function(e,t,n){var r=this.onSnapshotInternal({includeMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(i){r(),i.metadata.fromCache&&n&&"server"===n.source?t(new T(S.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):e(i)},error:t})},e.prototype.parseDocumentIdValue=function(e){if("string"===typeof e){if(""===e)throw new T(S.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");if(!this._query.isCollectionGroupQuery()&&-1!==e.indexOf("/"))throw new T(S.INVALID_ARGUMENT,"Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '"+e+"' contains a '/' character.");var t=this._query.path.child(he.fromString(e));if(!de.isDocumentKey(t))throw new T(S.INVALID_ARGUMENT,"Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but '"+t+"' is not because it has an odd number of segments ("+t.length+").");return new qt(this.firestore._databaseId,new de(t))}if(e instanceof Eo){var n=e;return new qt(this.firestore._databaseId,n._key)}throw new T(S.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: "+K(e)+".")},e.prototype.validateDisjunctiveFilterElements=function(e,t){if(!Array.isArray(e)||0===e.length)throw new T(S.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for '"+t.toString()+"' filters.");if(e.length>10)throw new T(S.INVALID_ARGUMENT,"Invalid Query. '"+t.toString()+"' filters support a maximum of 10 elements in the value array.");if(e.indexOf(null)>=0)throw new T(S.INVALID_ARGUMENT,"Invalid Query. '"+t.toString()+"' filters cannot contain 'null' in the value array.");if(e.filter((function(e){return Number.isNaN(e)})).length>0)throw new T(S.INVALID_ARGUMENT,"Invalid Query. '"+t.toString()+"' filters cannot contain 'NaN' in the value array.")},e.prototype.validateNewFilter=function(e){if(e instanceof jr){var t=[zr.ARRAY_CONTAINS,zr.ARRAY_CONTAINS_ANY],n=[zr.IN,zr.ARRAY_CONTAINS_ANY],r=t.indexOf(e.op)>=0,i=n.indexOf(e.op)>=0;if(e.isInequality()){var o=this._query.getInequalityFilterField();if(null!==o&&!o.isEqual(e.field))throw new T(S.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+o.toString()+"' and '"+e.field.toString()+"'");var a=this._query.getFirstOrderByField();null!==a&&this.validateOrderByAndInequalityMatch(e.field,a)}else if(i||r){var s=null;if(i&&(s=this._query.findFilterOperator(n)),null===s&&r&&(s=this._query.findFilterOperator(t)),null!=s)throw s===e.op?new T(S.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '"+e.op.toString()+"' filter."):new T(S.INVALID_ARGUMENT,"Invalid query. You cannot use '"+e.op.toString()+"' filters with '"+s.toString()+"' filters.")}}},e.prototype.validateNewOrderBy=function(e){if(null===this._query.getFirstOrderByField()){var t=this._query.getInequalityFilterField();null!==t&&this.validateOrderByAndInequalityMatch(t,e.field)}},e.prototype.validateOrderByAndInequalityMatch=function(e,t){if(!t.isEqual(e))throw new T(S.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+e.toString()+"' and so you must also use '"+e.toString()+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+t.toString()+"' instead.")},e}(),No=function(){function e(e,t,n){this._firestore=e,this._originalQuery=t,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new Io(n.hasPendingWrites,n.fromCache)}return Object.defineProperty(e.prototype,"docs",{get:function(){var e=[];return this.forEach((function(t){return e.push(t)})),e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"empty",{get:function(){return this._snapshot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this._snapshot.docs.size},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e,t){var n=this;
1M("QuerySnapshot.forEach",arguments,1,2),O("QuerySnapshot.forEach","function",1,e),this._snapshot.docs.forEach((function(r){e.call(t,n.convertToDocumentImpl(r))}))},Object.defineProperty(e.prototype,"query",{get:function(){return new _o(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),e.prototype.docChanges=function(e){e&&(G("QuerySnapshot.docChanges",e,["includeMetadataChanges"]),q("QuerySnapshot.docChanges","boolean","includeMetadataChanges",e.includeMetadataChanges));var t=!(!e||!e.includeMetadataChanges);if(t&&this._snapshot.excludesMetadataChanges)throw new T(S.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t,n){if(n.oldDocs.isEmpty()){var r,i=0;return n.docChanges.map((function(t){var o=new Do(e,t.doc.key,t.doc,n.fromCache,n.mutatedKeys.has(t.doc.key));return v(t.type===Dr.Added,"Invalid event type for first snapshot"),v(!r||n.query.docComparator(r,t.doc)<0,"Got added events in wrong order"),r=t.doc,{type:"added",doc:o,oldIndex:-1,newIndex:i++}}))}var o=n.oldDocs;return n.docChanges.filter((function(e){return t||e.type!==Dr.Metadata})).map((function(t){var r=new Do(e,t.doc.key,t.doc,n.fromCache,n.mutatedKeys.has(t.doc.key)),i=-1,a=-1;return t.type!==Dr.Added&&(v((i=o.indexOf(t.doc.key))>=0,"Index for document not found"),o=o.delete(t.doc.key)),t.type!==Dr.Removed&&(a=(o=o.add(t.doc)).indexOf(t.doc.key)),{type:Oo(t.type),doc:r,oldIndex:i,newIndex:a}}))}(this._firestore,t,this._snapshot),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges},e.prototype.isEqual=function(t){if(!(t instanceof e))throw z("isEqual","QuerySnapshot",1,t);return this._firestore===t._firestore&&this._originalQuery.isEqual(t._originalQuery)&&this._snapshot.isEqual(t._snapshot)},e.prototype.convertToDocumentImpl=function(e){return new Do(this._firestore,e.key,e,this.metadata.fromCache,this._snapshot.mutatedKeys.has(e.key))},e}();a.__spreadArrays(["length","forEach","map"],"undefined"!==typeof Symbol?[Symbol.iterator]:[]).forEach((function(e){try{Object.defineProperty(No.prototype.docChanges,e,{get:function(){return function(){throw new T(S.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}()}})}catch(t){}}));var Ao=function(e){function t(t,n){var r=e.call(this,Wr.atPath(t),n)||this;if(t.length%2!==1)throw new T(S.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+t.canonicalString()+" has "+t.length);return r}return a.__extends(t,e),Object.defineProperty(t.prototype,"id",{get:function(){return this._query.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){var e=this._query.path.popLast();return e.isEmpty()?null:new Eo(new de(e),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this._query.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.doc=function(e){if(M("CollectionReference.doc",arguments,0,1),0===arguments.length&&(e=Y.newId()),O("CollectionReference.doc","non-empty string",1,e),""===e)throw new T(S.INVALID_ARGUMENT,"Document path must be a non-empty string");var t=he.fromString(e);return Eo.forPath(this._query.path.child(t),this.firestore)},t.prototype.add=function(e){k("CollectionReference.add",arguments,1),O("CollectionReference.add","object",1,e);var t=this.doc();return t.set(e).then((function(){return t}))},t}(_o);function ko(e,t){if(void 0===t)return{merge:!1};if(G(e,t,["merge","mergeFields"]),q(e,"boolean","merge",t.merge),V(e,"mergeFields","a string or a FieldPath",t.mergeFields,(function(e){return"string"===typeof e||e instanceof Qi})),void 0!==t.mergeFields&&void 0!==t.merge)throw new T(S.INVALID_ARGUMENT,"Invalid options passed to function "+e+'(): You cannot specify both "merge" and "mergeFields".');return t}function Ro(e,t){return void 0===t?{}:(G(e,t,["serverTimestamps"]),F(e,0,"serverTimestamps",t.serverTimestamps,["estimate","previous","none"]),t)}function Mo(e,t){P(e,"object",1,t),t&&(G(e,t,["source"]),F(e,0,"source",t.source,["default","server","cache"]))}function Lo(e,t,n){if(t instanceof Eo){if(t.firestore!==n)throw new T(S.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return t}throw z(e,"DocumentReference",1,t)}function Oo(e){switch(e){case Dr.Added:return"added";case Dr.Modified:case Dr.Metadata:return"modified";case Dr.Removed:return"removed";default:return g("Unknown change type: "+e)}}var Po=E(bo,"Use firebase.firestore() instead."),xo=E(So,"Use firebase.firestore().runTransaction() instead."),qo=E(To,"Use firebase.firestore().batch() instead."),Vo=E(Eo,"Use firebase.firestore().doc() instead."),Fo=E(Co),Bo=E(Do),Uo=E(_o),Qo=E(No),Ko=E(Ao,"Use firebase.firestore().collection() instead."),Wo={Firestore:Po,GeoPoint:Kr,Timestamp:Te,Blob:re,Transaction:xo,WriteBatch:qo,DocumentReference:Vo,DocumentSnapshot:Fo,Query:Uo,QueryDocumentSnapshot:Bo,QuerySnapsh
1ot:Qo,CollectionReference:Ko,FieldPath:Qi,FieldValue:io,setLogLevel:bo.setLogLevel,CACHE_SIZE_UNLIMITED:vo};function Go(e){e.INTERNAL.registerService("firestore",(function(e){return new bo(e)}),function(e){v(e&&"object"===typeof e,"shallowCopy() expects object parameter.");var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}(Wo))}var zo=function(){function e(){}return e.prototype.addCallback=function(e){},e.prototype.shutdown=function(){},e}(),jo="ConnectivityMonitor",Ho=function(){function e(){var e=this;this.networkAvailableListener=function(){return e.onNetworkAvailable()},this.networkUnavailableListener=function(){return e.onNetworkUnavailable()},this.callbacks=[],this.configureNetworkMonitoring()}return e.prototype.addCallback=function(e){this.callbacks.push(e)},e.prototype.shutdown=function(){window.removeEventListener("online",this.networkAvailableListener),window.removeEventListener("offline",this.networkUnavailableListener)},e.prototype.configureNetworkMonitoring=function(){window.addEventListener("online",this.networkAvailableListener),window.addEventListener("offline",this.networkUnavailableListener)},e.prototype.onNetworkAvailable=function(){p(jo,"Network connectivity changed: AVAILABLE");for(var e=0,t=this.callbacks;e<t.length;e++){(0,t[e])(0)}},e.prototype.onNetworkUnavailable=function(){p(jo,"Network connectivity changed: UNAVAILABLE");for(var e=0,t=this.callbacks;e<t.length;e++){(0,t[e])(1)}},e.isAvailable=function(){return"undefined"!==typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener},e}(),Yo=function(){function e(e){this.sendFn=e.sendFn,this.closeFn=e.closeFn}return e.prototype.onOpen=function(e){v(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=e},e.prototype.onClose=function(e){v(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=e},e.prototype.onMessage=function(e){v(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=e},e.prototype.close=function(){this.closeFn()},e.prototype.send=function(e){this.sendFn(e)},e.prototype.callOnOpen=function(){v(void 0!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},e.prototype.callOnClose=function(e){v(void 0!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(e)},e.prototype.callOnMessage=function(e){v(void 0!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(e)},e}(),Jo="Connection",Xo={BatchGetDocuments:"batchGet",Commit:"commit"},Zo="gl-js/ fire/"+h,$o=function(){function e(e){this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.baseUrl=t+"://"+e.host,this.forceLongPolling=e.forceLongPolling}return e.prototype.modifyHeadersForRequest=function(e,t){if(t)for(var n in t.authHeaders)t.authHeaders.hasOwnProperty(n)&&(e[n]=t.authHeaders[n]);e["X-Goog-Api-Client"]=Zo},e.prototype.invokeRPC=function(e,t,n){var r=this,i=this.makeUrl(e);return new Promise((function(o,s){var u=new c.XhrIo;u.listenOnce(c.EventType.COMPLETE,(function(){try{switch(u.getLastErrorCode()){case c.ErrorCode.NO_ERROR:var t=u.getResponseJson();p(Jo,"XHR received:",JSON.stringify(t)),o(t);break;case c.ErrorCode.TIMEOUT:p(Jo,'RPC "'+e+'" timed out'),s(new T(S.DEADLINE_EXCEEDED,"Request time out"));break;case c.ErrorCode.HTTP_ERROR:var n=u.getStatus();if(p(Jo,'RPC "'+e+'" failed with status:',n,"response text:",u.getResponseText()),n>0){var r=u.getResponseJson().error;if(r&&r.status&&r.message){var i=function(e){var t=e.toLowerCase().replace("_","-");return Object.values(S).indexOf(t)>=0?t:S.UNKNOWN}(r.status);s(new T(i,r.message))}else s(new T(S.UNKNOWN,"Server responded with status "+u.getStatus()))}else p(Jo,'RPC "'+e+'" failed'),s(new T(S.UNAVAILABLE,"Connection failed."));break;default:g('RPC "'+e+'" failed with unanticipated webchannel error '+u.getLastErrorCode()+": "+u.getLastError()+", giving up.")}}finally{p(Jo,'RPC "'+e+'" completed.')}}));var h=a.__assign({},t);delete h.database;var l=JSON.stringify(h);p(Jo,"XHR sending: ",i+" "+l);var f={"Content-Type":"text/plain"};r.modifyHeadersForRequest(f,n),u.send(i,"POST",l,f,15)}))},e.prototype.invokeStreamingRPC=function(e,t,n){return this.invokeRPC(e,t,n)},e.prototype.openStream=function(e,t){var n=[this.baseUrl,"/","google.firestore.v1.Firestore","/",e,"/channel"],r=c.createWebChannelTransport(),i={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database}
1,sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling};this.modifyHeadersForRequest(i.initMessageHeaders,t),u.isReactNative()||(i.httpHeadersOverwriteParam="$httpHeaders");var o=n.join("");p(Jo,"Creating WebChannel: "+o+" "+i);var a=r.createWebChannel(o,i),s=!1,h=!1,l=new Yo({sendFn:function(e){h?p(Jo,"Not sending because WebChannel is closed:",e):(s||(p(Jo,"Opening WebChannel transport."),a.open(),s=!0),p(Jo,"WebChannel sending:",e),a.send(e))},closeFn:function(){return a.close()}}),f=function(e,t){a.listen(e,(function(e){try{t(e)}catch(n){setTimeout((function(){throw n}),0)}}))};return f(c.WebChannel.EventType.OPEN,(function(){h||p(Jo,"WebChannel transport opened.")})),f(c.WebChannel.EventType.CLOSE,(function(){h||(h=!0,p(Jo,"WebChannel transport closed"),l.callOnClose())})),f(c.WebChannel.EventType.ERROR,(function(e){h||(h=!0,p(Jo,"WebChannel transport errored:",e),l.callOnClose(new T(S.UNAVAILABLE,"The operation could not be completed")))})),f(c.WebChannel.EventType.MESSAGE,(function(e){if(!h){var t=e.data[0];v(!!t,"Got a webchannel message without data.");var n=t,r=n.error||n[0]&&n[0].error;if(r){p(Jo,"WebChannel received error:",r);var i=r.status,o=function(e){var t=Sr[e];if(void 0!==t)return Ir(t)}(i),s=r.message;void 0===o&&(o=S.INTERNAL,s="Unknown error status: "+i+" with message "+r.message),h=!0,l.callOnClose(new T(o,s)),a.close()}else p(Jo,"WebChannel received:",t),l.callOnMessage(t)}})),setTimeout((function(){l.callOnOpen()}),0),l},e.prototype.makeUrl=function(e){var t=Xo[e];v(void 0!==t,"Unknown REST mapping for: "+e);var n=[this.baseUrl,"/","v1"];return n.push("/projects/"),n.push(this.databaseId.projectId),n.push("/databases/"),n.push(this.databaseId.database),n.push("/documents"),n.push(":"),n.push(t),n.join("")},e}(),ea=function(){function e(){this.emptyByteString="",this.base64Available="undefined"!==typeof atob}return Object.defineProperty(e.prototype,"document",{get:function(){return"undefined"!==typeof document?document:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"window",{get:function(){return"undefined"!==typeof window?window:null},enumerable:!0,configurable:!0}),e.prototype.loadConnection=function(e){return Promise.resolve(new $o(e))},e.prototype.newConnectivityMonitor=function(){return Ho.isAvailable()?new Ho:new zo},e.prototype.newSerializer=function(e){return new mi(e,{useProto3Json:!0})},e.prototype.formatJSON=function(e){return JSON.stringify(e)},e.prototype.atob=function(e){return atob(e)},e.prototype.btoa=function(e){return btoa(e)},e}();function ta(e){Go(e)}w.setPlatform(new ea),ta(o),t.registerFirestore=ta}).call(this,n("8oxB"))}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.