-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfirebase.js
More file actions
1 lines (1 loc) · 836 KB
/
firebase.js
File metadata and controls
1 lines (1 loc) · 836 KB
1
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.firebase=t()}(this,function(){"use strict";!function(e){if(!e.fetch){var t={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};if(t.arrayBuffer)var n=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],r=function(e){return e&&DataView.prototype.isPrototypeOf(e)},i=ArrayBuffer.isView||function(e){return e&&n.indexOf(Object.prototype.toString.call(e))>-1};h.prototype.append=function(e,t){e=s(e),t=u(t);var n=this.map[e];this.map[e]=n?n+","+t:t},h.prototype.delete=function(e){delete this.map[s(e)]},h.prototype.get=function(e){return e=s(e),this.has(e)?this.map[e]:null},h.prototype.has=function(e){return this.map.hasOwnProperty(s(e))},h.prototype.set=function(e,t){this.map[s(e)]=u(t)},h.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},h.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),c(e)},h.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),c(e)},h.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),c(e)},t.iterable&&(h.prototype[Symbol.iterator]=h.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];y.prototype.clone=function(){return new y(this,{body:this._bodyInit})},m.call(y.prototype),m.call(v.prototype),v.prototype.clone=function(){return new v(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},v.error=function(){var e=new v(null,{status:0,statusText:""});return e.type="error",e};var a=[301,302,303,307,308];v.redirect=function(e,t){if(-1===a.indexOf(t))throw new RangeError("Invalid status code");return new v(null,{status:t,headers:{location:e}})},e.Headers=h,e.Request=y,e.Response=v,e.fetch=function(e,n){return new Promise(function(r,i){var o=new y(e,n),a=new XMLHttpRequest;a.onload=function(){var e,t,n={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var n=e.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();t.append(r,i)}}),t)};n.url="responseURL"in a?a.responseURL:n.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;r(new v(i,n))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&t.blob&&(a.responseType="blob"),o.headers.forEach(function(e,t){a.setRequestHeader(t,e)}),a.send(void 0===o._bodyInit?null:o._bodyInit)})},e.fetch.polyfill=!0}function s(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function c(e){var n={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t.iterable&&(n[Symbol.iterator]=function(){return n}),n}function h(e){this.map={},e instanceof h?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function l(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function d(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function f(e){var t=new FileReader,n=d(t);return t.readAsArrayBuffer(e),n}function p(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,e)if("string"==typeof e)this._bodyText=e;else if(t.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(t.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(t.arrayBuffer&&t.blob&&r(e))this._bodyArrayBuffer=p(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!t.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(e)&&!i(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=p(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var e=l(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?l(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(f)}),this.text=function(){var e,t,n,r=l(this);if(r)return r;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=d(t),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},t.formData&&(this.formData=function(){return this.text().then(g)}),this.json=function(){return this.text().then(JSON.parse)},this}function y(e,t){var n,r,i=(t=t||{}).body;if(e instanceof y){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new h(e.headers)),this.method=e.method,this.mode=e.mode,i||null==e._bodyInit||(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"omit",!t.headers&&this.headers||(this.headers=new h(t.headers)),this.method=(n=t.method||this.method||"GET",r=n.toUpperCase(),o.indexOf(r)>-1?r:n),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function g(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function v(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}}("undefined"!=typeof self?self:void 0);var setTimeoutFunc=setTimeout;function noop(){}function bind(e,t){return function(){e.apply(t,arguments)}}function Promise$1(e){if(!(this instanceof Promise$1))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],doResolve(e,this)}function handle(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,Promise$1._immediateFn(function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var r;try{r=n(e._value)}catch(e){return void reject(t.promise,e)}resolve(t.promise,r)}else(1===e._state?resolve:reject)(t.promise,e._value)})):e._deferreds.push(t)}function resolve(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof Promise$1)return e._state=3,e._value=t,void finale(e);if("function"==typeof n)return void doResolve(bind(n,t),e)}e._state=1,e._value=t,finale(e)}catch(t){reject(e,t)}}function reject(e,t){e._state=2,e._value=t,finale(e)}function finale(e){2===e._state&&0===e._deferreds.length&&Promise$1._immediateFn(function(){e._handled||Promise$1._unhandledRejectionFn(e._value)});for(var t=0,n=e._deferreds.length;t<n;t++)handle(e,e._deferreds[t]);e._deferreds=null}function Handler(e,t,n){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=n}function doResolve(e,t){var n=!1;try{e(function(e){n||(n=!0,resolve(t,e))},function(e){n||(n=!0,reject(t,e))})}catch(e){if(n)return;n=!0,reject(t,e)}}Promise$1.prototype.catch=function(e){return this.then(null,e)},Promise$1.prototype.then=function(e,t){var n=new this.constructor(noop);return handle(this,new Handler(e,t,n)),n},Promise$1.prototype.finally=function(e){var t=this.constructor;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){return t.reject(n)})})},Promise$1.all=function(e){return new Promise$1(function(t,n){if(!e||void 0===e.length)throw new TypeError("Promise.all accepts an array");var r=Array.prototype.slice.call(e);if(0===r.length)return t([]);var i=r.length;function o(e,a){try{if(a&&("object"==typeof a||"function"==typeof a)){var s=a.then;if("function"==typeof s)return void s.call(a,function(t){o(e,t)},n)}r[e]=a,0==--i&&t(r)}catch(e){n(e)}}for(var a=0;a<r.length;a++)o(a,r[a])})},Promise$1.resolve=function(e){return e&&"object"==typeof e&&e.constructor===Promise$1?e:new Promise$1(function(t){t(e)})},Promise$1.reject=function(e){return new Promise$1(function(t,n){n(e)})},Promise$1.race=function(e){return new Promise$1(function(t,n){for(var r=0,i=e.length;r<i;r++)e[r].then(t,n)})},Promise$1._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){setTimeoutFunc(e,0)},Promise$1._unhandledRejectionFn=function(e){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var globalNS=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}globalNS.Promise||(globalNS.Promise=Promise$1);var _global=createCommonjsModule(function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)}),_core=createCommonjsModule(function(e){var t=e.exports={version:"2.5.5"};"number"==typeof __e&&(__e=t)}),_core_1=_core.version,_isObject=function(e){return"object"==typeof e?null!==e:"function"==typeof e},_anObject=function(e){if(!_isObject(e))throw TypeError(e+" is not an object!");return e},_fails=function(e){try{return!!e()}catch(e){return!0}},_descriptors=!_fails(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),document$1=_global.document,is=_isObject(document$1)&&_isObject(document$1.createElement),_domCreate=function(e){return is?document$1.createElement(e):{}},_ie8DomDefine=!_descriptors&&!_fails(function(){return 7!=Object.defineProperty(_domCreate("div"),"a",{get:function(){return 7}}).a}),_toPrimitive=function(e,t){if(!_isObject(e))return e;var n,r;if(t&&"function"==typeof(n=e.toString)&&!_isObject(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!_isObject(r=n.call(e)))return r;if(!t&&"function"==typeof(n=e.toString)&&!_isObject(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")},dP=Object.defineProperty,f=_descriptors?Object.defineProperty:function(e,t,n){if(_anObject(e),t=_toPrimitive(t,!0),_anObject(n),_ie8DomDefine)try{return dP(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e},_objectDp={f:f},_propertyDesc=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},_hide=_descriptors?function(e,t,n){return _objectDp.f(e,t,_propertyDesc(1,n))}:function(e,t,n){return e[t]=n,e},hasOwnProperty={}.hasOwnProperty,_has=function(e,t){return hasOwnProperty.call(e,t)},id=0,px=Math.random(),_uid=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++id+px).toString(36))},_redefine=createCommonjsModule(function(e){var t=_uid("src"),n=Function.toString,r=(""+n).split("toString");_core.inspectSource=function(e){return n.call(e)},(e.exports=function(e,n,i,o){var a="function"==typeof i;a&&(_has(i,"name")||_hide(i,"name",n)),e[n]!==i&&(a&&(_has(i,t)||_hide(i,t,e[n]?""+e[n]:r.join(String(n)))),e===_global?e[n]=i:o?e[n]?e[n]=i:_hide(e,n,i):(delete e[n],_hide(e,n,i)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[t]||n.call(this)})}),_aFunction=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e},_ctx=function(e,t,n){if(_aFunction(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}},PROTOTYPE="prototype",$export=function(e,t,n){var r,i,o,a,s=e&$export.F,u=e&$export.G,c=e&$export.S,h=e&$export.P,l=e&$export.B,d=u?_global:c?_global[t]||(_global[t]={}):(_global[t]||{})[PROTOTYPE],f=u?_core:_core[t]||(_core[t]={}),p=f[PROTOTYPE]||(f[PROTOTYPE]={});for(r in u&&(n=t),n)o=((i=!s&&d&&void 0!==d[r])?d:n)[r],a=l&&i?_ctx(o,_global):h&&"function"==typeof o?_ctx(Function.call,o):o,d&&_redefine(d,r,o,e&$export.U),f[r]!=o&&_hide(f,r,a),h&&p[r]!=o&&(p[r]=o)};_global.core=_core,$export.F=1,$export.G=2,$export.S=4,$export.P=8,$export.B=16,$export.W=32,$export.U=64,$export.R=128;var _export=$export,toString={}.toString,_cof=function(e){return toString.call(e).slice(8,-1)},_iobject=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==_cof(e)?e.split(""):Object(e)},_defined=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e},_toObject=function(e){return Object(_defined(e))},ceil=Math.ceil,floor=Math.floor,_toInteger=function(e){return isNaN(e=+e)?0:(e>0?floor:ceil)(e)},min=Math.min,_toLength=function(e){return e>0?min(_toInteger(e),9007199254740991):0},_isArray=Array.isArray||function(e){return"Array"==_cof(e)},SHARED="__core-js_shared__",store=_global[SHARED]||(_global[SHARED]={}),_shared=function(e){return store[e]||(store[e]={})},_wks=createCommonjsModule(function(e){var t=_shared("wks"),n=_global.Symbol,r="function"==typeof n;(e.exports=function(e){return t[e]||(t[e]=r&&n[e]||(r?n:_uid)("Symbol."+e))}).store=t}),SPECIES=_wks("species"),_arraySpeciesConstructor=function(e){var t;return _isArray(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!_isArray(t.prototype)||(t=void 0),_isObject(t)&&null===(t=t[SPECIES])&&(t=void 0)),void 0===t?Array:t},_arraySpeciesCreate=function(e,t){return new(_arraySpeciesConstructor(e))(t)},_arrayMethods=function(e,t){var n=1==e,r=2==e,i=3==e,o=4==e,a=6==e,s=5==e||a,u=t||_arraySpeciesCreate;return function(t,c,h){for(var l,d,f=_toObject(t),p=_iobject(f),m=_ctx(c,h,3),y=_toLength(p.length),g=0,v=n?u(t,y):r?u(t,0):void 0;y>g;g++)if((s||g in p)&&(d=m(l=p[g],g,f),e))if(n)v[g]=d;else if(d)switch(e){case 3:return!0;case 5:return l;case 6:return g;case 2:v.push(l)}else if(o)return!1;return a?-1:i||o?o:v}},UNSCOPABLES=_wks("unscopables"),ArrayProto=Array.prototype;void 0==ArrayProto[UNSCOPABLES]&&_hide(ArrayProto,UNSCOPABLES,{});var _addToUnscopables=function(e){ArrayProto[UNSCOPABLES][e]=!0},$find=_arrayMethods(5),KEY="find",forced=!0;KEY in[]&&Array(1)[KEY](function(){forced=!1}),_export(_export.P+_export.F*forced,"Array",{find:function(e){return $find(this,e,arguments.length>1?arguments[1]:void 0)}}),_addToUnscopables(KEY);var find=_core.Array.find,$find$1=_arrayMethods(6),KEY$1="findIndex",forced$1=!0;KEY$1 in[]&&Array(1)[KEY$1](function(){forced$1=!1}),_export(_export.P+_export.F*forced$1,"Array",{findIndex:function(e){return $find$1(this,e,arguments.length>1?arguments[1]:void 0)}}),_addToUnscopables(KEY$1);var findIndex=_core.Array.findIndex,_toIobject=function(e){return _iobject(_defined(e))},max=Math.max,min$1=Math.min,_toAbsoluteIndex=function(e,t){return(e=_toInteger(e))<0?max(e+t,0):min$1(e,t)},_arrayIncludes=function(e){return function(t,n,r){var i,o=_toIobject(t),a=_toLength(o.length),s=_toAbsoluteIndex(r,a);if(e&&n!=n){for(;a>s;)if((i=o[s++])!=i)return!0}else for(;a>s;s++)if((e||s in o)&&o[s]===n)return e||s||0;return!e&&-1}},shared=_shared("keys"),_sharedKey=function(e){return shared[e]||(shared[e]=_uid(e))},arrayIndexOf=_arrayIncludes(!1),IE_PROTO=_sharedKey("IE_PROTO"),_objectKeysInternal=function(e,t){var n,r=_toIobject(e),i=0,o=[];for(n in r)n!=IE_PROTO&&_has(r,n)&&o.push(n);for(;t.length>i;)_has(r,n=t[i++])&&(~arrayIndexOf(o,n)||o.push(n));return o},_enumBugKeys="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),_objectKeys=Object.keys||function(e){return _objectKeysInternal(e,_enumBugKeys)},f$1=Object.getOwnPropertySymbols,_objectGops={f:f$1},f$2={}.propertyIsEnumerable,_objectPie={f:f$2},$assign=Object.assign,_objectAssign=!$assign||_fails(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=$assign({},e)[n]||Object.keys($assign({},t)).join("")!=r})?function(e,t){for(var n=_toObject(e),r=arguments.length,i=1,o=_objectGops.f,a=_objectPie.f;r>i;)for(var s,u=_iobject(arguments[i++]),c=o?_objectKeys(u).concat(o(u)):_objectKeys(u),h=c.length,l=0;h>l;)a.call(u,s=c[l++])&&(n[s]=u[s]);return n}:$assign;_export(_export.S+_export.F,"Object",{assign:_objectAssign});var assign=_core.Object.assign,MATCH=_wks("match"),_isRegexp=function(e){var t;return _isObject(e)&&(void 0!==(t=e[MATCH])?!!t:"RegExp"==_cof(e))},_stringContext=function(e,t,n){if(_isRegexp(t))throw TypeError("String#"+n+" doesn't accept regex!");return String(_defined(e))},MATCH$1=_wks("match"),_failsIsRegexp=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[MATCH$1]=!1,!"/./"[e](t)}catch(e){}}return!0},STARTS_WITH="startsWith",$startsWith=""[STARTS_WITH];_export(_export.P+_export.F*_failsIsRegexp(STARTS_WITH),"String",{startsWith:function(e){var t=_stringContext(this,e,STARTS_WITH),n=_toLength(Math.min(arguments.length>1?arguments[1]:void 0,t.length)),r=String(e);return $startsWith?$startsWith.call(t,r,n):t.slice(n,n+r.length)===r}});var startsWith=_core.String.startsWith,_stringRepeat=function(e){var t=String(_defined(this)),n="",r=_toInteger(e);if(r<0||r==1/0)throw RangeError("Count can't be negative");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(n+=t);return n};_export(_export.P,"String",{repeat:_stringRepeat});var repeat=_core.String.repeat,_meta=createCommonjsModule(function(e){var t=_uid("meta"),n=_objectDp.f,r=0,i=Object.isExtensible||function(){return!0},o=!_fails(function(){return i(Object.preventExtensions({}))}),a=function(e){n(e,t,{value:{i:"O"+ ++r,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,n){if(!_isObject(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!_has(e,t)){if(!i(e))return"F";if(!n)return"E";a(e)}return e[t].i},getWeak:function(e,n){if(!_has(e,t)){if(!i(e))return!0;if(!n)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&i(e)&&!_has(e,t)&&a(e),e}}}),_meta_1=_meta.KEY,_meta_2=_meta.NEED,_meta_3=_meta.fastKey,_meta_4=_meta.getWeak,_meta_5=_meta.onFreeze,def=_objectDp.f,TAG=_wks("toStringTag"),_setToStringTag=function(e,t,n){e&&!_has(e=n?e:e.prototype,TAG)&&def(e,TAG,{configurable:!0,value:t})},f$3=_wks,_wksExt={f:f$3},_library=!1,defineProperty=_objectDp.f,_wksDefine=function(e){var t=_core.Symbol||(_core.Symbol=_library?{}:_global.Symbol||{});"_"==e.charAt(0)||e in t||defineProperty(t,e,{value:_wksExt.f(e)})},_enumKeys=function(e){var t=_objectKeys(e),n=_objectGops.f;if(n)for(var r,i=n(e),o=_objectPie.f,a=0;i.length>a;)o.call(e,r=i[a++])&&t.push(r);return t},_objectDps=_descriptors?Object.defineProperties:function(e,t){_anObject(e);for(var n,r=_objectKeys(t),i=r.length,o=0;i>o;)_objectDp.f(e,n=r[o++],t[n]);return e},document$1$1=_global.document,_html=document$1$1&&document$1$1.documentElement,IE_PROTO$1=_sharedKey("IE_PROTO"),Empty=function(){},PROTOTYPE$1="prototype",createDict=function(){var e,t=_domCreate("iframe"),n=_enumBugKeys.length;for(t.style.display="none",_html.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),createDict=e.F;n--;)delete createDict[PROTOTYPE$1][_enumBugKeys[n]];return createDict()},_objectCreate=Object.create||function(e,t){var n;return null!==e?(Empty[PROTOTYPE$1]=_anObject(e),n=new Empty,Empty[PROTOTYPE$1]=null,n[IE_PROTO$1]=e):n=createDict(),void 0===t?n:_objectDps(n,t)},hiddenKeys=_enumBugKeys.concat("length","prototype"),f$4=Object.getOwnPropertyNames||function(e){return _objectKeysInternal(e,hiddenKeys)},_objectGopn={f:f$4},gOPN=_objectGopn.f,toString$1={}.toString,windowNames="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],getWindowNames=function(e){try{return gOPN(e)}catch(e){return windowNames.slice()}},f$5=function(e){return windowNames&&"[object Window]"==toString$1.call(e)?getWindowNames(e):gOPN(_toIobject(e))},_objectGopnExt={f:f$5},gOPD=Object.getOwnPropertyDescriptor,f$6=_descriptors?gOPD:function(e,t){if(e=_toIobject(e),t=_toPrimitive(t,!0),_ie8DomDefine)try{return gOPD(e,t)}catch(e){}if(_has(e,t))return _propertyDesc(!_objectPie.f.call(e,t),e[t])},_objectGopd={f:f$6},META=_meta.KEY,gOPD$1=_objectGopd.f,dP$1=_objectDp.f,gOPN$1=_objectGopnExt.f,$Symbol=_global.Symbol,$JSON=_global.JSON,_stringify=$JSON&&$JSON.stringify,PROTOTYPE$2="prototype",HIDDEN=_wks("_hidden"),TO_PRIMITIVE=_wks("toPrimitive"),isEnum={}.propertyIsEnumerable,SymbolRegistry=_shared("symbol-registry"),AllSymbols=_shared("symbols"),OPSymbols=_shared("op-symbols"),ObjectProto=Object[PROTOTYPE$2],USE_NATIVE="function"==typeof $Symbol,QObject=_global.QObject,setter=!QObject||!QObject[PROTOTYPE$2]||!QObject[PROTOTYPE$2].findChild,setSymbolDesc=_descriptors&&_fails(function(){return 7!=_objectCreate(dP$1({},"a",{get:function(){return dP$1(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=gOPD$1(ObjectProto,t);r&&delete ObjectProto[t],dP$1(e,t,n),r&&e!==ObjectProto&&dP$1(ObjectProto,t,r)}:dP$1,wrap=function(e){var t=AllSymbols[e]=_objectCreate($Symbol[PROTOTYPE$2]);return t._k=e,t},isSymbol=USE_NATIVE&&"symbol"==typeof $Symbol.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof $Symbol},$defineProperty=function(e,t,n){return e===ObjectProto&&$defineProperty(OPSymbols,t,n),_anObject(e),t=_toPrimitive(t,!0),_anObject(n),_has(AllSymbols,t)?(n.enumerable?(_has(e,HIDDEN)&&e[HIDDEN][t]&&(e[HIDDEN][t]=!1),n=_objectCreate(n,{enumerable:_propertyDesc(0,!1)})):(_has(e,HIDDEN)||dP$1(e,HIDDEN,_propertyDesc(1,{})),e[HIDDEN][t]=!0),setSymbolDesc(e,t,n)):dP$1(e,t,n)},$defineProperties=function(e,t){_anObject(e);for(var n,r=_enumKeys(t=_toIobject(t)),i=0,o=r.length;o>i;)$defineProperty(e,n=r[i++],t[n]);return e},$create=function(e,t){return void 0===t?_objectCreate(e):$defineProperties(_objectCreate(e),t)},$propertyIsEnumerable=function(e){var t=isEnum.call(this,e=_toPrimitive(e,!0));return!(this===ObjectProto&&_has(AllSymbols,e)&&!_has(OPSymbols,e))&&(!(t||!_has(this,e)||!_has(AllSymbols,e)||_has(this,HIDDEN)&&this[HIDDEN][e])||t)},$getOwnPropertyDescriptor=function(e,t){if(e=_toIobject(e),t=_toPrimitive(t,!0),e!==ObjectProto||!_has(AllSymbols,t)||_has(OPSymbols,t)){var n=gOPD$1(e,t);return!n||!_has(AllSymbols,t)||_has(e,HIDDEN)&&e[HIDDEN][t]||(n.enumerable=!0),n}},$getOwnPropertyNames=function(e){for(var t,n=gOPN$1(_toIobject(e)),r=[],i=0;n.length>i;)_has(AllSymbols,t=n[i++])||t==HIDDEN||t==META||r.push(t);return r},$getOwnPropertySymbols=function(e){for(var t,n=e===ObjectProto,r=gOPN$1(n?OPSymbols:_toIobject(e)),i=[],o=0;r.length>o;)!_has(AllSymbols,t=r[o++])||n&&!_has(ObjectProto,t)||i.push(AllSymbols[t]);return i};USE_NATIVE||($Symbol=function(){if(this instanceof $Symbol)throw TypeError("Symbol is not a constructor!");var e=_uid(arguments.length>0?arguments[0]:void 0),t=function(n){this===ObjectProto&&t.call(OPSymbols,n),_has(this,HIDDEN)&&_has(this[HIDDEN],e)&&(this[HIDDEN][e]=!1),setSymbolDesc(this,e,_propertyDesc(1,n))};return _descriptors&&setter&&setSymbolDesc(ObjectProto,e,{configurable:!0,set:t}),wrap(e)},_redefine($Symbol[PROTOTYPE$2],"toString",function(){return this._k}),_objectGopd.f=$getOwnPropertyDescriptor,_objectDp.f=$defineProperty,_objectGopn.f=_objectGopnExt.f=$getOwnPropertyNames,_objectPie.f=$propertyIsEnumerable,_objectGops.f=$getOwnPropertySymbols,_descriptors&&!_library&&_redefine(ObjectProto,"propertyIsEnumerable",$propertyIsEnumerable,!0),_wksExt.f=function(e){return wrap(_wks(e))}),_export(_export.G+_export.W+_export.F*!USE_NATIVE,{Symbol:$Symbol});for(var es6Symbols="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),j=0;es6Symbols.length>j;)_wks(es6Symbols[j++]);for(var wellKnownSymbols=_objectKeys(_wks.store),k=0;wellKnownSymbols.length>k;)_wksDefine(wellKnownSymbols[k++]);_export(_export.S+_export.F*!USE_NATIVE,"Symbol",{for:function(e){return _has(SymbolRegistry,e+="")?SymbolRegistry[e]:SymbolRegistry[e]=$Symbol(e)},keyFor:function(e){if(!isSymbol(e))throw TypeError(e+" is not a symbol!");for(var t in SymbolRegistry)if(SymbolRegistry[t]===e)return t},useSetter:function(){setter=!0},useSimple:function(){setter=!1}}),_export(_export.S+_export.F*!USE_NATIVE,"Object",{create:$create,defineProperty:$defineProperty,defineProperties:$defineProperties,getOwnPropertyDescriptor:$getOwnPropertyDescriptor,getOwnPropertyNames:$getOwnPropertyNames,getOwnPropertySymbols:$getOwnPropertySymbols}),$JSON&&_export(_export.S+_export.F*(!USE_NATIVE||_fails(function(){var e=$Symbol();return"[null]"!=_stringify([e])||"{}"!=_stringify({a:e})||"{}"!=_stringify(Object(e))})),"JSON",{stringify:function(e){for(var t,n,r=[e],i=1;arguments.length>i;)r.push(arguments[i++]);if(n=t=r[1],(_isObject(t)||void 0!==e)&&!isSymbol(e))return _isArray(t)||(t=function(e,t){if("function"==typeof n&&(t=n.call(this,e,t)),!isSymbol(t))return t}),r[1]=t,_stringify.apply($JSON,r)}}),$Symbol[PROTOTYPE$2][TO_PRIMITIVE]||_hide($Symbol[PROTOTYPE$2],TO_PRIMITIVE,$Symbol[PROTOTYPE$2].valueOf),_setToStringTag($Symbol,"Symbol"),_setToStringTag(Math,"Math",!0),_setToStringTag(_global.JSON,"JSON",!0);var TAG$1=_wks("toStringTag"),ARG="Arguments"==_cof(function(){return arguments}()),tryGet=function(e,t){try{return e[t]}catch(e){}},_classof=function(e){var t,n,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=tryGet(t=Object(e),TAG$1))?n:ARG?_cof(t):"Object"==(r=_cof(t))&&"function"==typeof t.callee?"Arguments":r},test={};test[_wks("toStringTag")]="z",test+""!="[object z]"&&_redefine(Object.prototype,"toString",function(){return"[object "+_classof(this)+"]"},!0),_wksDefine("asyncIterator"),_wksDefine("observable");var symbol=_core.Symbol,_stringAt=function(e){return function(t,n){var r,i,o=String(_defined(t)),a=_toInteger(n),s=o.length;return a<0||a>=s?e?"":void 0:(r=o.charCodeAt(a))<55296||r>56319||a+1===s||(i=o.charCodeAt(a+1))<56320||i>57343?e?o.charAt(a):r:e?o.slice(a,a+2):i-56320+(r-55296<<10)+65536}},_iterators={},IteratorPrototype={};_hide(IteratorPrototype,_wks("iterator"),function(){return this});var _iterCreate=function(e,t,n){e.prototype=_objectCreate(IteratorPrototype,{next:_propertyDesc(1,n)}),_setToStringTag(e,t+" Iterator")},IE_PROTO$2=_sharedKey("IE_PROTO"),ObjectProto$1=Object.prototype,_objectGpo=Object.getPrototypeOf||function(e){return e=_toObject(e),_has(e,IE_PROTO$2)?e[IE_PROTO$2]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ObjectProto$1:null},ITERATOR=_wks("iterator"),BUGGY=!([].keys&&"next"in[].keys()),FF_ITERATOR="@@iterator",KEYS="keys",VALUES="values",returnThis=function(){return this},_iterDefine=function(e,t,n,r,i,o,a){_iterCreate(n,t,r);var s,u,c,h=function(e){if(!BUGGY&&e in p)return p[e];switch(e){case KEYS:case VALUES:return function(){return new n(this,e)}}return function(){return new n(this,e)}},l=t+" Iterator",d=i==VALUES,f=!1,p=e.prototype,m=p[ITERATOR]||p[FF_ITERATOR]||i&&p[i],y=m||h(i),g=i?d?h("entries"):y:void 0,v="Array"==t&&p.entries||m;if(v&&(c=_objectGpo(v.call(new e)))!==Object.prototype&&c.next&&(_setToStringTag(c,l,!0),_library||"function"==typeof c[ITERATOR]||_hide(c,ITERATOR,returnThis)),d&&m&&m.name!==VALUES&&(f=!0,y=function(){return m.call(this)}),_library&&!a||!BUGGY&&!f&&p[ITERATOR]||_hide(p,ITERATOR,y),_iterators[t]=y,_iterators[l]=returnThis,i)if(s={values:d?y:h(VALUES),keys:o?y:h(KEYS),entries:g},a)for(u in s)u in p||_redefine(p,u,s[u]);else _export(_export.P+_export.F*(BUGGY||f),t,s);return s},$at=_stringAt(!0);_iterDefine(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=$at(t,n),this._i+=e.length,{value:e,done:!1})});var _iterStep=function(e,t){return{value:t,done:!!e}},es6_array_iterator=_iterDefine(Array,"Array",function(e,t){this._t=_toIobject(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,_iterStep(1)):_iterStep(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]])},"values");_iterators.Arguments=_iterators.Array,_addToUnscopables("keys"),_addToUnscopables("values"),_addToUnscopables("entries");for(var ITERATOR$1=_wks("iterator"),TO_STRING_TAG=_wks("toStringTag"),ArrayValues=_iterators.Array,DOMIterables={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},collections=_objectKeys(DOMIterables),i=0;i<collections.length;i++){var NAME=collections[i],explicit=DOMIterables[NAME],Collection=_global[NAME],proto=Collection&&Collection.prototype,key;if(proto&&(proto[ITERATOR$1]||_hide(proto,ITERATOR$1,ArrayValues),proto[TO_STRING_TAG]||_hide(proto,TO_STRING_TAG,NAME),_iterators[NAME]=ArrayValues,explicit))for(key in es6_array_iterator)proto[key]||_redefine(proto,key,es6_array_iterator[key],!0)}var iterator=_wksExt.f("iterator"),extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};function __extends(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};function __awaiter(e,t,n,r){return new(n||(n=Promise))(function(i,o){function a(e){try{u(r.next(e))}catch(e){o(e)}}function s(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(a,s)}u((r=r.apply(e,t||[])).next())})}function __generator(e,t){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=r[2&o[0]?"return":o[0]?"throw":"next"])&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[0,i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var CONSTANTS={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+CONSTANTS.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},stringToByteArray=function(e){for(var t=[],n=0,r=0;r<e.length;r++){var i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},byteArrayToString=function(e){for(var t=[],n=0,r=0;n<e.length;){var i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){var o=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&o)}else if(i>239&&i<365){var a=((7&i)<<18|(63&(o=e[n++]))<<12|(63&(s=e[n++]))<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(a>>10)),t[r++]=String.fromCharCode(56320+(1023&a))}else{o=e[n++];var s=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&s)}}return t.join("")},base64={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray:function(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[],i=0;i<e.length;i+=3){var o=e[i],a=i+1<e.length,s=a?e[i+1]:0,u=i+2<e.length,c=u?e[i+2]:0,h=o>>2,l=(3&o)<<4|s>>4,d=(15&s)<<2|c>>6,f=63&c;u||(f=64,a||(d=64)),r.push(n[h],n[l],n[d],n[f])}return r.join("")},encodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray(e),t)},decodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):byteArrayToString(this.decodeStringToByteArray(e,t))},decodeStringToByteArray:function(e,t){this.init_();for(var n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[],i=0;i<e.length;){var o=n[e.charAt(i++)],a=i<e.length?n[e.charAt(i)]:0,s=++i<e.length?n[e.charAt(i)]:64,u=++i<e.length?n[e.charAt(i)]:64;if(++i,null==o||null==a||null==s||null==u)throw Error();var c=o<<2|a>>4;if(r.push(c),64!=s){var h=a<<4&240|s>>2;if(r.push(h),64!=u){var l=s<<6&192|u;r.push(l)}}}return r},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},base64Encode=function(e){var t=stringToByteArray(e);return base64.encodeByteArray(t,!0)},base64Decode=function(e){try{return base64.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function deepCopy(e){return deepExtend(void 0,e)}function deepExtend(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(var n in t)t.hasOwnProperty(n)&&(e[n]=deepExtend(e[n],t[n]));return e}function patchProperty(e,t,n){e[t]=n}var Deferred=function(){function e(){var e=this;this.promise=new Promise(function(t,n){e.resolve=t,e.reject=n})}return e.prototype.wrapCallback=function(e){var t=this;return function(n,r){n?t.reject(n):t.resolve(r),"function"==typeof e&&(t.promise.catch(function(){}),1===e.length?e(n):e(n,r))}},e}(),getUA=function(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""},isMobileCordova=function(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())},isReactNative=function(){return"object"==typeof navigator&&"ReactNative"===navigator.product},isNodeSdk=function(){return!0===CONSTANTS.NODE_CLIENT||!0===CONSTANTS.NODE_ADMIN},ERROR_NAME="FirebaseError",captureStackTrace=Error.captureStackTrace,FirebaseError=function(){return function(e,t){if(this.code=e,this.message=t,captureStackTrace)captureStackTrace(this,ErrorFactory.prototype.create);else try{throw Error.apply(this,arguments)}catch(e){this.name=ERROR_NAME,Object.defineProperty(this,"stack",{get:function(){return e.stack}})}}}();FirebaseError.prototype=Object.create(Error.prototype),FirebaseError.prototype.constructor=FirebaseError,FirebaseError.prototype.name=ERROR_NAME;var ErrorFactory=function(){function e(e,t,n){this.service=e,this.serviceName=t,this.errors=n,this.pattern=/\{\$([^}]+)}/g}return e.prototype.create=function(e,t){void 0===t&&(t={});var n,r=this.errors[e],i=this.service+"/"+e;n=void 0===r?"Error":r.replace(this.pattern,function(e,n){var r=t[n];return void 0!==r?r.toString():"<"+n+"?>"}),n=this.serviceName+": "+n+" ("+i+").";var o=new FirebaseError(i,n);for(var a in t)t.hasOwnProperty(a)&&"_"!==a.slice(-1)&&(o[a]=t[a]);return o},e}();function jsonEval(e){return JSON.parse(e)}function stringify(e){return JSON.stringify(e)}var decode=function(e){var t={},n={},r={},i="";try{var o=e.split(".");t=jsonEval(base64Decode(o[0])||""),n=jsonEval(base64Decode(o[1])||""),i=o[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}},isValidFormat=function(e){var t=decode(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},isAdmin=function(e){var t=decode(e).claims;return"object"==typeof t&&!0===t.admin},contains=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},safeGet=function(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]},forEach=function(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])},extend=function(e,t){return forEach(t,function(t,n){e[t]=n}),e},clone=function(e){return extend({},e)},isEmpty=function(e){for(var t in e)return!1;return!0},getCount=function(e){var t=0;for(var n in e)t++;return t},map=function(e,t,n){var r={};for(var i in e)r[i]=t.call(n,e[i],i,e);return r},findKey=function(e,t,n){for(var r in e)if(t.call(n,e[r],r,e))return r},findValue=function(e,t,n){var r=findKey(e,t,n);return r&&e[r]},getAnyKey=function(e){for(var t in e)return t},getValues=function(e){var t=[],n=0;for(var r in e)t[n++]=e[r];return t},every=function(e,t){for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&!t(n,e[n]))return!1;return!0},querystring=function(e){var t=[];return forEach(e,function(e,n){Array.isArray(n)?n.forEach(function(n){t.push(encodeURIComponent(e)+"="+encodeURIComponent(n))}):t.push(encodeURIComponent(e)+"="+encodeURIComponent(n))}),t.length?"&"+t.join("&"):""},Hash=function(){return function(){this.blockSize=-1}}(),Sha1=function(e){function t(){var t=e.call(this)||this;t.chain_=[],t.buf_=[],t.W_=[],t.pad_=[],t.inbuf_=0,t.total_=0,t.blockSize=64,t.pad_[0]=128;for(var n=1;n<t.blockSize;++n)t.pad_[n]=0;return t.reset(),t}return __extends(t,e),t.prototype.reset=function(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0},t.prototype.compress_=function(e,t){t||(t=0);var n=this.W_;if("string"==typeof e)for(var r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(r=16;r<80;r++){var i=n[r-3]^n[r-8]^n[r-14]^n[r-16];n[r]=4294967295&(i<<1|i>>>31)}var o,a,s=this.chain_[0],u=this.chain_[1],c=this.chain_[2],h=this.chain_[3],l=this.chain_[4];for(r=0;r<80;r++){r<40?r<20?(o=h^u&(c^h),a=1518500249):(o=u^c^h,a=1859775393):r<60?(o=u&c|h&(u|c),a=2400959708):(o=u^c^h,a=3395469782);i=(s<<5|s>>>27)+o+l+a+n[r]&4294967295;l=h,h=c,c=4294967295&(u<<30|u>>>2),u=s,s=i}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+u&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+h&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295},t.prototype.update=function(e,t){if(null!=e){void 0===t&&(t=e.length);for(var n=t-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r<t;){if(0==o)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[o]=e.charCodeAt(r),++r,++o==this.blockSize){this.compress_(i),o=0;break}}else for(;r<t;)if(i[o]=e[r],++r,++o==this.blockSize){this.compress_(i),o=0;break}}this.inbuf_=o,this.total_+=t}},t.prototype.digest=function(){var e=[],t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(var n=this.blockSize-1;n>=56;n--)this.buf_[n]=255&t,t/=256;this.compress_(this.buf_);var r=0;for(n=0;n<5;n++)for(var i=24;i>=0;i-=8)e[r]=this.chain_[n]>>i&255,++r;return e},t}(Hash);function createSubscribe(e,t){var n=new ObserverProxy(e,t);return n.subscribe.bind(n)}var ObserverProxy=function(){function e(e,t){var n=this;this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(function(){e(n)}).catch(function(e){n.error(e)})}return e.prototype.next=function(e){this.forEachObserver(function(t){t.next(e)})},e.prototype.error=function(e){this.forEachObserver(function(t){t.error(e)}),this.close(e)},e.prototype.complete=function(){this.forEachObserver(function(e){e.complete()}),this.close()},e.prototype.subscribe=function(e,t,n){var r,i=this;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");void 0===(r=implementsAnyMethods(e,["next","error","complete"])?e:{next:e,error:t,complete:n}).next&&(r.next=noop$1),void 0===r.error&&(r.error=noop$1),void 0===r.complete&&(r.complete=noop$1);var o=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(function(){try{i.finalError?r.error(i.finalError):r.complete()}catch(e){}}),this.observers.push(r),o},e.prototype.unsubscribeOne=function(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))},e.prototype.forEachObserver=function(e){if(!this.finalized)for(var t=0;t<this.observers.length;t++)this.sendOne(t,e)},e.prototype.sendOne=function(e,t){var n=this;this.task.then(function(){if(void 0!==n.observers&&void 0!==n.observers[e])try{t(n.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})},e.prototype.close=function(e){var t=this;this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(function(){t.observers=void 0,t.onNoObservers=void 0}))},e}();function implementsAnyMethods(e,t){if("object"!=typeof e||null===e)return!1;for(var n=0,r=t;n<r.length;n++){var i=r[n];if(i in e&&"function"==typeof e[i])return!0}return!1}function noop$1(){}var validateArgCount=function(e,t,n,r){var i;if(r<t?i="at least "+t:r>n&&(i=0===n?"none":"no more than "+n),i)throw new Error(e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")};function errorPrefix(e,t,n){var r="";switch(t){case 1:r=n?"first":"First";break;case 2:r=n?"second":"Second";break;case 3:r=n?"third":"Third";break;case 4:r=n?"fourth":"Fourth";break;default:throw new Error("errorPrefix called with argumentNumber > 4. Need to update it?")}var i=e+" failed: ";return i+=r+" argument "}function validateCallback(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(errorPrefix(e,t,r)+"must be a valid function.")}function validateContextObject(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(errorPrefix(e,t,r)+"must be a valid context object.")}var stringToByteArray$1=function(e){for(var t=[],n=0,r=0;r<e.length;r++){var i=e.charCodeAt(r);if(i>=55296&&i<=56319){var o=i-55296;assert(++r<e.length,"Surrogate pair missing trail surrogate."),i=65536+(o<<10)+(e.charCodeAt(r)-56320)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):i<65536?(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},stringLength=function(e){for(var t=0,n=0;n<e.length;n++){var r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t},contains$1=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},DEFAULT_ENTRY_NAME="[DEFAULT]",tokenListeners=[],FirebaseAppImpl=function(){function e(e,t,n){this.firebase_=n,this.isDeleted_=!1,this.services_={},this.name_=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled||!1,this.options_=deepCopy(e),this.INTERNAL={getUid:function(){return null},getToken:function(){return Promise.resolve(null)},addAuthTokenListener:function(e){tokenListeners.push(e),setTimeout(function(){return e(null)},0)},removeAuthTokenListener:function(e){tokenListeners=tokenListeners.filter(function(t){return t!==e})}}}return Object.defineProperty(e.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed_(),this._automaticDataCollectionEnabled},set:function(e){this.checkDestroyed_(),this._automaticDataCollectionEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return this.checkDestroyed_(),this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this.checkDestroyed_(),this.options_},enumerable:!0,configurable:!0}),e.prototype.delete=function(){var e=this;return new Promise(function(t){e.checkDestroyed_(),t()}).then(function(){e.firebase_.INTERNAL.removeApp(e.name_);var t=[];return Object.keys(e.services_).forEach(function(n){Object.keys(e.services_[n]).forEach(function(r){t.push(e.services_[n][r])})}),Promise.all(t.map(function(e){return e.INTERNAL.delete()}))}).then(function(){e.isDeleted_=!0,e.services_={}})},e.prototype._getService=function(e,t){if(void 0===t&&(t=DEFAULT_ENTRY_NAME),this.checkDestroyed_(),this.services_[e]||(this.services_[e]={}),!this.services_[e][t]){var n=t!==DEFAULT_ENTRY_NAME?t:void 0,r=this.firebase_.INTERNAL.factories[e](this,this.extendApp.bind(this),n);this.services_[e][t]=r}return this.services_[e][t]},e.prototype.extendApp=function(e){var t=this;deepExtend(this,e),e.INTERNAL&&e.INTERNAL.addAuthTokenListener&&(tokenListeners.forEach(function(e){t.INTERNAL.addAuthTokenListener(e)}),tokenListeners=[])},e.prototype.checkDestroyed_=function(){this.isDeleted_&&error("app-deleted",{name:this.name_})},e}();function createFirebaseNamespace(){var e={},t={},n={},r={__esModule:!0,initializeApp:function(t,n){void 0===n&&(n={});if("object"!=typeof n||null===n){var i=n;n={name:i}}var o=n;void 0===o.name&&(o.name=DEFAULT_ENTRY_NAME);var s=o.name;"string"==typeof s&&s||error("bad-app-name",{name:s+""});contains$1(e,s)&&error("duplicate-app",{name:s});var u=new FirebaseAppImpl(t,o,r);return e[s]=u,a(u,"create"),u},app:i,apps:null,Promise:Promise,SDK_VERSION:"5.5.2",INTERNAL:{registerService:function(e,a,s,u,c){t[e]&&error("duplicate-service",{name:e});t[e]=a,u&&(n[e]=u,o().forEach(function(e){u("create",e)}));var h=function(t){return void 0===t&&(t=i()),"function"!=typeof t[e]&&error("invalid-app-argument",{name:e}),t[e]()};void 0!==s&&deepExtend(h,s);return r[e]=h,FirebaseAppImpl.prototype[e]=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return this._getService.bind(this,e).apply(this,c?t:[])},h},createFirebaseNamespace:createFirebaseNamespace,extendNamespace:function(e){deepExtend(r,e)},createSubscribe:createSubscribe,ErrorFactory:ErrorFactory,removeApp:function(t){a(e[t],"delete"),delete e[t]},factories:t,useAsService:s,Promise:Promise,deepExtend:deepExtend}};function i(t){return contains$1(e,t=t||DEFAULT_ENTRY_NAME)||error("no-app",{name:t}),e[t]}function o(){return Object.keys(e).map(function(t){return e[t]})}function a(e,r){Object.keys(t).forEach(function(t){var i=s(e,t);null!==i&&n[i]&&n[i](r,e)})}function s(e,t){if("serverAuth"===t)return null;var n=t;e.options;return n}return patchProperty(r,"default",r),Object.defineProperty(r,"apps",{get:o}),patchProperty(i,"App",FirebaseAppImpl),r}function error(e,t){throw appErrors.create(e,t)}FirebaseAppImpl.prototype.name&&FirebaseAppImpl.prototype.options||FirebaseAppImpl.prototype.delete||console.log("dc");var errors={"no-app":"No Firebase App '{$name}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$name}","duplicate-app":"Firebase App named '{$name}' already exists","app-deleted":"Firebase App named '{$name}' already deleted","duplicate-service":"Firebase service named '{$name}' already registered","sa-not-supported":"Initializing the Firebase SDK with a service account is only allowed in a Node.js environment. On client devices, you should instead initialize the SDK with an api key and auth domain","invalid-app-argument":"firebase.{$name}() takes either no argument or a Firebase App instance."},appErrors=new ErrorFactory("app","Firebase",errors),firebase=createFirebaseNamespace(),LogLevel;(function(){var e,t=t||{},n=this;function r(e){return"string"==typeof e}function i(e){return"boolean"==typeof e}function o(){}function a(e){var t=typeof e;if("object"==t){if(!e)return"null";if(e instanceof Array)return"array";if(e instanceof Object)return t;var n=Object.prototype.toString.call(e);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof e.length&&void 0!==e.splice&&void 0!==e.propertyIsEnumerable&&!e.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==e.call&&void 0!==e.propertyIsEnumerable&&!e.propertyIsEnumerable("call"))return"function"}else if("function"==t&&void 0===e.call)return"object";return t}function s(e){return null===e}function u(e){return"array"==a(e)}function c(e){var t=a(e);return"array"==t||"object"==t&&"number"==typeof e.length}function h(e){return"function"==a(e)}function l(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var d="closure_uid_"+(1e9*Math.random()>>>0),f=0;function p(e,t,n){return e.call.apply(e.bind,arguments)}function m(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function y(e,t,n){return(y=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?p:m).apply(null,arguments)}function g(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}var v=Date.now||function(){return+new Date};function _(e,t){function n(){}n.prototype=t.prototype,e.nb=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.dd=function(e,n,r){for(var i=Array(arguments.length-2),o=2;o<arguments.length;o++)i[o-2]=arguments[o];return t.prototype[n].apply(e,i)}}function b(e){e.prototype.then=e.prototype.then,e.prototype.$goog_Thenable=!0}function E(e){if(!e)return!1;try{return!!e.$goog_Thenable}catch(e){return!1}}function S(e){if(Error.captureStackTrace)Error.captureStackTrace(this,S);else{var t=Error().stack;t&&(this.stack=t)}e&&(this.message=String(e))}function T(e,t){for(var n="",r=(e=e.split("%s")).length-1,i=0;i<r;i++)n+=e[i]+(i<t.length?t[i]:"%s");S.call(this,n+e[r])}function w(e,t){throw new T("Failure"+(e?": "+e:""),Array.prototype.slice.call(arguments,1))}function C(e,t){this.c=e,this.f=t,this.b=0,this.a=null}function I(e,t){e.f(t),100>e.b&&(e.b++,t.next=e.a,e.a=t)}function N(){this.b=this.a=null}_(S,Error),S.prototype.name="CustomError",_(T,S),T.prototype.name="AssertionError",C.prototype.get=function(){if(0<this.b){this.b--;var e=this.a;this.a=e.next,e.next=null}else e=this.c();return e};var R=new C(function(){return new A},function(e){e.reset()});function D(){var e=de,t=null;return e.a&&(t=e.a,e.a=e.a.next,e.a||(e.b=null),t.next=null),t}function A(){this.next=this.b=this.a=null}N.prototype.add=function(e,t){var n=R.get();n.set(e,t),this.b?this.b.next=n:this.a=n,this.b=n},A.prototype.set=function(e,t){this.a=e,this.b=t,this.next=null},A.prototype.reset=function(){this.next=this.b=this.a=null};var O=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if(r(e))return r(t)&&1==t.length?e.indexOf(t,0):-1;for(var n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1},P=Array.prototype.forEach?function(e,t,n){Array.prototype.forEach.call(e,t,n)}:function(e,t,n){for(var i=e.length,o=r(e)?e.split(""):e,a=0;a<i;a++)a in o&&t.call(n,o[a],a,e)};var k=Array.prototype.map?function(e,t){return Array.prototype.map.call(e,t,void 0)}:function(e,t){for(var n=e.length,i=Array(n),o=r(e)?e.split(""):e,a=0;a<n;a++)a in o&&(i[a]=t.call(void 0,o[a],a,e));return i},L=Array.prototype.some?function(e,t){return Array.prototype.some.call(e,t,void 0)}:function(e,t){for(var n=e.length,i=r(e)?e.split(""):e,o=0;o<n;o++)if(o in i&&t.call(void 0,i[o],o,e))return!0;return!1};function M(e,t){return 0<=O(e,t)}function F(e,t){var n;return(n=0<=(t=O(e,t)))&&Array.prototype.splice.call(e,t,1),n}function x(e,t){!function(e,t){var n=e.length,i=r(e)?e.split(""):e;for(--n;0<=n;--n)n in i&&t.call(void 0,i[n],n,e)}(e,function(n,r){t.call(void 0,n,r,e)&&1==Array.prototype.splice.call(e,r,1).length&&0})}function U(e){return Array.prototype.concat.apply([],arguments)}function B(e){var t=e.length;if(0<t){for(var n=Array(t),r=0;r<t;r++)n[r]=e[r];return n}return[]}function V(e,t){for(var n=e.split("%s"),r="",i=Array.prototype.slice.call(arguments,1);i.length&&1<n.length;)r+=n.shift()+i.shift();return r+n.join("%s")}var q=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function j(e){return X.test(e)?(-1!=e.indexOf("&")&&(e=e.replace(K,"&")),-1!=e.indexOf("<")&&(e=e.replace(G,"<")),-1!=e.indexOf(">")&&(e=e.replace($,">")),-1!=e.indexOf('"')&&(e=e.replace(H,""")),-1!=e.indexOf("'")&&(e=e.replace(Q,"'")),-1!=e.indexOf("\0")&&(e=e.replace(Y,"�")),e):e}var W,K=/&/g,G=/</g,$=/>/g,H=/"/g,Q=/'/g,Y=/\x00/g,X=/[\x00&<>"']/;function z(e,t){return-1!=e.indexOf(t)}function J(e,t){return e<t?-1:e>t?1:0}e:{var Z=n.navigator;if(Z){var ee=Z.userAgent;if(ee){W=ee;break e}}W=""}function te(e){return z(W,e)}function ne(e,t){for(var n in e)t.call(void 0,e[n],n,e)}function re(e){for(var t in e)return!1;return!0}function ie(e){var t,n={};for(t in e)n[t]=e[t];return n}var oe,ae,se="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ue(e,t){for(var n,r,i=1;i<arguments.length;i++){for(n in r=arguments[i])e[n]=r[n];for(var o=0;o<se.length;o++)n=se[o],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function ce(e){n.setTimeout(function(){throw e},0)}function he(e,t){ae||function(){if(n.Promise&&n.Promise.resolve){var e=n.Promise.resolve(void 0);ae=function(){e.then(fe)}}else ae=function(){var e=fe;!h(n.setImmediate)||n.Window&&n.Window.prototype&&!te("Edge")&&n.Window.prototype.setImmediate==n.setImmediate?(oe||(oe=function(){var e=n.MessageChannel;if(void 0===e&&"undefined"!=typeof window&&window.postMessage&&window.addEventListener&&!te("Presto")&&(e=function(){var e=document.createElement("IFRAME");e.style.display="none",e.src="",document.documentElement.appendChild(e);var t=e.contentWindow;(e=t.document).open(),e.write(""),e.close();var n="callImmediate"+Math.random(),r="file:"==t.location.protocol?"*":t.location.protocol+"//"+t.location.host;e=y(function(e){"*"!=r&&e.origin!=r||e.data!=n||this.port1.onmessage()},this),t.addEventListener("message",e,!1),this.port1={},this.port2={postMessage:function(){t.postMessage(n,r)}}}),void 0!==e&&!te("Trident")&&!te("MSIE")){var t=new e,r={},i=r;return t.port1.onmessage=function(){if(void 0!==r.next){var e=(r=r.next).vb;r.vb=null,e()}},function(e){i.next={vb:e},i=i.next,t.port2.postMessage(0)}}return"undefined"!=typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(e){var t=document.createElement("SCRIPT");t.onreadystatechange=function(){t.onreadystatechange=null,t.parentNode.removeChild(t),t=null,e(),e=null},document.documentElement.appendChild(t)}:function(e){n.setTimeout(e,0)}}()),oe(e)):n.setImmediate(e)}}(),le||(ae(),le=!0),de.add(e,t)}var le=!1,de=new N;function fe(){for(var e;e=D();){try{e.a.call(e.b)}catch(e){ce(e)}I(R,e)}le=!1}function pe(e,t){if(this.a=me,this.i=void 0,this.f=this.b=this.c=null,this.g=this.h=!1,e!=o)try{var n=this;e.call(t,function(e){Ne(n,ye,e)},function(e){if(!(e instanceof Le))try{if(e instanceof Error)throw e;throw Error("Promise rejected.")}catch(e){}Ne(n,ge,e)})}catch(e){Ne(this,ge,e)}}var me=0,ye=2,ge=3;function ve(){this.next=this.f=this.b=this.g=this.a=null,this.c=!1}ve.prototype.reset=function(){this.f=this.b=this.g=this.a=null,this.c=!1};var _e=new C(function(){return new ve},function(e){e.reset()});function be(e,t,n){var r=_e.get();return r.g=e,r.b=t,r.f=n,r}function Ee(e){if(e instanceof pe)return e;var t=new pe(o);return Ne(t,ye,e),t}function Se(e){return new pe(function(t,n){n(e)})}function Te(e,t,n){Re(e,t,n,null)||he(g(t,e))}function we(e){return new pe(function(t){var n=e.length,r=[];if(n)for(var i=function(e,i,o){n--,r[e]=i?{Cb:!0,value:o}:{Cb:!1,reason:o},0==n&&t(r)},o=0;o<e.length;o++)Te(e[o],g(i,o,!0),g(i,o,!1));else t(r)})}function Ce(e,t){e.b||e.a!=ye&&e.a!=ge||De(e),e.f?e.f.next=t:e.b=t,e.f=t}function Ie(e,t,n,r){var i=be(null,null,null);return i.a=new pe(function(e,o){i.g=t?function(n){try{var i=t.call(r,n);e(i)}catch(e){o(e)}}:e,i.b=n?function(t){try{var i=n.call(r,t);void 0===i&&t instanceof Le?o(t):e(i)}catch(e){o(e)}}:o}),i.a.c=e,Ce(e,i),i.a}function Ne(e,t,n){e.a==me&&(e===n&&(t=ge,n=new TypeError("Promise cannot resolve to itself")),e.a=1,Re(n,e.Mc,e.Nc,e)||(e.i=n,e.a=t,e.c=null,De(e),t!=ge||n instanceof Le||function(e,t){e.g=!0,he(function(){e.g&&ke.call(null,t)})}(e,n)))}function Re(e,t,n,r){if(e instanceof pe)return Ce(e,be(t||o,n||null,r)),!0;if(E(e))return e.then(t,n,r),!0;if(l(e))try{var i=e.then;if(h(i))return function(e,t,n,r,i){function o(e){a||(a=!0,r.call(i,e))}var a=!1;try{t.call(e,function(e){a||(a=!0,n.call(i,e))},o)}catch(e){o(e)}}(e,i,t,n,r),!0}catch(e){return n.call(r,e),!0}return!1}function De(e){e.h||(e.h=!0,he(e.Xb,e))}function Ae(e){var t=null;return e.b&&(t=e.b,e.b=t.next,t.next=null),e.b||(e.f=null),t}function Oe(e,t,n,r){if(n==ge&&t.b&&!t.c)for(;e&&e.g;e=e.c)e.g=!1;if(t.a)t.a.c=null,Pe(t,n,r);else try{t.c?t.g.call(t.f):Pe(t,n,r)}catch(e){ke.call(null,e)}I(_e,t)}function Pe(e,t,n){t==ye?e.g.call(e.f,n):e.b&&e.b.call(e.f,n)}pe.prototype.then=function(e,t,n){return Ie(this,h(e)?e:null,h(t)?t:null,n)},b(pe),(e=pe.prototype).ia=function(e,t){return(e=be(e,e,t)).c=!0,Ce(this,e),this},e.s=function(e,t){return Ie(this,null,e,t)},e.cancel=function(e){this.a==me&&he(function(){!function e(t,n){if(t.a==me)if(t.c){var r=t.c;if(r.b){for(var i=0,o=null,a=null,s=r.b;s&&(s.c||(i++,s.a==t&&(o=s),!(o&&1<i)));s=s.next)o||(a=s);o&&(r.a==me&&1==i?e(r,n):(a?((i=a).next==r.f&&(r.f=i),i.next=i.next.next):Ae(r),Oe(r,o,ge,n)))}t.c=null}else Ne(t,ge,n)}(this,new Le(e))},this)},e.Mc=function(e){this.a=me,Ne(this,ye,e)},e.Nc=function(e){this.a=me,Ne(this,ge,e)},e.Xb=function(){for(var e;e=Ae(this);)Oe(this,e,this.a,this.i);this.h=!1};var ke=ce;function Le(e){S.call(this,e)}function Me(){0!=Fe&&(xe[this[d]||(this[d]=++f)]=this),this.pa=this.pa,this.ja=this.ja}_(Le,S),Le.prototype.name="cancel";var Fe=0,xe={};function Ue(e){if(!e.pa&&(e.pa=!0,e.ua(),0!=Fe)){var t=e[d]||(e[d]=++f);if(0!=Fe&&e.ja&&0<e.ja.length)throw Error(e+" did not empty its onDisposeCallbacks queue. This probably means it overrode dispose() or disposeInternal() without calling the superclass' method.");delete xe[t]}}function Be(e){return Be[" "](e),e}Me.prototype.pa=!1,Me.prototype.ua=function(){if(this.ja)for(;this.ja.length;)this.ja.shift()()},Be[" "]=o;var Ve,qe,je=te("Opera"),We=te("Trident")||te("MSIE"),Ke=te("Edge"),Ge=Ke||We,$e=te("Gecko")&&!(z(W.toLowerCase(),"webkit")&&!te("Edge"))&&!(te("Trident")||te("MSIE"))&&!te("Edge"),He=z(W.toLowerCase(),"webkit")&&!te("Edge");function Qe(){var e=n.document;return e?e.documentMode:void 0}e:{var Ye="",Xe=(qe=W,$e?/rv:([^\);]+)(\)|;)/.exec(qe):Ke?/Edge\/([\d\.]+)/.exec(qe):We?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(qe):He?/WebKit\/(\S+)/.exec(qe):je?/(?:Version)[ \/]?(\S+)/.exec(qe):void 0);if(Xe&&(Ye=Xe?Xe[1]:""),We){var ze=Qe();if(null!=ze&&ze>parseFloat(Ye)){Ve=String(ze);break e}}Ve=Ye}var Je,Ze={};function et(e){return function(e,t){var n=Ze;return Object.prototype.hasOwnProperty.call(n,e)?n[e]:n[e]=t(e)}(e,function(){for(var t=0,n=q(String(Ve)).split("."),r=q(String(e)).split("."),i=Math.max(n.length,r.length),o=0;0==t&&o<i;o++){var a=n[o]||"",s=r[o]||"";do{if(a=/(\d*)(\D*)(.*)/.exec(a)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],0==a[0].length&&0==s[0].length)break;t=J(0==a[1].length?0:parseInt(a[1],10),0==s[1].length?0:parseInt(s[1],10))||J(0==a[2].length,0==s[2].length)||J(a[2],s[2]),a=a[3],s=s[3]}while(0==t)}return 0<=t})}var tt=n.document;Je=tt&&We?Qe()||("CSS1Compat"==tt.compatMode?parseInt(Ve,10):5):void 0;var nt=Object.freeze||function(e){return e},rt=!We||9<=Number(Je),it=We&&!et("9"),ot=function(){if(!n.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});return n.addEventListener("test",o,t),n.removeEventListener("test",o,t),e}();function at(e,t){this.type=e,this.b=this.target=t,this.Jb=!0}function st(e,t){if(at.call(this,e?e.type:""),this.relatedTarget=this.b=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.pointerId=0,this.pointerType="",this.a=null,e){var n=this.type=e.type,i=e.changedTouches?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.b=t,t=e.relatedTarget){if($e){e:{try{Be(t.nodeName);var o=!0;break e}catch(e){}o=!1}o||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,null===i?(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0):(this.clientX=void 0!==i.clientX?i.clientX:i.pageX,this.clientY=void 0!==i.clientY?i.clientY:i.pageY,this.screenX=i.screenX||0,this.screenY=i.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType=r(e.pointerType)?e.pointerType:ut[e.pointerType]||"",this.a=e,e.defaultPrevented&&this.preventDefault()}}at.prototype.preventDefault=function(){this.Jb=!1},_(st,at);var ut=nt({2:"touch",3:"pen",4:"mouse"});st.prototype.preventDefault=function(){st.nb.preventDefault.call(this);var e=this.a;if(e.preventDefault)e.preventDefault();else if(e.returnValue=!1,it)try{(e.ctrlKey||112<=e.keyCode&&123>=e.keyCode)&&(e.keyCode=-1)}catch(e){}},st.prototype.f=function(){return this.a};var ct="closure_listenable_"+(1e6*Math.random()|0),ht=0;function lt(e){e.na=!0,e.listener=null,e.proxy=null,e.src=null,e.La=null}function dt(e){this.src=e,this.a={},this.b=0}function ft(e,t){var n=t.type;n in e.a&&F(e.a[n],t)&&(lt(t),0==e.a[n].length&&(delete e.a[n],e.b--))}function pt(e,t,n,r){for(var i=0;i<e.length;++i){var o=e[i];if(!o.na&&o.listener==t&&o.capture==!!n&&o.La==r)return i}return-1}dt.prototype.add=function(e,t,n,r,i){var o=e.toString();(e=this.a[o])||(e=this.a[o]=[],this.b++);var a=pt(e,t,r,i);return-1<a?(t=e[a],n||(t.Ia=!1)):((t=new function(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.La=i,this.key=++ht,this.na=this.Ia=!1}(t,this.src,o,!!r,i)).Ia=n,e.push(t)),t};var mt="closure_lm_"+(1e6*Math.random()|0),yt={};function gt(e,t,n,r,i){if(r&&r.once)_t(e,t,n,r,i);else if(u(t))for(var o=0;o<t.length;o++)gt(e,t[o],n,r,i);else n=Rt(n),e&&e[ct]?At(e,t,n,l(r)?!!r.capture:!!r,i):vt(e,t,n,!1,r,i)}function vt(e,t,n,r,i,o){if(!t)throw Error("Invalid event type");var a=l(i)?!!i.capture:!!i,s=It(e);if(s||(e[mt]=s=new dt(e)),!(n=s.add(t,n,r,a,o)).proxy)if(r=function(){var e=Ct,t=rt?function(n){return e.call(t.src,t.listener,n)}:function(n){if(!(n=e.call(t.src,t.listener,n)))return n};return t}(),n.proxy=r,r.src=e,r.listener=n,e.addEventListener)ot||(i=a),void 0===i&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(St(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}}function _t(e,t,n,r,i){if(u(t))for(var o=0;o<t.length;o++)_t(e,t[o],n,r,i);else n=Rt(n),e&&e[ct]?Ot(e,t,n,l(r)?!!r.capture:!!r,i):vt(e,t,n,!0,r,i)}function bt(e,t,n,r,i){if(u(t))for(var o=0;o<t.length;o++)bt(e,t[o],n,r,i);else r=l(r)?!!r.capture:!!r,n=Rt(n),e&&e[ct]?(e=e.l,(t=String(t).toString())in e.a&&(-1<(n=pt(o=e.a[t],n,r,i))&&(lt(o[n]),Array.prototype.splice.call(o,n,1),0==o.length&&(delete e.a[t],e.b--)))):e&&(e=It(e))&&(t=e.a[t.toString()],e=-1,t&&(e=pt(t,n,r,i)),(n=-1<e?t[e]:null)&&Et(n))}function Et(e){if("number"!=typeof e&&e&&!e.na){var t=e.src;if(t&&t[ct])ft(t.l,e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(St(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=It(t))?(ft(n,e),0==n.b&&(n.src=null,t[mt]=null)):lt(e)}}}function St(e){return e in yt?yt[e]:yt[e]="on"+e}function Tt(e,t,n,r){var i=!0;if((e=It(e))&&(t=e.a[t.toString()]))for(t=t.concat(),e=0;e<t.length;e++){var o=t[e];o&&o.capture==n&&!o.na&&(o=wt(o,r),i=i&&!1!==o)}return i}function wt(e,t){var n=e.listener,r=e.La||e.src;return e.Ia&&Et(e),n.call(r,t)}function Ct(e,t){if(e.na)return!0;if(!rt){if(!t)e:{t=["window","event"];for(var r=n,i=0;i<t.length;i++)if(null==(r=r[t[i]])){t=null;break e}t=r}if(t=new st(i=t,this),r=!0,!(0>i.keyCode||void 0!=i.returnValue)){e:{var o=!1;if(0==i.keyCode)try{i.keyCode=-1;break e}catch(e){o=!0}(o||void 0==i.returnValue)&&(i.returnValue=!0)}for(i=[],o=t.b;o;o=o.parentNode)i.push(o);for(e=e.type,o=i.length-1;0<=o;o--){t.b=i[o];var a=Tt(i[o],e,!0,t);r=r&&a}for(o=0;o<i.length;o++)t.b=i[o],a=Tt(i[o],e,!1,t),r=r&&a}return r}return wt(e,new st(t,this))}function It(e){return(e=e[mt])instanceof dt?e:null}var Nt="__closure_events_fn_"+(1e9*Math.random()>>>0);function Rt(e){return h(e)?e:(e[Nt]||(e[Nt]=function(t){return e.handleEvent(t)}),e[Nt])}function Dt(){Me.call(this),this.l=new dt(this),this.Qb=this,this.Ua=null}function At(e,t,n,r,i){e.l.add(String(t),n,!1,r,i)}function Ot(e,t,n,r,i){e.l.add(String(t),n,!0,r,i)}function Pt(e,t,n,r){if(!(t=e.l.a[String(t)]))return!0;t=t.concat();for(var i=!0,o=0;o<t.length;++o){var a=t[o];if(a&&!a.na&&a.capture==n){var s=a.listener,u=a.La||a.src;a.Ia&&ft(e.l,a),i=!1!==s.call(u,r)&&i}}return i&&0!=r.Jb}function kt(e,t,r){if(h(e))r&&(e=y(e,r));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=y(e.handleEvent,e)}return 2147483647<Number(t)?-1:n.setTimeout(e,t||0)}function Lt(e){var t=null;return new pe(function(n,r){-1==(t=kt(function(){n(void 0)},e))&&r(Error("Failed to schedule timer."))}).s(function(e){throw n.clearTimeout(t),e})}function Mt(e){if(e.S&&"function"==typeof e.S)return e.S();if(r(e))return e.split("");if(c(e)){for(var t=[],n=e.length,i=0;i<n;i++)t.push(e[i]);return t}for(i in t=[],n=0,e)t[n++]=e[i];return t}function Ft(e){if(e.U&&"function"==typeof e.U)return e.U();if(!e.S||"function"!=typeof e.S){if(c(e)||r(e)){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}for(var i in t=[],n=0,e)t[n++]=i;return t}}function xt(e,t){this.b={},this.a=[],this.c=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(e)if(e instanceof xt)for(n=e.U(),r=0;r<n.length;r++)this.set(n[r],e.get(n[r]));else for(r in e)this.set(r,e[r])}function Ut(e){if(e.c!=e.a.length){for(var t=0,n=0;t<e.a.length;){var r=e.a[t];Bt(e.b,r)&&(e.a[n++]=r),t++}e.a.length=n}if(e.c!=e.a.length){var i={};for(n=t=0;t<e.a.length;)Bt(i,r=e.a[t])||(e.a[n++]=r,i[r]=1),t++;e.a.length=n}}function Bt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}_(Dt,Me),Dt.prototype[ct]=!0,Dt.prototype.addEventListener=function(e,t,n,r){gt(this,e,t,n,r)},Dt.prototype.removeEventListener=function(e,t,n,r){bt(this,e,t,n,r)},Dt.prototype.dispatchEvent=function(e){var t,n=this.Ua;if(n)for(t=[];n;n=n.Ua)t.push(n);n=this.Qb;var i=e.type||e;if(r(e))e=new at(e,n);else if(e instanceof at)e.target=e.target||n;else{var o=e;ue(e=new at(i,n),o)}if(o=!0,t)for(var a=t.length-1;0<=a;a--){var s=e.b=t[a];o=Pt(s,i,!0,e)&&o}if(o=Pt(s=e.b=n,i,!0,e)&&o,o=Pt(s,i,!1,e)&&o,t)for(a=0;a<t.length;a++)o=Pt(s=e.b=t[a],i,!1,e)&&o;return o},Dt.prototype.ua=function(){if(Dt.nb.ua.call(this),this.l){var e,t=this.l;for(e in t.a){for(var n=t.a[e],r=0;r<n.length;r++)lt(n[r]);delete t.a[e],t.b--}}this.Ua=null},(e=xt.prototype).S=function(){Ut(this);for(var e=[],t=0;t<this.a.length;t++)e.push(this.b[this.a[t]]);return e},e.U=function(){return Ut(this),this.a.concat()},e.clear=function(){this.b={},this.c=this.a.length=0},e.get=function(e,t){return Bt(this.b,e)?this.b[e]:t},e.set=function(e,t){Bt(this.b,e)||(this.c++,this.a.push(e)),this.b[e]=t},e.forEach=function(e,t){for(var n=this.U(),r=0;r<n.length;r++){var i=n[r],o=this.get(i);e.call(t,o,i,this)}};var Vt=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function qt(e,t){if(this.b=this.l=this.c="",this.i=null,this.h=this.g="",this.f=!1,e instanceof qt){this.f=void 0!==t?t:e.f,jt(this,e.c),this.l=e.l,this.b=e.b,Wt(this,e.i),this.g=e.g,t=e.a;var n=new rn;n.c=t.c,t.a&&(n.a=new xt(t.a),n.b=t.b),Kt(this,n),this.h=e.h}else e&&(n=String(e).match(Vt))?(this.f=!!t,jt(this,n[1]||"",!0),this.l=Yt(n[2]||""),this.b=Yt(n[3]||"",!0),Wt(this,n[4]),this.g=Yt(n[5]||"",!0),Kt(this,n[6]||"",!0),this.h=Yt(n[7]||"")):(this.f=!!t,this.a=new rn(null,this.f))}function jt(e,t,n){e.c=n?Yt(t,!0):t,e.c&&(e.c=e.c.replace(/:$/,""))}function Wt(e,t){if(t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);e.i=t}else e.i=null}function Kt(e,t,n){t instanceof rn?(e.a=t,function(e,t){t&&!e.f&&(on(e),e.c=null,e.a.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(sn(this,t),cn(this,n,e))},e)),e.f=t}(e.a,e.f)):(n||(t=Xt(t,tn)),e.a=new rn(t,e.f))}function Gt(e,t,n){e.a.set(t,n)}function $t(e,t){return e.a.get(t)}function Ht(e){return e instanceof qt?new qt(e):new qt(e,void 0)}function Qt(e,t){var n=new qt(null,void 0);return jt(n,"https"),e&&(n.b=e),t&&(n.g=t),n}function Yt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Xt(e,t,n){return r(e)?(e=encodeURI(e).replace(t,zt),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function zt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}qt.prototype.toString=function(){var e=[],t=this.c;t&&e.push(Xt(t,Jt,!0),":");var n=this.b;return(n||"file"==t)&&(e.push("//"),(t=this.l)&&e.push(Xt(t,Jt,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.i)&&e.push(":",String(n))),(n=this.g)&&(this.b&&"/"!=n.charAt(0)&&e.push("/"),e.push(Xt(n,"/"==n.charAt(0)?en:Zt,!0))),(n=this.a.toString())&&e.push("?",n),(n=this.h)&&e.push("#",Xt(n,nn)),e.join("")};var Jt=/[#\/\?@]/g,Zt=/[#\?:]/g,en=/[#\?]/g,tn=/[#\?@]/g,nn=/#/g;function rn(e,t){this.b=this.a=null,this.c=e||null,this.f=!!t}function on(e){e.a||(e.a=new xt,e.b=0,e.c&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var o=e[n].substring(0,r);i=e[n].substring(r+1)}else o=e[n];t(o,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(e.c,function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)}))}function an(e){var t=Ft(e);if(void 0===t)throw Error("Keys are undefined");var n=new rn(null,void 0);e=Mt(e);for(var r=0;r<t.length;r++){var i=t[r],o=e[r];u(o)?cn(n,i,o):n.add(i,o)}return n}function sn(e,t){on(e),t=hn(e,t),Bt(e.a.b,t)&&(e.c=null,e.b-=e.a.get(t).length,Bt((e=e.a).b,t)&&(delete e.b[t],e.c--,e.a.length>2*e.c&&Ut(e)))}function un(e,t){return on(e),t=hn(e,t),Bt(e.a.b,t)}function cn(e,t,n){sn(e,t),0<n.length&&(e.c=null,e.a.set(hn(e,t),B(n)),e.b+=n.length)}function hn(e,t){return t=String(t),e.f&&(t=t.toLowerCase()),t}(e=rn.prototype).add=function(e,t){on(this),this.c=null,e=hn(this,e);var n=this.a.get(e);return n||this.a.set(e,n=[]),n.push(t),this.b+=1,this},e.clear=function(){this.a=this.c=null,this.b=0},e.forEach=function(e,t){on(this),this.a.forEach(function(n,r){P(n,function(n){e.call(t,n,r,this)},this)},this)},e.U=function(){on(this);for(var e=this.a.S(),t=this.a.U(),n=[],r=0;r<t.length;r++)for(var i=e[r],o=0;o<i.length;o++)n.push(t[r]);return n},e.S=function(e){on(this);var t=[];if(r(e))un(this,e)&&(t=U(t,this.a.get(hn(this,e))));else{e=this.a.S();for(var n=0;n<e.length;n++)t=U(t,e[n])}return t},e.set=function(e,t){return on(this),this.c=null,un(this,e=hn(this,e))&&(this.b-=this.a.get(e).length),this.a.set(e,[t]),this.b+=1,this},e.get=function(e,t){return 0<(e=e?this.S(e):[]).length?String(e[0]):t},e.toString=function(){if(this.c)return this.c;if(!this.a)return"";for(var e=[],t=this.a.U(),n=0;n<t.length;n++){var r=t[n],i=encodeURIComponent(String(r));r=this.S(r);for(var o=0;o<r.length;o++){var a=i;""!==r[o]&&(a+="="+encodeURIComponent(String(r[o]))),e.push(a)}}return this.c=e.join("&")};var ln=!We||9<=Number(Je);function dn(){this.a="",this.b=pn}function fn(e){return e instanceof dn&&e.constructor===dn&&e.b===pn?e.a:(w("expected object of type Const, got '"+e+"'"),"type_error:Const")}dn.prototype.ma=!0,dn.prototype.la=function(){return this.a},dn.prototype.toString=function(){return"Const{"+this.a+"}"};var pn={};function mn(e){var t=new dn;return t.a=e,t}function yn(){this.a="",this.b=En}function gn(e){return e instanceof yn&&e.constructor===yn&&e.b===En?e.a:(w("expected object of type TrustedResourceUrl, got '"+e+"' of type "+a(e)),"type_error:TrustedResourceUrl")}function vn(e,t){var n=fn(e);if(!bn.test(n))throw Error("Invalid TrustedResourceUrl format: "+n);return function(e){var t=new yn;return t.a=e,t}(e=n.replace(_n,function(e,r){if(!Object.prototype.hasOwnProperty.call(t,r))throw Error('Found marker, "'+r+'", in format string, "'+n+'", but no valid label mapping found in args: '+JSON.stringify(t));return(e=t[r])instanceof dn?fn(e):encodeURIComponent(String(e))}))}mn(""),yn.prototype.ma=!0,yn.prototype.la=function(){return this.a},yn.prototype.toString=function(){return"TrustedResourceUrl{"+this.a+"}"};var _n=/%{(\w+)}/g,bn=/^(?:https:)?\/\/[0-9a-z.:[\]-]+\/|^\/[^\/\\]|^about:blank#/i,En={};function Sn(){this.a="",this.b=In}function Tn(e){return e instanceof Sn&&e.constructor===Sn&&e.b===In?e.a:(w("expected object of type SafeUrl, got '"+e+"' of type "+a(e)),"type_error:SafeUrl")}Sn.prototype.ma=!0,Sn.prototype.la=function(){return this.a},Sn.prototype.toString=function(){return"SafeUrl{"+this.a+"}"};var wn=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i;function Cn(e){return e instanceof Sn?e:(e=e.ma?e.la():String(e),wn.test(e)||(e="about:invalid#zClosurez"),Nn(e))}var In={};function Nn(e){var t=new Sn;return t.a=e,t}function Rn(){this.a="",this.b=Dn}Nn("about:blank"),Rn.prototype.ma=!0,Rn.prototype.la=function(){return this.a},Rn.prototype.toString=function(){return"SafeHtml{"+this.a+"}"};var Dn={};function An(e){var t=new Rn;return t.a=e,t}function On(e){var t=document;return r(e)?t.getElementById(e):e}function Pn(e,t){ne(t,function(t,n){t&&t.ma&&(t=t.la()),"style"==n?e.style.cssText=t:"class"==n?e.className=t:"for"==n?e.htmlFor=t:kn.hasOwnProperty(n)?e.setAttribute(kn[n],t):0==n.lastIndexOf("aria-",0)||0==n.lastIndexOf("data-",0)?e.setAttribute(n,t):e[n]=t})}An("<!DOCTYPE html>"),An(""),An("<br>");var kn={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"};function Ln(e,t,n){var i=arguments,o=document,a=String(i[0]),s=i[1];if(!ln&&s&&(s.name||s.type)){if(a=["<",a],s.name&&a.push(' name="',j(s.name),'"'),s.type){a.push(' type="',j(s.type),'"');var h={};ue(h,s),delete h.type,s=h}a.push(">"),a=a.join("")}return a=o.createElement(a),s&&(r(s)?a.className=s:u(s)?a.className=s.join(" "):Pn(a,s)),2<i.length&&function(e,t,n){function i(n){n&&t.appendChild(r(n)?e.createTextNode(n):n)}for(var o=2;o<n.length;o++){var a=n[o];!c(a)||l(a)&&0<a.nodeType?i(a):P(Mn(a)?B(a):a,i)}}(o,a,i),a}function Mn(e){if(e&&"number"==typeof e.length){if(l(e))return"function"==typeof e.item||"string"==typeof e.item;if(h(e))return"function"==typeof e.item}return!1}function Fn(e){var t=[];return function e(t,n,r){if(null==n)r.push("null");else{if("object"==typeof n){if(u(n)){var i=n;n=i.length,r.push("[");for(var o="",a=0;a<n;a++)r.push(o),e(t,i[a],r),o=",";return void r.push("]")}if(!(n instanceof String||n instanceof Number||n instanceof Boolean)){for(i in r.push("{"),o="",n)Object.prototype.hasOwnProperty.call(n,i)&&("function"!=typeof(a=n[i])&&(r.push(o),Bn(i,r),r.push(":"),e(t,a,r),o=","));return void r.push("}")}n=n.valueOf()}switch(typeof n){case"string":Bn(n,r);break;case"number":r.push(isFinite(n)&&!isNaN(n)?String(n):"null");break;case"boolean":r.push(String(n));break;case"function":r.push("null");break;default:throw Error("Unknown type: "+typeof n)}}}(new function(){},e,t),t.join("")}var xn={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\u000b"},Un=/\uffff/.test("")?/[\\"\x00-\x1f\x7f-\uffff]/g:/[\\"\x00-\x1f\x7f-\xff]/g;function Bn(e,t){t.push('"',e.replace(Un,function(e){var t=xn[e];return t||(t="\\u"+(65536|e.charCodeAt(0)).toString(16).substr(1),xn[e]=t),t}),'"')}function Vn(){var e=ir();return We&&!!Je&&11==Je||/Edge\/\d+/.test(e)}function qn(){return n.window&&n.window.location.href||self&&self.location&&self.location.href||""}function jn(e,t){t=t||n.window;var r="about:blank";e&&(r=Tn(Cn(e))),t.location.href=r}function Wn(e){return!!((e=(e||ir()).toLowerCase()).match(/android/)||e.match(/webos/)||e.match(/iphone|ipad|ipod/)||e.match(/blackberry/)||e.match(/windows phone/)||e.match(/iemobile/))}function Kn(e){e=e||n.window;try{e.close()}catch(e){}}function Gn(e,t,n){var r=Math.floor(1e9*Math.random()).toString();t=t||500,n=n||600;var i=(window.screen.availHeight-n)/2,o=(window.screen.availWidth-t)/2;for(s in t={width:t,height:n,top:0<i?i:0,left:0<o?o:0,location:!0,resizable:!0,statusbar:!0,toolbar:!1},n=ir().toLowerCase(),r&&(t.target=r,z(n,"crios/")&&(t.target="_blank")),tr(ir())==Zn&&(e=e||"http://localhost",t.scrollbars=!0),n=e||"",(e=t)||(e={}),r=window,t=n instanceof Sn?n:Cn(void 0!==n.href?n.href:String(n)),n=e.target||n.target,i=[],e)switch(s){case"width":case"height":case"top":case"left":i.push(s+"="+e[s]);break;case"target":case"noopener":case"noreferrer":break;default:i.push(s+"="+(e[s]?1:0))}var s=i.join(",");if((te("iPhone")&&!te("iPod")&&!te("iPad")||te("iPad")||te("iPod"))&&r.navigator&&r.navigator.standalone&&n&&"_self"!=n?(s=r.document.createElement("A"),t instanceof Sn||t instanceof Sn||(t=t.ma?t.la():String(t),wn.test(t)||(t="about:invalid#zClosurez"),t=Nn(t)),s.href=Tn(t),s.setAttribute("target",n),e.noreferrer&&s.setAttribute("rel","noreferrer"),(e=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,r,1),s.dispatchEvent(e),s={}):e.noreferrer?(s=r.open("",n,s),e=Tn(t),s&&(Ge&&z(e,";")&&(e="'"+e.replace(/'/g,"%27")+"'"),s.opener=null,mn("b/12014412, meta tag with sanitized URL"),e=An(e='<meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0; url='+j(e)+'">'),s.document.write(function(e){return e instanceof Rn&&e.constructor===Rn&&e.b===Dn?e.a:(w("expected object of type SafeHtml, got '"+e+"' of type "+a(e)),"type_error:SafeHtml")}(e)),s.document.close())):(s=r.open(Tn(t),n,s))&&e.noopener&&(s.opener=null),s)try{s.focus()}catch(e){}return s}var $n=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;function Hn(){var e=null;return new pe(function(t){"complete"==n.document.readyState?t():(e=function(){t()},_t(window,"load",e))}).s(function(t){throw bt(window,"load",e),t})}function Qn(e){return e=e||ir(),!("file:"!==cr()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Yn(){var e=n.window;try{return!(!e||e==e.top)}catch(e){return!1}}function Xn(){return"object"!=typeof n.window&&"function"==typeof n.importScripts}function zn(){return firebase.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":firebase.INTERNAL.hasOwnProperty("node")?"Node":Xn()?"Worker":"Browser"}function Jn(){var e=zn();return"ReactNative"===e||"Node"===e}var Zn="Firefox",er="Chrome";function tr(e){var t=e.toLowerCase();return z(t,"opera/")||z(t,"opr/")||z(t,"opios/")?"Opera":z(t,"iemobile")?"IEMobile":z(t,"msie")||z(t,"trident/")?"IE":z(t,"edge/")?"Edge":z(t,"firefox/")?Zn:z(t,"silk/")?"Silk":z(t,"blackberry")?"Blackberry":z(t,"webos")?"Webos":!z(t,"safari/")||z(t,"chrome/")||z(t,"crios/")||z(t,"android")?!z(t,"chrome/")&&!z(t,"crios/")||z(t,"edge/")?z(t,"android")?"Android":(e=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==e.length?e[1]:"Other":er:"Safari"}var nr={Tc:"FirebaseCore-web",Vc:"FirebaseUI-web"};function rr(e,t){t=t||[];var n,r=[],i={};for(n in nr)i[nr[n]]=!0;for(n=0;n<t.length;n++)void 0!==i[t[n]]&&(delete i[t[n]],r.push(t[n]));return r.sort(),(t=r).length||(t=["FirebaseCore-web"]),"Browser"===(r=zn())?r=tr(i=ir()):"Worker"===r&&(r=tr(i=ir())+"-"+r),r+"/JsCore/"+e+"/"+t.join(",")}function ir(){return n.navigator&&n.navigator.userAgent||""}function or(e,t){e=e.split("."),t=t||n;for(var r=0;r<e.length&&"object"==typeof t&&null!=t;r++)t=t[e[r]];return r!=e.length&&(t=void 0),t}function ar(){try{var e=n.localStorage,t=pr();if(e)return e.setItem(t,"1"),e.removeItem(t),!Vn()||!!n.indexedDB}catch(e){return Xn()&&!!n.indexedDB}return!1}function sr(){return(ur()||"chrome-extension:"===cr()||Qn())&&!Jn()&&ar()&&!Xn()}function ur(){return"http:"===cr()||"https:"===cr()}function cr(){return n.location&&n.location.protocol||null}function hr(e){return!Wn(e=e||ir())&&tr(e)!=Zn}function lr(e){return void 0===e?null:Fn(e)}function dr(e){var t,n={};for(t in e)e.hasOwnProperty(t)&&null!==e[t]&&void 0!==e[t]&&(n[t]=e[t]);return n}function fr(e){if(null!==e)return JSON.parse(e)}function pr(e){return e||Math.floor(1e9*Math.random()).toString()}function mr(e){return"Safari"!=tr(e=e||ir())&&!e.toLowerCase().match(/iphone|ipad|ipod/)}function yr(){var e=n.___jsl;if(e&&e.H)for(var t in e.H)if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=e.H[t].L.concat(),e.CP)for(var r=0;r<e.CP.length;r++)e.CP[r]=null}function gr(e,t){if(e>t)throw Error("Short delay should be less than long delay!");this.a=e,this.c=t,e=ir(),t=zn(),this.b=Wn(e)||"ReactNative"===t}function vr(){var e=n.document;return!e||void 0===e.visibilityState||"visible"==e.visibilityState}function _r(e){try{var t=new Date(parseInt(e,10));if(!isNaN(t.getTime())&&!/[^0-9]/.test(e))return t.toUTCString()}catch(e){}return null}function br(){return!(!or("fireauth.oauthhelper",n)&&!or("fireauth.iframe",n))}gr.prototype.get=function(){var e=n.navigator;return!e||"boolean"!=typeof e.onLine||!ur()&&"chrome-extension:"!==cr()&&void 0===e.connection||e.onLine?this.b?this.c:this.a:Math.min(5e3,this.a)};var Er,Sr={};function Tr(e){Sr[e]||(Sr[e]=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(e))}try{var wr={};Object.defineProperty(wr,"abcd",{configurable:!0,enumerable:!0,value:1}),Object.defineProperty(wr,"abcd",{configurable:!0,enumerable:!0,value:2}),Er=2==wr.abcd}catch(qe){Er=!1}function Cr(e,t,n){Er?Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n}):e[t]=n}function Ir(e,t){if(t)for(var n in t)t.hasOwnProperty(n)&&Cr(e,n,t[n])}function Nr(e){var t={};return Ir(t,e),t}function Rr(e){var t=e;if("object"==typeof e&&null!=e)for(var n in t="length"in e?[]:{},e)Cr(t,n,Rr(e[n]));return t}var Dr="EMAIL_SIGNIN",Ar="email",Or="newEmail",Pr="requestType",kr="email",Lr="fromEmail",Mr="data",Fr="operation";function xr(e,t){this.code=Br+e,this.message=t||Vr[e]||""}function Ur(e){var t=e&&e.code;return t?new xr(t.substring(Br.length),e.message):null}_(xr,Error),xr.prototype.D=function(){return{code:this.code,message:this.message}},xr.prototype.toJSON=function(){return this.D()};var Br="auth/",Vr={"argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-already-in-use":"The email address is already in use by another account.","expired-action-code":"The action code has expired. ","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal error has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal error has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-email":"The email address is badly formatted.","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal error has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network error (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal error has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","user-cancelled":"User did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled."};function qr(e){var t=e[Gr];if(void 0===t)throw new xr("missing-continue-uri");if("string"!=typeof t||"string"==typeof t&&!t.length)throw new xr("invalid-continue-uri");this.h=t,this.b=this.a=null,this.g=!1;var n=e[jr];if(n&&"object"==typeof n){t=n[Qr];var r=n[$r];if(n=n[Hr],"string"==typeof t&&t.length){if(this.a=t,void 0!==r&&"boolean"!=typeof r)throw new xr("argument-error",$r+" property must be a boolean when specified.");if(this.g=!!r,void 0!==n&&("string"!=typeof n||"string"==typeof n&&!n.length))throw new xr("argument-error",Hr+" property must be a non empty string when specified.");this.b=n||null}else{if(void 0!==t)throw new xr("argument-error",Qr+" property must be a non empty string when specified.");if(void 0!==r||void 0!==n)throw new xr("missing-android-pkg-name")}}else if(void 0!==n)throw new xr("argument-error",jr+" property must be a non null object when specified.");if(this.f=null,(t=e[Kr])&&"object"==typeof t){if("string"==typeof(t=t[Yr])&&t.length)this.f=t;else if(void 0!==t)throw new xr("argument-error",Yr+" property must be a non empty string when specified.")}else if(void 0!==t)throw new xr("argument-error",Kr+" property must be a non null object when specified.");if(void 0!==(e=e[Wr])&&"boolean"!=typeof e)throw new xr("argument-error",Wr+" property must be a boolean when specified.");this.c=!!e}var jr="android",Wr="handleCodeInApp",Kr="iOS",Gr="url",$r="installApp",Hr="minimumVersion",Qr="packageName",Yr="bundleId";function Xr(e){var t={};for(var n in t.continueUrl=e.h,t.canHandleCodeInApp=e.c,(t.androidPackageName=e.a)&&(t.androidMinimumVersion=e.b,t.androidInstallApp=e.g),t.iOSBundleId=e.f,t)null===t[n]&&delete t[n];return t}var zr=null,Jr=null;function Zr(e){var t="";return function(e,t){function n(t){for(;r<e.length;){var n=e.charAt(r++),i=Jr[n];if(null!=i)return i;if(!/^[\s\xa0]*$/.test(n))throw Error("Unknown base64 encoding at char: "+n)}return t}!function(){if(!zr){zr={},Jr={};for(var e=0;65>e;e++)zr[e]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(e),Jr[zr[e]]=e,62<=e&&(Jr["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(e)]=e)}}();for(var r=0;;){var i=n(-1),o=n(0),a=n(64),s=n(64);if(64===s&&-1===i)break;t(i<<2|o>>4),64!=a&&(t(o<<4&240|a>>2),64!=s&&t(a<<6&192|s))}}(e,function(e){t+=String.fromCharCode(e)}),t}function ei(e){this.c=e.sub,this.a=e.provider_id||e.firebase&&e.firebase.sign_in_provider||null,this.b=!!e.is_anonymous||"anonymous"==this.a}function ti(e){return(e=ni(e))&&e.sub&&e.iss&&e.aud&&e.exp?new ei(e):null}function ni(e){if(!e)return null;if(3!=(e=e.split(".")).length)return null;for(var t=(4-(e=e[1]).length%4)%4,n=0;n<t;n++)e+=".";try{return JSON.parse(Zr(e))}catch(e){}return null}ei.prototype.f=function(){return this.b};var ri="oauth_consumer_key oauth_nonce oauth_signature oauth_signature_method oauth_timestamp oauth_token oauth_version".split(" "),ii=["client_id","response_type","scope","redirect_uri","state"],oi={Uc:{Ma:"locale",Ba:500,Aa:600,Na:"facebook.com",gb:ii},Wc:{Ma:null,Ba:500,Aa:620,Na:"github.com",gb:ii},Xc:{Ma:"hl",Ba:515,Aa:680,Na:"google.com",gb:ii},cd:{Ma:"lang",Ba:485,Aa:705,Na:"twitter.com",gb:ri}};function ai(e){for(var t in oi)if(oi[t].Na==e)return oi[t];return null}function si(e){var t={};t["facebook.com"]=di,t["google.com"]=pi,t["github.com"]=fi,t["twitter.com"]=mi;var n=e&&e[ci];try{if(n)return t[n]?new t[n](e):new li(e);if(void 0!==e[ui])return new hi(e)}catch(e){}return null}var ui="idToken",ci="providerId";function hi(e){var t=e[ci];if(!t&&e[ui]){var n=ti(e[ui]);n&&n.a&&(t=n.a)}if(!t)throw Error("Invalid additional user info!");"anonymous"!=t&&"custom"!=t||(t=null),n=!1,void 0!==e.isNewUser?n=!!e.isNewUser:"identitytoolkit#SignupNewUserResponse"===e.kind&&(n=!0),Cr(this,"providerId",t),Cr(this,"isNewUser",n)}function li(e){hi.call(this,e),Cr(this,"profile",Rr((e=fr(e.rawUserInfo||"{}"))||{}))}function di(e){if(li.call(this,e),"facebook.com"!=this.providerId)throw Error("Invalid provider ID!")}function fi(e){if(li.call(this,e),"github.com"!=this.providerId)throw Error("Invalid provider ID!");Cr(this,"username",this.profile&&this.profile.login||null)}function pi(e){if(li.call(this,e),"google.com"!=this.providerId)throw Error("Invalid provider ID!")}function mi(e){if(li.call(this,e),"twitter.com"!=this.providerId)throw Error("Invalid provider ID!");Cr(this,"username",e.screenName||null)}function yi(e){var t=Ht(e),n=$t(t,"link"),r=$t(Ht(n),"link");return $t(Ht(t=$t(t,"deep_link_id")),"link")||t||r||n||e}function gi(e,t){return e.then(function(e){if(e[zo]){var n=ti(e[zo]);if(!n||t!=n.c)throw new xr("user-mismatch");return e}throw new xr("user-mismatch")}).s(function(e){throw e&&e.code&&e.code==Br+"user-not-found"?new xr("user-mismatch"):e})}function vi(e,t,n){if(t.idToken||t.accessToken)t.idToken&&Cr(this,"idToken",t.idToken),t.accessToken&&Cr(this,"accessToken",t.accessToken);else{if(!t.oauthToken||!t.oauthTokenSecret)throw new xr("internal-error","failed to construct a credential");Cr(this,"accessToken",t.oauthToken),Cr(this,"secret",t.oauthTokenSecret)}Cr(this,"providerId",e),Cr(this,"signInMethod",n)}function _i(e){var t={};return e.idToken&&(t.id_token=e.idToken),e.accessToken&&(t.access_token=e.accessToken),e.secret&&(t.oauth_token_secret=e.secret),t.providerId=e.providerId,{postBody:an(t).toString(),requestUri:"http://localhost"}}function bi(e,t){this.Cc=t||[],Ir(this,{providerId:e,isOAuthProvider:!0}),this.xb={},this.bb=(ai(e)||{}).Ma||null,this.Za=null}function Ei(e){bi.call(this,e,ii),this.a=[]}function Si(){Ei.call(this,"facebook.com")}function Ti(e){if(!e)throw new xr("argument-error","credential failed: expected 1 argument (the OAuth access token).");var t=e;return l(e)&&(t=e.accessToken),(new Si).credential(null,t)}function wi(){Ei.call(this,"github.com")}function Ci(e){if(!e)throw new xr("argument-error","credential failed: expected 1 argument (the OAuth access token).");var t=e;return l(e)&&(t=e.accessToken),(new wi).credential(null,t)}function Ii(){Ei.call(this,"google.com"),this.ta("profile")}function Ni(e,t){var n=e;return l(e)&&(n=e.idToken,t=e.accessToken),(new Ii).credential(n,t)}function Ri(){bi.call(this,"twitter.com",ri)}function Di(e,t){var n=e;if(l(n)||(n={oauthToken:e,oauthTokenSecret:t}),!n.oauthToken||!n.oauthTokenSecret)throw new xr("argument-error","credential failed: expected 2 arguments (the OAuth access token and secret).");return new vi("twitter.com",n,"twitter.com")}function Ai(e,t,n){this.a=e,this.b=t,Cr(this,"providerId","password"),Cr(this,"signInMethod",n===Oi.EMAIL_LINK_SIGN_IN_METHOD?Oi.EMAIL_LINK_SIGN_IN_METHOD:Oi.EMAIL_PASSWORD_SIGN_IN_METHOD)}function Oi(){Ir(this,{providerId:"password",isOAuthProvider:!1})}function Pi(e,t){if(!(t=ki(t)))throw new xr("argument-error","Invalid email link!");return new Ai(e,t,Oi.EMAIL_LINK_SIGN_IN_METHOD)}function ki(e){var t=$t((e=new function(e){this.a=Ht(e)}(e=yi(e))).a,"oobCode")||null;return"signIn"===($t(e.a,"mode")||null)&&t?t:null}function Li(e){if(!(e.Sa&&e.Ra||e.Fa&&e.$))throw new xr("internal-error");this.a=e,Cr(this,"providerId","phone"),Cr(this,"signInMethod","phone")}function Mi(e){return e.a.Fa&&e.a.$?{temporaryProof:e.a.Fa,phoneNumber:e.a.$}:{sessionInfo:e.a.Sa,code:e.a.Ra}}function Fi(e){try{this.a=e||firebase.auth()}catch(e){throw new xr("argument-error","Either an instance of firebase.auth.Auth must be passed as an argument to the firebase.auth.PhoneAuthProvider constructor, or the default firebase App instance must be initialized via firebase.initializeApp().")}Ir(this,{providerId:"phone",isOAuthProvider:!1})}function xi(e,t){if(!e)throw new xr("missing-verification-id");if(!t)throw new xr("missing-verification-code");return new Li({Sa:e,Ra:t})}function Ui(e){if(e.temporaryProof&&e.phoneNumber)return new Li({Fa:e.temporaryProof,$:e.phoneNumber});var t=e&&e.providerId;if(!t||"password"===t)return null;var n=e&&e.oauthAccessToken,r=e&&e.oauthTokenSecret;e=e&&e.oauthIdToken;try{switch(t){case"google.com":return Ni(e,n);case"facebook.com":return Ti(n);case"github.com":return Ci(n);case"twitter.com":return Di(n,r);default:return new Ei(t).credential(e,n)}}catch(e){return null}}function Bi(e){if(!e.isOAuthProvider)throw new xr("invalid-oauth-provider")}function Vi(e,t,n,r,i){if(this.b=e,this.c=t||null,this.f=n||null,this.g=r||null,this.a=i||null,!this.f&&!this.a)throw new xr("invalid-auth-event");if(this.f&&this.a)throw new xr("invalid-auth-event");if(this.f&&!this.g)throw new xr("invalid-auth-event")}function qi(e){return(e=e||{}).type?new Vi(e.type,e.eventId,e.urlResponse,e.sessionId,e.error&&Ur(e.error)):null}function ji(){this.b=null,this.a=[]}_(li,hi),_(di,li),_(fi,li),_(pi,li),_(mi,li),vi.prototype.ya=function(e){return pa(e,_i(this))},vi.prototype.c=function(e,t){var n=_i(this);return n.idToken=t,ma(e,n)},vi.prototype.f=function(e,t){return gi(ya(e,_i(this)),t)},vi.prototype.D=function(){var e={providerId:this.providerId,signInMethod:this.signInMethod};return this.idToken&&(e.oauthIdToken=this.idToken),this.accessToken&&(e.oauthAccessToken=this.accessToken),this.secret&&(e.oauthTokenSecret=this.secret),e},bi.prototype.Da=function(e){return this.xb=ie(e),this},_(Ei,bi),Ei.prototype.ta=function(e){return M(this.a,e)||this.a.push(e),this},Ei.prototype.Db=function(){return B(this.a)},Ei.prototype.credential=function(e,t){if(!e&&!t)throw new xr("argument-error","credential failed: must provide the ID token and/or the access token.");return new vi(this.providerId,{idToken:e||null,accessToken:t||null},this.providerId)},_(Si,Ei),Cr(Si,"PROVIDER_ID","facebook.com"),Cr(Si,"FACEBOOK_SIGN_IN_METHOD","facebook.com"),_(wi,Ei),Cr(wi,"PROVIDER_ID","github.com"),Cr(wi,"GITHUB_SIGN_IN_METHOD","github.com"),_(Ii,Ei),Cr(Ii,"PROVIDER_ID","google.com"),Cr(Ii,"GOOGLE_SIGN_IN_METHOD","google.com"),_(Ri,bi),Cr(Ri,"PROVIDER_ID","twitter.com"),Cr(Ri,"TWITTER_SIGN_IN_METHOD","twitter.com"),Ai.prototype.ya=function(e){return this.signInMethod==Oi.EMAIL_LINK_SIGN_IN_METHOD?Ga(e,wa,{email:this.a,oobCode:this.b}):Ga(e,qa,{email:this.a,password:this.b})},Ai.prototype.c=function(e,t){return this.signInMethod==Oi.EMAIL_LINK_SIGN_IN_METHOD?Ga(e,Ca,{idToken:t,email:this.a,oobCode:this.b}):Ga(e,Ma,{idToken:t,email:this.a,password:this.b})},Ai.prototype.f=function(e,t){return gi(this.ya(e),t)},Ai.prototype.D=function(){return{email:this.a,password:this.b,signInMethod:this.signInMethod}},Ir(Oi,{PROVIDER_ID:"password"}),Ir(Oi,{EMAIL_LINK_SIGN_IN_METHOD:"emailLink"}),Ir(Oi,{EMAIL_PASSWORD_SIGN_IN_METHOD:"password"}),Li.prototype.ya=function(e){return e.Ta(Mi(this))},Li.prototype.c=function(e,t){var n=Mi(this);return n.idToken=t,Ga(e,Wa,n)},Li.prototype.f=function(e,t){var n=Mi(this);return n.operation="REAUTH",gi(e=Ga(e,Ka,n),t)},Li.prototype.D=function(){var e={providerId:"phone"};return this.a.Sa&&(e.verificationId=this.a.Sa),this.a.Ra&&(e.verificationCode=this.a.Ra),this.a.Fa&&(e.temporaryProof=this.a.Fa),this.a.$&&(e.phoneNumber=this.a.$),e},Fi.prototype.Ta=function(e,t){var n=this.a.b;return Ee(t.verify()).then(function(i){if(!r(i))throw new xr("argument-error","An implementation of firebase.auth.ApplicationVerifier.prototype.verify() must return a firebase.Promise that resolves with a string.");switch(t.type){case"recaptcha":return function(e,t){return Ga(e,ka,t)}(n,{phoneNumber:e,recaptchaToken:i}).then(function(e){return"function"==typeof t.reset&&t.reset(),e},function(e){throw"function"==typeof t.reset&&t.reset(),e});default:throw new xr("argument-error",'Only firebase.auth.ApplicationVerifiers with type="recaptcha" are currently supported.')}})},Ir(Fi,{PROVIDER_ID:"phone"}),Ir(Fi,{PHONE_SIGN_IN_METHOD:"phone"}),Vi.prototype.D=function(){return{type:this.b,eventId:this.c,urlResponse:this.f,sessionId:this.g,error:this.a&&this.a.D()}};var Wi=null;function Ki(e){var t="unauthorized-domain",n=void 0,r=Ht(e);e=r.b,"chrome-extension"==(r=r.c)?n=V("This chrome extension ID (chrome-extension://%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",e):"http"==r||"https"==r?n=V("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",e):t="operation-not-supported-in-this-environment",xr.call(this,t,n)}function Gi(e,t,n){xr.call(this,e,n),(e=t||{}).yb&&Cr(this,"email",e.yb),e.$&&Cr(this,"phoneNumber",e.$),e.credential&&Cr(this,"credential",e.credential)}function $i(e){if(e.code){var t=e.code||"";0==t.indexOf(Br)&&(t=t.substring(Br.length));var n={credential:Ui(e)};if(e.email)n.yb=e.email;else if(e.phoneNumber)n.$=e.phoneNumber;else if(!n.credential)return new xr(t,e.message||void 0);return new Gi(t,n,e.message)}return null}ji.prototype.subscribe=function(e){var t=this;this.a.push(e),this.b||(this.b=function(e){for(var n=0;n<t.a.length;n++)t.a[n](e)},"function"==typeof(e=or("universalLinks.subscribe",n))&&e(null,this.b))},ji.prototype.unsubscribe=function(e){x(this.a,function(t){return t==e})},_(Ki,xr),_(Gi,xr),Gi.prototype.D=function(){var e={code:this.code,message:this.message};this.email&&(e.email=this.email),this.phoneNumber&&(e.phoneNumber=this.phoneNumber);var t=this.credential&&this.credential.D();return t&&ue(e,t),e},Gi.prototype.toJSON=function(){return this.D()};var Hi,Qi=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,63}$/;function Yi(){}function Xi(e){return e.c||(e.c=e.b())}function zi(){}function Ji(e){if(!e.f&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var t=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],n=0;n<t.length;n++){var r=t[n];try{return new ActiveXObject(r),e.f=r}catch(e){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed")}return e.f}function Zi(){}function eo(){this.a=new XDomainRequest,this.readyState=0,this.onreadystatechange=null,this.responseText="",this.status=-1,this.statusText="",this.a.onload=y(this.dc,this),this.a.onerror=y(this.Eb,this),this.a.onprogress=y(this.ec,this),this.a.ontimeout=y(this.hc,this)}function to(e,t){e.readyState=t,e.onreadystatechange&&e.onreadystatechange()}function no(e,t,n){this.reset(e,t,n,void 0,void 0)}function ro(e){this.f=e,this.b=this.c=this.a=null}function io(e,t){this.name=e,this.value=t}Yi.prototype.c=null,_(zi,Yi),zi.prototype.a=function(){var e=Ji(this);return e?new ActiveXObject(e):new XMLHttpRequest},zi.prototype.b=function(){var e={};return Ji(this)&&(e[0]=!0,e[1]=!0),e},Hi=new zi,_(Zi,Yi),Zi.prototype.a=function(){var e=new XMLHttpRequest;if("withCredentials"in e)return e;if("undefined"!=typeof XDomainRequest)return new eo;throw Error("Unsupported browser")},Zi.prototype.b=function(){return{}},(e=eo.prototype).open=function(e,t,n){if(null!=n&&!n)throw Error("Only async requests are supported.");this.a.open(e,t)},e.send=function(e){if(e){if("string"!=typeof e)throw Error("Only string data is supported");this.a.send(e)}else this.a.send()},e.abort=function(){this.a.abort()},e.setRequestHeader=function(){},e.getResponseHeader=function(e){return"content-type"==e.toLowerCase()?this.a.contentType:""},e.dc=function(){this.status=200,this.responseText=this.a.responseText,to(this,4)},e.Eb=function(){this.status=500,this.responseText="",to(this,4)},e.hc=function(){this.Eb()},e.ec=function(){this.status=200,to(this,1)},e.getAllResponseHeaders=function(){return"content-type: "+this.a.contentType},no.prototype.a=null,no.prototype.reset=function(e,t,n,r,i){delete this.a},io.prototype.toString=function(){return this.name};var oo=new io("SEVERE",1e3),ao=new io("WARNING",900),so=new io("CONFIG",700),uo=new io("FINE",500);ro.prototype.log=function(e,t,n){if(e.value>=function e(t){return t.c?t.c:t.a?e(t.a):(w("Root logger has no level set."),null)}(this).value)for(h(t)&&(t=t()),e=new no(e,String(t),this.f),n&&(e.a=n),n=this;n;)n=n.a};var co={},ho=null;function lo(e){var t;if(ho||(ho=new ro(""),co[""]=ho,ho.c=so),!(t=co[e])){t=new ro(e);var n=e.lastIndexOf("."),r=e.substr(n+1);(n=lo(e.substr(0,n))).b||(n.b={}),n.b[r]=t,t.a=n,co[e]=t}return t}function fo(e,t){e&&e.log(uo,t,void 0)}function po(e){this.f=e}function mo(e){Dt.call(this),this.i=e,this.readyState=yo,this.status=0,this.responseText=this.statusText="",this.onreadystatechange=null,this.g=new Headers,this.b=null,this.h="GET",this.c="",this.a=!1,this.f=lo("goog.net.FetchXmlHttp")}_(po,Yi),po.prototype.a=function(){return new mo(this.f)},po.prototype.b=function(e){return function(){return e}}({}),_(mo,Dt);var yo=0;function go(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function vo(e){Dt.call(this),this.headers=new xt,this.C=e||null,this.c=!1,this.w=this.a=null,this.h=this.N=this.m="",this.f=this.I=this.i=this.G=!1,this.g=0,this.u=null,this.o=_o,this.v=this.O=!1}(e=mo.prototype).open=function(e,t){if(this.readyState!=yo)throw this.abort(),Error("Error reopening a connection");this.h=e,this.c=t,this.readyState=1,go(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.a=!0;var t={headers:this.g,method:this.h,credentials:void 0,cache:void 0};e&&(t.body=e),this.i.fetch(new Request(this.c,t)).then(this.gc.bind(this),this.Fb.bind(this))},e.abort=function(){this.responseText="",this.g=new Headers,this.status=0,1<=this.readyState&&this.a&&4!=this.readyState&&(this.readyState=4,this.a=!1,go(this)),this.readyState=yo},e.gc=function(e){this.a&&(this.b||(this.b=e.headers,this.readyState=2,go(this)),this.a&&(this.readyState=3,go(this),this.a&&e.text().then(this.fc.bind(this,e),this.Fb.bind(this))))},e.fc=function(e,t){this.a&&(this.status=e.status,this.statusText=e.statusText,this.responseText=t,this.readyState=4,go(this))},e.Fb=function(e){var t=this.f;t&&t.log(ao,"Failed to fetch url "+this.c,e instanceof Error?e:Error(e)),this.a&&(this.readyState=4,go(this))},e.setRequestHeader=function(e,t){this.g.append(e,t)},e.getResponseHeader=function(e){return this.b?this.b.get(e.toLowerCase())||"":((e=this.f)&&e.log(ao,"Attempting to get response header but no headers have been received for url: "+this.c,void 0),"")},e.getAllResponseHeaders=function(){if(!this.b){var e=this.f;return e&&e.log(ao,"Attempting to get all response headers but no headers have been received for url: "+this.c,void 0),""}e=[];for(var t=this.b.entries(),n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},_(vo,Dt);var _o="";vo.prototype.b=lo("goog.net.XhrIo");var bo=/^https?$/i,Eo=["POST","PUT"];function So(e,t,i,o,a){if(e.a)throw Error("[goog.net.XhrIo] Object is active with another request="+e.m+"; newUri="+t);i=i?i.toUpperCase():"GET",e.m=t,e.h="",e.N=i,e.G=!1,e.c=!0,e.a=e.C?e.C.a():Hi.a(),e.w=e.C?Xi(e.C):Xi(Hi),e.a.onreadystatechange=y(e.Ib,e);try{fo(e.b,Oo(e,"Opening Xhr")),e.I=!0,e.a.open(i,String(t),!0),e.I=!1}catch(t){return fo(e.b,Oo(e,"Error opening Xhr: "+t.message)),void wo(e,t)}t=o||"";var s=new xt(e.headers);a&&function(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(c(e)||r(e))P(e,t,void 0);else for(var n=Ft(e),i=Mt(e),o=i.length,a=0;a<o;a++)t.call(void 0,i[a],n&&n[a],e)}(a,function(e,t){s.set(t,e)}),a=function(e){e:{for(var t=To,n=e.length,i=r(e)?e.split(""):e,o=0;o<n;o++)if(o in i&&t.call(void 0,i[o],o,e)){t=o;break e}t=-1}return 0>t?null:r(e)?e.charAt(t):e[t]}(s.U()),o=n.FormData&&t instanceof n.FormData,!M(Eo,i)||a||o||s.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),s.forEach(function(e,t){this.a.setRequestHeader(t,e)},e),e.o&&(e.a.responseType=e.o),"withCredentials"in e.a&&e.a.withCredentials!==e.O&&(e.a.withCredentials=e.O);try{Ro(e),0<e.g&&(e.v=function(e){return We&&et(9)&&"number"==typeof e.timeout&&void 0!==e.ontimeout}(e.a),fo(e.b,Oo(e,"Will abort after "+e.g+"ms if incomplete, xhr2 "+e.v)),e.v?(e.a.timeout=e.g,e.a.ontimeout=y(e.Ga,e)):e.u=kt(e.Ga,e.g,e)),fo(e.b,Oo(e,"Sending request")),e.i=!0,e.a.send(t),e.i=!1}catch(t){fo(e.b,Oo(e,"Send error: "+t.message)),wo(e,t)}}function To(e){return"content-type"==e.toLowerCase()}function wo(e,t){e.c=!1,e.a&&(e.f=!0,e.a.abort(),e.f=!1),e.h=t,Co(e),No(e)}function Co(e){e.G||(e.G=!0,e.dispatchEvent("complete"),e.dispatchEvent("error"))}function Io(e){if(e.c&&void 0!==t)if(e.w[1]&&4==Do(e)&&2==Ao(e))fo(e.b,Oo(e,"Local request error detected and ignored"));else if(e.i&&4==Do(e))kt(e.Ib,0,e);else if(e.dispatchEvent("readystatechange"),4==Do(e)){fo(e.b,Oo(e,"Request complete")),e.c=!1;try{var r,i=Ao(e);e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var o=!0;break e;default:o=!1}if(!(r=o)){var a;if(a=0===i){var s=String(e.m).match(Vt)[1]||null;if(!s&&n.self&&n.self.location){var u=n.self.location.protocol;s=u.substr(0,u.length-1)}a=!bo.test(s?s.toLowerCase():"")}r=a}if(r)e.dispatchEvent("complete"),e.dispatchEvent("success");else{try{var c=2<Do(e)?e.a.statusText:""}catch(t){fo(e.b,"Can not get status: "+t.message),c=""}e.h=c+" ["+Ao(e)+"]",Co(e)}}finally{No(e)}}}function No(e,t){if(e.a){Ro(e);var n=e.a,r=e.w[0]?o:null;e.a=null,e.w=null,t||e.dispatchEvent("ready");try{n.onreadystatechange=r}catch(t){(e=e.b)&&e.log(oo,"Problem encountered resetting onreadystatechange: "+t.message,void 0)}}}function Ro(e){e.a&&e.v&&(e.a.ontimeout=null),e.u&&(n.clearTimeout(e.u),e.u=null)}function Do(e){return e.a?e.a.readyState:0}function Ao(e){try{return 2<Do(e)?e.a.status:-1}catch(e){return-1}}function Oo(e,t){return t+" ["+e.N+" "+e.m+" "+Ao(e)+"]"}function Po(e,t){this.g=[],this.v=e,this.u=t||null,this.f=this.a=!1,this.c=void 0,this.m=this.w=this.i=!1,this.h=0,this.b=null,this.l=0}function ko(e,t,n){e.a=!0,e.c=n,e.f=!t,xo(e)}function Lo(e){if(e.a){if(!e.m)throw new Uo(e);e.m=!1}}function Mo(e,t,n,r){e.g.push([t,n,r]),e.a&&xo(e)}function Fo(e){return L(e.g,function(e){return h(e[1])})}function xo(e){if(e.h&&e.a&&Fo(e)){var t=e.h,r=qo[t];r&&(n.clearTimeout(r.a),delete qo[t]),e.h=0}e.b&&(e.b.l--,delete e.b),t=e.c;for(var i=r=!1;e.g.length&&!e.i;){var o=e.g.shift(),a=o[0],s=o[1];if(o=o[2],a=e.f?s:a)try{var u=a.call(o||e.u,t);void 0!==u&&(e.f=e.f&&(u==t||u instanceof Error),e.c=t=u),(E(t)||"function"==typeof n.Promise&&t instanceof n.Promise)&&(i=!0,e.i=!0)}catch(n){t=n,e.f=!0,Fo(e)||(r=!0)}}e.c=t,i&&(u=y(e.o,e,!0),i=y(e.o,e,!1),t instanceof Po?(Mo(t,u,i),t.w=!0):t.then(u,i)),r&&(t=new Vo(t),qo[t.a]=t,e.h=t.a)}function Uo(){S.call(this)}function Bo(){S.call(this)}function Vo(e){this.a=n.setTimeout(y(this.c,this),0),this.b=e}(e=vo.prototype).Ga=function(){void 0!==t&&this.a&&(this.h="Timed out after "+this.g+"ms, aborting",fo(this.b,Oo(this,this.h)),this.dispatchEvent("timeout"),this.abort(8))},e.abort=function(){this.a&&this.c&&(fo(this.b,Oo(this,"Aborting")),this.c=!1,this.f=!0,this.a.abort(),this.f=!1,this.dispatchEvent("complete"),this.dispatchEvent("abort"),No(this))},e.ua=function(){this.a&&(this.c&&(this.c=!1,this.f=!0,this.a.abort(),this.f=!1),No(this,!0)),vo.nb.ua.call(this)},e.Ib=function(){this.pa||(this.I||this.i||this.f?Io(this):this.vc())},e.vc=function(){Io(this)},e.getResponse=function(){try{if(!this.a)return null;if("response"in this.a)return this.a.response;switch(this.o){case _o:case"text":return this.a.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in this.a)return this.a.mozResponseArrayBuffer}var e=this.b;return e&&e.log(oo,"Response type "+this.o+" is not supported on this browser",void 0),null}catch(e){return fo(this.b,"Can not get response: "+e.message),null}},Po.prototype.cancel=function(e){if(this.a)this.c instanceof Po&&this.c.cancel();else{if(this.b){var t=this.b;delete this.b,e?t.cancel(e):(t.l--,0>=t.l&&t.cancel())}this.v?this.v.call(this.u,this):this.m=!0,this.a||(e=new Bo(this),Lo(this),ko(this,!1,e))}},Po.prototype.o=function(e,t){this.i=!1,ko(this,e,t)},Po.prototype.C=function(){Lo(this),ko(this,!0,null)},Po.prototype.then=function(e,t,n){var r,i,o=new pe(function(e,t){r=e,i=t});return Mo(this,r,function(e){e instanceof Bo?o.cancel():i(e)}),o.then(e,t,n)},b(Po),_(Uo,S),Uo.prototype.message="Deferred has already fired",Uo.prototype.name="AlreadyCalledError",_(Bo,S),Bo.prototype.message="Deferred was canceled",Bo.prototype.name="CanceledError",Vo.prototype.c=function(){throw delete qo[this.a],this.b};var qo={};function jo(e){var t={},n=t.document||document,r=gn(e),i=document.createElement("SCRIPT"),o={Kb:i,Ga:void 0},a=new Po(Wo,o),s=null,u=null!=t.timeout?t.timeout:5e3;return 0<u&&(s=window.setTimeout(function(){Ko(i,!0);var e=new Ho($o,"Timeout reached for loading script "+r);Lo(a),ko(a,!1,e)},u),o.Ga=s),i.onload=i.onreadystatechange=function(){i.readyState&&"loaded"!=i.readyState&&"complete"!=i.readyState||(Ko(i,t.ed||!1,s),a.C())},i.onerror=function(){Ko(i,!0,s);var e=new Ho(Go,"Error while loading script "+r);Lo(a),ko(a,!1,e)},ue(o=t.attributes||{},{type:"text/javascript",charset:"UTF-8"}),Pn(i,o),i.src=gn(e),function(e){var t;return(t=(e||document).getElementsByTagName("HEAD"))&&0!=t.length?t[0]:e.documentElement}(n).appendChild(i),a}function Wo(){if(this&&this.Kb){var e=this.Kb;e&&"SCRIPT"==e.tagName&&Ko(e,!0,this.Ga)}}function Ko(e,t,r){null!=r&&n.clearTimeout(r),e.onload=o,e.onerror=o,e.onreadystatechange=o,t&&window.setTimeout(function(){e&&e.parentNode&&e.parentNode.removeChild(e)},0)}var Go=0,$o=1;function Ho(e,t){var n="Jsloader error (code #"+e+")";t&&(n+=": "+t),S.call(this,n),this.code=e}function Qo(e){this.f=e}function Yo(e,t,r){if(this.b=e,e=t||{},this.i=e.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token",this.l=e.secureTokenTimeout||Jo,this.f=ie(e.secureTokenHeaders||Zo),this.g=e.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",this.h=e.firebaseTimeout||ea,this.a=ie(e.firebaseHeaders||ta),r&&(this.a["X-Client-Version"]=r,this.f["X-Client-Version"]=r),r="Node"==zn(),!(r=n.XMLHttpRequest||r&&firebase.INTERNAL.node&&firebase.INTERNAL.node.XMLHttpRequest)&&!Xn())throw new xr("internal-error","The XMLHttpRequest compatibility library was not found.");this.c=void 0,Xn()?this.c=new po(self):Jn()?this.c=new Qo(r):this.c=new Zi}_(Ho,S),_(Qo,Yi),Qo.prototype.a=function(){return new this.f},Qo.prototype.b=function(){return{}};var Xo,zo="idToken",Jo=new gr(3e4,6e4),Zo={"Content-Type":"application/x-www-form-urlencoded"},ea=new gr(3e4,6e4),ta={"Content-Type":"application/json"};function na(e,t){t?e.a["X-Firebase-Locale"]=t:delete e.a["X-Firebase-Locale"]}function ra(e,t){t?(e.a["X-Client-Version"]=t,e.f["X-Client-Version"]=t):(delete e.a["X-Client-Version"],delete e.f["X-Client-Version"])}function ia(e,t,r,i,o,a,s){(function(){var e=ir();return!((e=tr(e)!=er?null:(e=e.match(/\sChrome\/(\d+)/i))&&2==e.length?parseInt(e[1],10):null)&&30>e||We&&Je&&!(9<Je))})()||Xn()?e=y(e.o,e):(Xo||(Xo=new pe(function(e,t){!function(e,t){if(((window.gapi||{}).client||{}).request)e();else{n[aa]=function(){((window.gapi||{}).client||{}).request?e():t(Error("CORS_UNSUPPORTED"))};var r=vn(oa,{onload:aa});!function(e,t){Mo(e,null,t,void 0)}(jo(r),function(){t(Error("CORS_UNSUPPORTED"))})}}(e,t)})),e=y(e.m,e)),e(t,r,i,o,a,s)}Yo.prototype.o=function(e,t,r,i,o,a){if(Xn()&&(void 0===n.fetch||void 0===n.Headers||void 0===n.Request))throw new xr("operation-not-supported-in-this-environment","fetch, Headers and Request native APIs or equivalent Polyfills must be available to support HTTP requests from a Worker environment.");var s=new vo(this.c);if(a){s.g=Math.max(0,a);var u=setTimeout(function(){s.dispatchEvent("timeout")},a)}At(s,"complete",function(){u&&clearTimeout(u);var e=null;try{e=JSON.parse(function(e){try{return e.a?e.a.responseText:""}catch(t){return fo(e.b,"Can not get responseText: "+t.message),""}}(this))||null}catch(t){e=null}t&&t(e)}),Ot(s,"ready",function(){u&&clearTimeout(u),Ue(this)}),Ot(s,"timeout",function(){u&&clearTimeout(u),Ue(this),t&&t(null)}),So(s,e,r,i,o)};var oa=mn("https://apis.google.com/js/client.js?onload=%{onload}"),aa="__fcb"+Math.floor(1e6*Math.random()).toString();function sa(e){if(!Qi.test(e.email))throw new xr("invalid-email")}function ua(e){"email"in e&&sa(e)}function ca(e){if(!e[zo])throw new xr("internal-error")}function ha(e){if(e.phoneNumber||e.temporaryProof){if(!e.phoneNumber||!e.temporaryProof)throw new xr("internal-error")}else{if(!e.sessionInfo)throw new xr("missing-verification-id");if(!e.code)throw new xr("missing-verification-code")}}Yo.prototype.m=function(e,t,n,r,i){var o=this;Xo.then(function(){window.gapi.client.setApiKey(o.b);var a=window.gapi.auth.getToken();window.gapi.auth.setToken(null),window.gapi.client.request({path:e,method:n,body:r,headers:i,authType:"none",callback:function(e){window.gapi.auth.setToken(a),t&&t(e)}})}).s(function(e){t&&t({error:{message:e&&e.message||"CORS_UNSUPPORTED"}})})},Yo.prototype.Pa=function(){return Ga(this,Fa,{})},Yo.prototype.ob=function(e,t){return Ga(this,La,{idToken:e,email:t})},Yo.prototype.pb=function(e,t){return Ga(this,Ma,{idToken:e,password:t})};var la={displayName:"DISPLAY_NAME",photoUrl:"PHOTO_URL"};function da(e){if(!e.requestUri||!e.sessionId&&!e.postBody)throw new xr("internal-error")}function fa(e){var t=null;if(e.needConfirmation?(e.code="account-exists-with-different-credential",t=$i(e)):"FEDERATED_USER_ID_ALREADY_LINKED"==e.errorMessage?(e.code="credential-already-in-use",t=$i(e)):"EMAIL_EXISTS"==e.errorMessage?(e.code="email-already-in-use",t=$i(e)):e.errorMessage&&(t=$a(e.errorMessage)),t)throw t;if(!e[zo])throw new xr("internal-error")}function pa(e,t){return t.returnIdpCredential=!0,Ga(e,xa,t)}function ma(e,t){return t.returnIdpCredential=!0,Ga(e,Ba,t)}function ya(e,t){return t.returnIdpCredential=!0,t.autoCreate=!1,Ga(e,Ua,t)}function ga(e){if(!e.oobCode)throw new xr("invalid-action-code")}(e=Yo.prototype).qb=function(e,t){var n={idToken:e},r=[];return ne(la,function(e,i){var o=t[i];null===o?r.push(e):i in t&&(n[i]=o)}),r.length&&(n.deleteAttribute=r),Ga(this,La,n)},e.jb=function(e,t){return ue(e={requestType:"PASSWORD_RESET",email:e},t),Ga(this,Da,e)},e.kb=function(e,t){return ue(e={requestType:"EMAIL_SIGNIN",email:e},t),Ga(this,Na,e)},e.ib=function(e,t){return ue(e={requestType:"VERIFY_EMAIL",idToken:e},t),Ga(this,Ra,e)},e.Ta=function(e){return Ga(this,ja,e)},e.Ya=function(e,t){return Ga(this,Pa,{oobCode:e,newPassword:t})},e.Ja=function(e){return Ga(this,_a,{oobCode:e})},e.Va=function(e){return Ga(this,va,{oobCode:e})};var va={endpoint:"setAccountInfo",B:ga,da:"email"},_a={endpoint:"resetPassword",B:ga,J:function(e){var t=e.requestType;if(!t||!e.email&&"EMAIL_SIGNIN"!=t)throw new xr("internal-error")}},ba={endpoint:"signupNewUser",B:function(e){if(sa(e),!e.password)throw new xr("weak-password")},J:ca,R:!0},Ea={endpoint:"createAuthUri"},Sa={endpoint:"deleteAccount",T:["idToken"]},Ta={endpoint:"setAccountInfo",T:["idToken","deleteProvider"],B:function(e){if(!u(e.deleteProvider))throw new xr("internal-error")}},wa={endpoint:"emailLinkSignin",T:["email","oobCode"],B:sa,J:ca,R:!0},Ca={endpoint:"emailLinkSignin",T:["idToken","email","oobCode"],B:sa,J:ca,R:!0},Ia={endpoint:"getAccountInfo"},Na={endpoint:"getOobConfirmationCode",T:["requestType"],B:function(e){if("EMAIL_SIGNIN"!=e.requestType)throw new xr("internal-error");sa(e)},da:"email"},Ra={endpoint:"getOobConfirmationCode",T:["idToken","requestType"],B:function(e){if("VERIFY_EMAIL"!=e.requestType)throw new xr("internal-error")},da:"email"},Da={endpoint:"getOobConfirmationCode",T:["requestType"],B:function(e){if("PASSWORD_RESET"!=e.requestType)throw new xr("internal-error");sa(e)},da:"email"},Aa={tb:!0,endpoint:"getProjectConfig",Hb:"GET"},Oa={tb:!0,endpoint:"getRecaptchaParam",Hb:"GET",J:function(e){if(!e.recaptchaSiteKey)throw new xr("internal-error")}},Pa={endpoint:"resetPassword",B:ga,da:"email"},ka={endpoint:"sendVerificationCode",T:["phoneNumber","recaptchaToken"],da:"sessionInfo"},La={endpoint:"setAccountInfo",T:["idToken"],B:ua,R:!0},Ma={endpoint:"setAccountInfo",T:["idToken"],B:function(e){if(ua(e),!e.password)throw new xr("weak-password")},J:ca,R:!0},Fa={endpoint:"signupNewUser",J:ca,R:!0},xa={endpoint:"verifyAssertion",B:da,J:fa,R:!0},Ua={endpoint:"verifyAssertion",B:da,J:function(e){if(e.errorMessage&&"USER_NOT_FOUND"==e.errorMessage)throw new xr("user-not-found");if(e.errorMessage)throw $a(e.errorMessage);if(!e[zo])throw new xr("internal-error")},R:!0},Ba={endpoint:"verifyAssertion",B:function(e){if(da(e),!e.idToken)throw new xr("internal-error")},J:fa,R:!0},Va={endpoint:"verifyCustomToken",B:function(e){if(!e.token)throw new xr("invalid-custom-token")},J:ca,R:!0},qa={endpoint:"verifyPassword",B:function(e){if(sa(e),!e.password)throw new xr("wrong-password")},J:ca,R:!0},ja={endpoint:"verifyPhoneNumber",B:ha,J:ca},Wa={endpoint:"verifyPhoneNumber",B:function(e){if(!e.idToken)throw new xr("internal-error");ha(e)},J:function(e){if(e.temporaryProof)throw e.code="credential-already-in-use",$i(e);ca(e)}},Ka={Wb:{USER_NOT_FOUND:"user-not-found"},endpoint:"verifyPhoneNumber",B:ha,J:ca};function Ga(e,t,n){if(!function(e,t){if(!t||!t.length)return!0;if(!e)return!1;for(var n=0;n<t.length;n++){var r=e[t[n]];if(void 0===r||null===r||""===r)return!1}return!0}(n,t.T))return Se(new xr("internal-error"));var r,i=t.Hb||"POST";return Ee(n).then(t.B).then(function(){return t.R&&(n.returnSecureToken=!0),function(e,t,n,r,i,o){var a=Ht(e.g+t);Gt(a,"key",e.b),o&&Gt(a,"cb",v().toString());var s="GET"==n;if(s)for(var u in r)r.hasOwnProperty(u)&&Gt(a,u,r[u]);return new pe(function(t,o){ia(e,a.toString(),function(e){e?e.error?o(Ha(e,i||{})):t(e):o(new xr("network-request-failed"))},n,s?void 0:Fn(dr(r)),e.a,e.h.get())})}(e,t.endpoint,i,n,t.Wb,t.tb||!1)}).then(function(e){return r=e}).then(t.J).then(function(){if(!t.da)return r;if(!(t.da in r))throw new xr("internal-error");return r[t.da]})}function $a(e){return Ha({error:{errors:[{message:e}],code:400,message:e}})}function Ha(e,t){var n=(e.error&&e.error.errors&&e.error.errors[0]||{}).reason||"",r={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(n=r[n]?new xr(r[n]):null)return n;for(var i in n=e.error&&e.error.message||"",ue(r={INVALID_CUSTOM_TOKEN:"invalid-custom-token",CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_EMAIL:"invalid-email",INVALID_PASSWORD:"wrong-password",USER_DISABLED:"user-disabled",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",INVALID_MESSAGE_PAYLOAD:"invalid-message-payload",INVALID_RECIPIENT_EMAIL:"invalid-recipient-email",INVALID_SENDER:"invalid-sender",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",INVALID_PROVIDER_ID:"invalid-provider-id",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",CORS_UNSUPPORTED:"cors-unsupported",DYNAMIC_LINK_NOT_ACTIVATED:"dynamic-link-not-activated",INVALID_APP_ID:"invalid-app-id",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",WEAK_PASSWORD:"weak-password",OPERATION_NOT_ALLOWED:"operation-not-allowed",USER_CANCELLED:"user-cancelled",CAPTCHA_CHECK_FAILED:"captcha-check-failed",INVALID_APP_CREDENTIAL:"invalid-app-credential",INVALID_CODE:"invalid-verification-code",INVALID_PHONE_NUMBER:"invalid-phone-number",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_APP_CREDENTIAL:"missing-app-credential",MISSING_CODE:"missing-verification-code",MISSING_PHONE_NUMBER:"missing-phone-number",MISSING_SESSION_INFO:"missing-verification-id",QUOTA_EXCEEDED:"quota-exceeded",SESSION_EXPIRED:"code-expired",REJECTED_CREDENTIAL:"rejected-credential",INVALID_CONTINUE_URI:"invalid-continue-uri",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",MISSING_IOS_BUNDLE_ID:"missing-ios-bundle-id",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",INVALID_CERT_HASH:"invalid-cert-hash"},t||{}),t=(t=n.match(/^[^\s]+\s*:\s*(.*)$/))&&1<t.length?t[1]:void 0,r)if(0===n.indexOf(i))return new xr(r[i],t);return!t&&e&&(t=lr(e)),new xr("internal-error",t)}var Qa,Ya={Zc:{$a:"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",hb:"https://securetoken.googleapis.com/v1/token",id:"p"},ad:{$a:"https://staging-www.sandbox.googleapis.com/identitytoolkit/v3/relyingparty/",hb:"https://staging-securetoken.sandbox.googleapis.com/v1/token",id:"s"},bd:{$a:"https://www-googleapis-test.sandbox.google.com/identitytoolkit/v3/relyingparty/",hb:"https://test-securetoken.sandbox.googleapis.com/v1/token",id:"t"}};function Xa(e){for(var t in Ya)if(Ya[t].id===e)return{firebaseEndpoint:(e=Ya[t]).$a,secureTokenEndpoint:e.hb};return null}function za(e){this.b=e,this.a=null,this.eb=function(e){return(ts||(ts=new pe(function(e,t){function r(){yr(),or("gapi.load")("gapi.iframes",{callback:e,ontimeout:function(){yr(),t(Error("Network Error"))},timeout:Za.get()})}if(or("gapi.iframes.Iframe"))e();else if(or("gapi.load"))r();else{var i="__iframefcb"+Math.floor(1e6*Math.random()).toString();n[i]=function(){or("gapi.load")?r():t(Error("Network Error"))},Ee(jo(i=vn(Ja,{onload:i}))).s(function(){t(Error("Network Error"))})}}).s(function(e){throw ts=null,e}))).then(function(){return new pe(function(t,n){or("gapi.iframes.getContext")().open({where:document.body,url:e.b,messageHandlersFilter:or("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"),attributes:{style:{position:"absolute",top:"-100px",width:"1px",height:"1px"}},dontclear:!0},function(r){function i(){clearTimeout(o),t()}e.a=r,e.a.restyle({setHideOnLeave:!1});var o=setTimeout(function(){n(Error("Network Error"))},es.get());r.ping(i).then(i,function(){n(Error("Network Error"))})})})})}(this)}Qa=Xa("__EID__")?"__EID__":void 0;var Ja=mn("https://apis.google.com/js/api.js?onload=%{onload}"),Za=new gr(3e4,6e4),es=new gr(5e3,15e3),ts=null;function ns(e,t,n){this.i=e,this.g=t,this.h=n,this.f=null,this.a=Qt(this.i,"/__/auth/iframe"),Gt(this.a,"apiKey",this.g),Gt(this.a,"appName",this.h),this.b=null,this.c=[]}function rs(e,t,n,r,i){this.o=e,this.m=t,this.c=n,this.l=r,this.h=this.g=this.i=null,this.a=i,this.f=null}function is(e){try{return firebase.app(e).auth().xa()}catch(e){return[]}}function os(e,t,n,r,i){this.m=e,this.f=t,this.b=n,this.c=r||null,this.h=i||null,this.o=this.u=this.v=null,this.g=[],this.l=this.a=null}function as(e){var t=qn();return function(e){return Ga(e,Aa,{}).then(function(e){return e.authorizedDomains||[]})}(e).then(function(e){e:{var n=Ht(t),r=n.c;n=n.b;for(var i=0;i<e.length;i++){var o=e[i],a=n,s=r;if(0==o.indexOf("chrome-extension://")?a=Ht(o).b==a&&"chrome-extension"==s:"http"!=s&&"https"!=s?a=!1:$n.test(o)?a=a==o:(o=o.split(".").join("\\."),a=new RegExp("^(.+\\."+o+"|"+o+")$","i").test(a)),a){e=!0;break e}}e=!1}if(!e)throw new Ki(qn())})}function ss(e){return e.l?e.l:(e.l=Hn().then(function(){if(!e.u){var t=e.c,n=e.h,r=is(e.b),i=new ns(e.m,e.f,e.b);i.f=t,i.b=n,i.c=B(r||[]),e.u=i.toString()}e.i=new za(e.u),function(e){if(!e.i)throw Error("IfcHandler must be initialized!");!function(e,t){e.eb.then(function(){e.a.register("authEvent",t,or("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})}(e.i,function(t){var n={};if(t&&t.authEvent){var r=!1;for(t=qi(t.authEvent),n=0;n<e.g.length;n++)r=e.g[n](t)||r;return(n={}).status=r?"ACK":"ERROR",Ee(n)}return n.status="ERROR",Ee(n)})}(e)}),e.l)}function us(e){return e.o||(e.v=e.c?rr(e.c,is(e.b)):null,e.o=new Yo(e.f,Xa(e.h),e.v)),e.o}function cs(e,t,n,r,i,o,a,s,u,c){return(e=new rs(e,t,n,r,i)).i=o,e.g=a,e.h=s,e.b=ie(u||null),e.f=c,e.toString()}function hs(e){if(this.a=e||firebase.INTERNAL.reactNative&&firebase.INTERNAL.reactNative.AsyncStorage,!this.a)throw new xr("internal-error","The React Native compatibility library was not found.");this.type="asyncStorage"}function ls(e){this.b=e,this.a={},this.c=y(this.f,this)}ns.prototype.toString=function(){return this.f?Gt(this.a,"v",this.f):sn(this.a.a,"v"),this.b?Gt(this.a,"eid",this.b):sn(this.a.a,"eid"),this.c.length?Gt(this.a,"fw",this.c.join(",")):sn(this.a.a,"fw"),this.a.toString()},rs.prototype.toString=function(){var e=Qt(this.o,"/__/auth/handler");if(Gt(e,"apiKey",this.m),Gt(e,"appName",this.c),Gt(e,"authType",this.l),this.a.isOAuthProvider){var t=this.a;try{var n=firebase.app(this.c).auth().ea()}catch(e){n=null}for(var r in t.Za=n,Gt(e,"providerId",this.a.providerId),n=dr((t=this.a).xb))n[r]=n[r].toString();r=t.Cc,n=ie(n);for(var i=0;i<r.length;i++){var o=r[i];o in n&&delete n[o]}t.bb&&t.Za&&!n[t.bb]&&(n[t.bb]=t.Za),re(n)||Gt(e,"customParameters",lr(n))}if("function"==typeof this.a.Db&&((t=this.a.Db()).length&&Gt(e,"scopes",t.join(","))),this.i?Gt(e,"redirectUrl",this.i):sn(e.a,"redirectUrl"),this.g?Gt(e,"eventId",this.g):sn(e.a,"eventId"),this.h?Gt(e,"v",this.h):sn(e.a,"v"),this.b)for(var a in this.b)this.b.hasOwnProperty(a)&&!$t(e,a)&&Gt(e,a,this.b[a]);return this.f?Gt(e,"eid",this.f):sn(e.a,"eid"),(a=is(this.c)).length&&Gt(e,"fw",a.join(",")),e.toString()},(e=os.prototype).Ea=function(e,t,n){var r=new xr("popup-closed-by-user"),i=new xr("web-storage-unsupported"),o=this,a=!1;return this.ga().then(function(){(function(e){var t={type:"webStorageSupport"};return ss(e).then(function(){return function(e,t){return e.eb.then(function(){return new pe(function(n){e.a.send(t.type,t,n,or("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})})}(e.i,t)}).then(function(e){if(e&&e.length&&void 0!==e[0].webStorageSupport)return e[0].webStorageSupport;throw Error()})})(o).then(function(n){n||(e&&Kn(e),t(i),a=!0)})}).s(function(){}).then(function(){if(!a)return function(e){return new pe(function(t){return function n(){Lt(2e3).then(function(){if(e&&!e.closed)return n();t()})}()})}(e)}).then(function(){if(!a)return Lt(n).then(function(){t(r)})})},e.Lb=function(){var e=ir();return!hr(e)&&!mr(e)},e.Gb=function(){return!1},e.Bb=function(e,t,n,r,i,o,a){if(!e)return Se(new xr("popup-blocked"));if(a&&!hr())return this.ga().s(function(t){Kn(e),i(t)}),r(),Ee();this.a||(this.a=as(us(this)));var s=this;return this.a.then(function(){var t=s.ga().s(function(t){throw Kn(e),i(t),t});return r(),t}).then(function(){(Bi(n),a)||jn(cs(s.m,s.f,s.b,t,n,null,o,s.c,void 0,s.h),e)}).s(function(e){throw"auth/network-request-failed"==e.code&&(s.a=null),e})},e.Ca=function(e,t,n){this.a||(this.a=as(us(this)));var r=this;return this.a.then(function(){Bi(t),jn(cs(r.m,r.f,r.b,e,t,qn(),n,r.c,void 0,r.h))}).s(function(e){throw"auth/network-request-failed"==e.code&&(r.a=null),e})},e.ga=function(){var e=this;return ss(this).then(function(){return e.i.eb}).s(function(){throw e.a=null,new xr("network-request-failed")})},e.Pb=function(){return!0},e.va=function(e){this.g.push(e)},e.Ka=function(e){x(this.g,function(t){return t==e})},(e=hs.prototype).get=function(e){return Ee(this.a.getItem(e)).then(function(e){return e&&fr(e)})},e.set=function(e,t){return Ee(this.a.setItem(e,lr(t)))},e.P=function(e){return Ee(this.a.removeItem(e))},e.Y=function(){},e.ca=function(){};var ds,fs=[];function ps(e){this.a=e}function ms(e){this.c=e,this.b=!1,this.a=[]}function ys(e,t,n,r){var i,o,a,s,u=n||{},c=null;if(e.b)return Se(Error("connection_unavailable"));var h=r?800:50,l="undefined"!=typeof MessageChannel?new MessageChannel:null;return new pe(function(n,r){l?(i=Math.floor(Math.random()*Math.pow(10,20)).toString(),l.port1.start(),a=setTimeout(function(){r(Error("unsupported_event"))},h),c={messageChannel:l,onMessage:o=function(e){e.data.eventId===i&&("ack"===e.data.status?(clearTimeout(a),s=setTimeout(function(){r(Error("timeout"))},3e3)):"done"===e.data.status?(clearTimeout(s),void 0!==e.data.response?n(e.data.response):r(Error("unknown_error"))):(clearTimeout(a),clearTimeout(s),r(Error("invalid_response"))))}},e.a.push(c),l.port1.addEventListener("message",o),e.c.postMessage({eventType:t,eventId:i,data:u},[l.port2])):r(Error("connection_unavailable"))}).then(function(t){return gs(e,c),t}).s(function(t){throw gs(e,c),t})}function gs(e,t){if(t){var n=t.messageChannel,r=t.onMessage;n&&(n.port1.removeEventListener("message",r),n.port1.close()),x(e.a,function(e){return e==t})}}function vs(){if(!Es())throw new xr("web-storage-unsupported");this.c={},this.a=[],this.b=0,this.m=n.indexedDB,this.type="indexedDB",this.g=this.l=this.f=this.i=null,this.u=!1,this.h=null;var e=this;Xn()&&self?(this.l=function(){var e=Xn()?self:null;if(P(fs,function(n){n.b==e&&(t=n)}),!t){var t=new ls(e);fs.push(t)}return t}(),this.l.subscribe("keyChanged",function(t,n){return Is(e).then(function(t){return 0<t.length&&P(e.a,function(e){e(t)}),{keyProcessed:M(t,n.key)}})}),this.l.subscribe("ping",function(){return Ee(["keyChanged"])})):function(){var e=n.navigator;return e&&e.serviceWorker?Ee().then(function(){return e.serviceWorker.ready}).then(function(e){return e.active||null}).s(function(){return null}):Ee(null)}().then(function(t){(e.h=t)&&(e.g=new ms(new ps(t)),ys(e.g,"ping",null,!0).then(function(t){t[0].fulfilled&&M(t[0].value,"keyChanged")&&(e.u=!0)}).s(function(){}))})}function _s(e){return new pe(function(t,n){var r=e.m.open("firebaseLocalStorageDb",1);r.onerror=function(e){try{e.preventDefault()}catch(e){}n(Error(e.target.error))},r.onupgradeneeded=function(e){e=e.target.result;try{e.createObjectStore("firebaseLocalStorage",{keyPath:"fbase_key"})}catch(e){n(e)}},r.onsuccess=function(r){(r=r.target.result).objectStoreNames.contains("firebaseLocalStorage")?t(r):function(e){return new pe(function(t,n){var r=e.m.deleteDatabase("firebaseLocalStorageDb");r.onsuccess=function(){t()},r.onerror=function(e){n(Error(e.target.error))}})}(e).then(function(){return _s(e)}).then(function(e){t(e)}).s(function(e){n(e)})}})}function bs(e){return e.o||(e.o=_s(e)),e.o}function Es(){try{return!!n.indexedDB}catch(e){return!1}}function Ss(e){return e.objectStore("firebaseLocalStorage")}function Ts(e,t){return e.transaction(["firebaseLocalStorage"],t?"readwrite":"readonly")}function ws(e){return new pe(function(t,n){e.onsuccess=function(e){e&&e.target?t(e.target.result):t()},e.onerror=function(e){n(Error(e.target.errorCode))}})}function Cs(e,t){return e.g&&e.h&&function(){var e=n.navigator;return e&&e.serviceWorker&&e.serviceWorker.controller||null}()===e.h?ys(e.g,"keyChanged",{key:t},e.u).then(function(){}).s(function(){}):Ee()}function Is(e){return bs(e).then(function(e){var t=Ss(Ts(e,!1));return t.getAll?ws(t.getAll()):new pe(function(e,n){var r=[],i=t.openCursor();i.onsuccess=function(t){(t=t.target.result)?(r.push(t.value),t.continue()):e(r)},i.onerror=function(e){n(Error(e.target.errorCode))}})}).then(function(t){var n={},r=[];if(0==e.b){for(r=0;r<t.length;r++)n[t[r].fbase_key]=t[r].value;r=function e(t,n){var r,i=[];for(r in t)r in n?typeof t[r]!=typeof n[r]?i.push(r):"object"==typeof t[r]&&null!=t[r]&&null!=n[r]?0<e(t[r],n[r]).length&&i.push(r):t[r]!==n[r]&&i.push(r):i.push(r);for(r in n)r in t||i.push(r);return i}(e.c,n),e.c=n}return r})}function Ns(e){e.i&&e.i.cancel("STOP_EVENT"),e.f&&(clearTimeout(e.f),e.f=null)}function Rs(e){var t=this,n=null;this.a=[],this.type="indexedDB",this.c=e,this.b=Ee().then(function(){if(Es()){var e=pr(),r="__sak"+e;return ds||(ds=new vs),(n=ds).set(r,e).then(function(){return n.get(r)}).then(function(t){if(t!==e)throw Error("indexedDB not supported!");return n.P(r)}).then(function(){return n}).s(function(){return t.c})}return t.c}).then(function(e){return t.type=e.type,e.Y(function(e){P(t.a,function(t){t(e)})}),e})}function Ds(){this.a={},this.type="inMemory"}function As(){if(!function(){var e="Node"==zn();if(!(e=Os()||e&&firebase.INTERNAL.node&&firebase.INTERNAL.node.localStorage))return!1;try{return e.setItem("__sak","1"),e.removeItem("__sak"),!0}catch(e){return!1}}()){if("Node"==zn())throw new xr("internal-error","The LocalStorage compatibility library was not found.");throw new xr("web-storage-unsupported")}this.a=Os()||firebase.INTERNAL.node.localStorage,this.type="localStorage"}function Os(){try{var e=n.localStorage,t=pr();return e&&(e.setItem(t,"1"),e.removeItem(t)),e}catch(e){return null}}function Ps(){this.type="nullStorage"}function ks(){if(!function(){var e="Node"==zn();if(!(e=Ls()||e&&firebase.INTERNAL.node&&firebase.INTERNAL.node.sessionStorage))return!1;try{return e.setItem("__sak","1"),e.removeItem("__sak"),!0}catch(e){return!1}}()){if("Node"==zn())throw new xr("internal-error","The SessionStorage compatibility library was not found.");throw new xr("web-storage-unsupported")}this.a=Ls()||firebase.INTERNAL.node.sessionStorage,this.type="sessionStorage"}function Ls(){try{var e=n.sessionStorage,t=pr();return e&&(e.setItem(t,"1"),e.removeItem(t)),e}catch(e){return null}}ls.prototype.f=function(e){var t=e.data.eventType,n=e.data.eventId,r=this.a[t];if(r&&0<r.length){e.ports[0].postMessage({status:"ack",eventId:n,eventType:t,response:null});var i=[];P(r,function(t){i.push(Ee().then(function(){return t(e.origin,e.data.data)}))}),we(i).then(function(r){var i=[];P(r,function(e){i.push({fulfilled:e.Cb,value:e.value,reason:e.reason?e.reason.message:void 0})}),P(i,function(e){for(var t in e)void 0===e[t]&&delete e[t]}),e.ports[0].postMessage({status:"done",eventId:n,eventType:t,response:i})})}},ls.prototype.subscribe=function(e,t){re(this.a)&&this.b.addEventListener("message",this.c),void 0===this.a[e]&&(this.a[e]=[]),this.a[e].push(t)},ls.prototype.unsubscribe=function(e,t){void 0!==this.a[e]&&t?(x(this.a[e],function(e){return e==t}),0==this.a[e].length&&delete this.a[e]):t||delete this.a[e],re(this.a)&&this.b.removeEventListener("message",this.c)},ps.prototype.postMessage=function(e,t){this.a.postMessage(e,t)},ms.prototype.close=function(){for(;0<this.a.length;)gs(this,this.a[0]);this.b=!0},(e=vs.prototype).set=function(e,t){var n,r=!1,i=this;return bs(this).then(function(t){return ws((t=Ss(Ts(n=t,!0))).get(e))}).then(function(o){var a=Ss(Ts(n,!0));return o?(o.value=t,ws(a.put(o))):(i.b++,r=!0,(o={}).fbase_key=e,o.value=t,ws(a.add(o)))}).then(function(){return i.c[e]=t,Cs(i,e)}).ia(function(){r&&i.b--})},e.get=function(e){return bs(this).then(function(t){return ws(Ss(Ts(t,!1)).get(e))}).then(function(e){return e&&e.value})},e.P=function(e){var t=!1,n=this;return bs(this).then(function(r){return t=!0,n.b++,ws(Ss(Ts(r,!0)).delete(e))}).then(function(){return delete n.c[e],Cs(n,e)}).ia(function(){t&&n.b--})},e.Y=function(e){0==this.a.length&&function(e){Ns(e),function t(){e.f=setTimeout(function(){e.i=Is(e).then(function(t){0<t.length&&P(e.a,function(e){e(t)})}).then(function(){t()}).s(function(e){"STOP_EVENT"!=e.message&&t()})},800)}()}(this),this.a.push(e)},e.ca=function(e){x(this.a,function(t){return t==e}),0==this.a.length&&Ns(this)},(e=Rs.prototype).get=function(e){return this.b.then(function(t){return t.get(e)})},e.set=function(e,t){return this.b.then(function(n){return n.set(e,t)})},e.P=function(e){return this.b.then(function(t){return t.P(e)})},e.Y=function(e){this.a.push(e)},e.ca=function(e){x(this.a,function(t){return t==e})},(e=Ds.prototype).get=function(e){return Ee(this.a[e])},e.set=function(e,t){return this.a[e]=t,Ee()},e.P=function(e){return delete this.a[e],Ee()},e.Y=function(){},e.ca=function(){},(e=As.prototype).get=function(e){var t=this;return Ee().then(function(){return fr(t.a.getItem(e))})},e.set=function(e,t){var n=this;return Ee().then(function(){var r=lr(t);null===r?n.P(e):n.a.setItem(e,r)})},e.P=function(e){var t=this;return Ee().then(function(){t.a.removeItem(e)})},e.Y=function(e){n.window&>(n.window,"storage",e)},e.ca=function(e){n.window&&bt(n.window,"storage",e)},(e=Ps.prototype).get=function(){return Ee(null)},e.set=function(){return Ee()},e.P=function(){return Ee()},e.Y=function(){},e.ca=function(){},(e=ks.prototype).get=function(e){var t=this;return Ee().then(function(){return fr(t.a.getItem(e))})},e.set=function(e,t){var n=this;return Ee().then(function(){var r=lr(t);null===r?n.P(e):n.a.setItem(e,r)})},e.P=function(e){var t=this;return Ee().then(function(){t.a.removeItem(e)})},e.Y=function(){},e.ca=function(){};var Ms,Fs,xs={A:As,Qa:ks},Us={A:As,Qa:ks},Bs={A:hs,Qa:Ps},Vs={A:As,Qa:Ps},qs={Yc:"local",NONE:"none",$c:"session"};function js(){var e=!(mr(ir())||!Yn()),t=hr(),r=ar();this.o=e,this.h=t,this.l=r,this.a={},Ms||(Ms=new function(){var e={};e.Browser=xs,e.Node=Us,e.ReactNative=Bs,e.Worker=Vs,this.a=e[zn()]}),e=Ms;try{this.g=!Vn()&&br()||!n.indexedDB?new e.a.A:new Rs(Xn()?new Ds:new e.a.A)}catch(e){this.g=new Ds,this.h=!0}try{this.i=new e.a.Qa}catch(e){this.i=new Ds}this.m=new Ds,this.f=y(this.Ob,this),this.b={}}function Ws(){return Fs||(Fs=new js),Fs}function Ks(e,t){switch(t){case"session":return e.i;case"none":return e.m;default:return e.g}}function Gs(e,t){return"firebase:"+e.name+(t?":"+t:"")}function $s(e,t,n){return n=Gs(t,n),"local"==t.A&&(e.b[n]=null),Ks(e,t.A).P(n)}function Hs(e){e.c&&(clearInterval(e.c),e.c=null)}(e=js.prototype).get=function(e,t){return Ks(this,e.A).get(Gs(e,t))},e.set=function(e,t,n){var r=Gs(e,n),i=this,o=Ks(this,e.A);return o.set(r,t).then(function(){return o.get(r)}).then(function(t){"local"==e.A&&(i.b[r]=t)})},e.addListener=function(e,t,r){e=Gs(e,t),this.l&&(this.b[e]=n.localStorage.getItem(e)),re(this.a)&&(Ks(this,"local").Y(this.f),this.h||(Vn()||!br())&&n.indexedDB||!this.l||function(e){Hs(e),e.c=setInterval(function(){for(var t in e.a){var r=n.localStorage.getItem(t),i=e.b[t];r!=i&&(e.b[t]=r,r=new st({type:"storage",key:t,target:window,oldValue:i,newValue:r,a:!0}),e.Ob(r))}},1e3)}(this)),this.a[e]||(this.a[e]=[]),this.a[e].push(r)},e.removeListener=function(e,t,n){e=Gs(e,t),this.a[e]&&(x(this.a[e],function(e){return e==n}),0==this.a[e].length&&delete this.a[e]),re(this.a)&&(Ks(this,"local").ca(this.f),Hs(this))},e.Ob=function(e){if(e&&e.f){var t=e.a.key;if(null==t)for(var r in this.a){var i=this.b[r];void 0===i&&(i=null);var o=n.localStorage.getItem(r);o!==i&&(this.b[r]=o,this.Wa(r))}else if(0==t.indexOf("firebase:")&&this.a[t]){if(void 0!==e.a.a?Ks(this,"local").ca(this.f):Hs(this),this.o)if(r=n.localStorage.getItem(t),(i=e.a.newValue)!==r)null!==i?n.localStorage.setItem(t,i):n.localStorage.removeItem(t);else if(this.b[t]===i&&void 0===e.a.a)return;var a=this;r=function(){void 0===e.a.a&&a.b[t]===n.localStorage.getItem(t)||(a.b[t]=n.localStorage.getItem(t),a.Wa(t))},We&&Je&&10==Je&&n.localStorage.getItem(t)!==e.a.newValue&&e.a.newValue!==e.a.oldValue?setTimeout(r,10):r()}}else P(e,y(this.Wa,this))},e.Wa=function(e){this.a[e]&&P(this.a[e],function(e){e()})};var Qs,Ys={name:"authEvent",A:"local"};function Xs(e,t){this.b=zs,this.f=n.Uint8Array?new Uint8Array(this.b):Array(this.b),this.g=this.c=0,this.a=[],this.i=e,this.h=t,this.l=n.Int32Array?new Int32Array(64):Array(64),void 0!==Qs||(Qs=n.Int32Array?new Int32Array(iu):iu),this.reset()}_(Xs,function(){this.b=-1});for(var zs=64,Js=zs-1,Zs=[],eu=0;eu<Js;eu++)Zs[eu]=0;var tu=U(128,Zs);function nu(e){for(var t=e.f,n=e.l,r=0,i=0;i<t.length;)n[r++]=t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3],i=4*r;for(t=16;64>t;t++){i=0|n[t-15],r=0|n[t-2];var o=(0|n[t-16])+((i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3)|0,a=(0|n[t-7])+((r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10)|0;n[t]=o+a|0}r=0|e.a[0],i=0|e.a[1];var s=0|e.a[2],u=0|e.a[3],c=0|e.a[4],h=0|e.a[5],l=0|e.a[6];for(o=0|e.a[7],t=0;64>t;t++){var d=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&i^r&s^i&s)|0;a=(o=o+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))|0)+((a=(a=c&h^~c&l)+(0|Qs[t])|0)+(0|n[t])|0)|0,o=l,l=h,h=c,c=u+a|0,u=s,s=i,i=r,r=a+d|0}e.a[0]=e.a[0]+r|0,e.a[1]=e.a[1]+i|0,e.a[2]=e.a[2]+s|0,e.a[3]=e.a[3]+u|0,e.a[4]=e.a[4]+c|0,e.a[5]=e.a[5]+h|0,e.a[6]=e.a[6]+l|0,e.a[7]=e.a[7]+o|0}function ru(e,t,n){void 0===n&&(n=t.length);var i=0,o=e.c;if(r(t))for(;i<n;)e.f[o++]=t.charCodeAt(i++),o==e.b&&(nu(e),o=0);else{if(!c(t))throw Error("message must be string or array");for(;i<n;){var a=t[i++];if(!("number"==typeof a&&0<=a&&255>=a&&a==(0|a)))throw Error("message must be a byte array");e.f[o++]=a,o==e.b&&(nu(e),o=0)}}e.c=o,e.g+=n}Xs.prototype.reset=function(){this.g=this.c=0,this.a=n.Int32Array?new Int32Array(this.h):B(this.h)};var iu=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function ou(){Xs.call(this,8,au)}_(ou,Xs);var au=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function su(e,t,n,r,i){this.m=e,this.i=t,this.l=n,this.o=r||null,this.u=i||null,this.h=t+":"+n,this.v=new function(){this.a=Ws()},this.g=new function(e){this.a=e,this.b=Ws()}(this.h),this.f=null,this.b=[],this.a=this.c=null}function uu(e){return new xr("invalid-cordova-configuration",e)}function cu(e){var t=new ou;ru(t,e),e=[];var n=8*t.g;56>t.c?ru(t,tu,56-t.c):ru(t,tu,t.b-(t.c-56));for(var r=63;56<=r;r--)t.f[r]=255&n,n/=256;for(nu(t),r=n=0;r<t.i;r++)for(var i=24;0<=i;i-=8)e[n++]=t.a[r]>>i&255;return function(e){return k(e,function(e){return 1<(e=e.toString(16)).length?e:"0"+e}).join("")}(e)}function hu(e,t){for(var n=0;n<e.b.length;n++)try{e.b[n](t)}catch(e){}}function lu(e){return e.f||(e.f=e.ga().then(function(){return new pe(function(t){e.va(function n(r){return t(r),e.Ka(n),!1}),function(e){function t(t){i=!0,o&&o.cancel(),du(e).then(function(n){var i=r;if(n&&t&&t.url){var o=null;-1!=(i=yi(t.url)).indexOf("/__/auth/callback")&&(o=(o="object"==typeof(o=fr($t(o=Ht(i),"firebaseError")||null))?Ur(o):null)?new Vi(n.b,n.c,null,null,o):new Vi(n.b,n.c,i,n.g)),i=o||r}hu(e,i)})}var r=new Vi("unknown",null,null,null,new xr("no-auth-event")),i=!1,o=Lt(500).then(function(){return du(e).then(function(){i||hu(e,r)})}),a=n.handleOpenURL;n.handleOpenURL=function(e){if(0==e.toLowerCase().indexOf(or("BuildInfo.packageName",n).toLowerCase()+"://")&&t({url:e}),"function"==typeof a)try{a(e)}catch(e){console.error(e)}},Wi||(Wi=new ji),Wi.subscribe(t)}(e)})})),e.f}function du(e){var t=null;return function(e){return e.b.get(Ys,e.a).then(function(e){return qi(e)})}(e.g).then(function(n){return t=n,$s((n=e.g).b,Ys,n.a)}).then(function(){return t})}(e=su.prototype).ga=function(){return this.za?this.za:this.za=(Qn(void 0)?Hn().then(function(){return new pe(function(e,t){var r=n.document,i=setTimeout(function(){t(Error("Cordova framework is not ready."))},1e3);r.addEventListener("deviceready",function(){clearTimeout(i),e()},!1)})}):Se(Error("Cordova must run in an Android or iOS file scheme."))).then(function(){if("function"!=typeof or("universalLinks.subscribe",n))throw uu("cordova-universal-links-plugin-fix is not installed");if(void 0===or("BuildInfo.packageName",n))throw uu("cordova-plugin-buildinfo is not installed");if("function"!=typeof or("cordova.plugins.browsertab.openUrl",n))throw uu("cordova-plugin-browsertab is not installed");if("function"!=typeof or("cordova.InAppBrowser.open",n))throw uu("cordova-plugin-inappbrowser is not installed")},function(){throw new xr("cordova-not-ready")})},e.Ea=function(e,t){return t(new xr("operation-not-supported-in-this-environment")),Ee()},e.Bb=function(){return Se(new xr("operation-not-supported-in-this-environment"))},e.Pb=function(){return!1},e.Lb=function(){return!0},e.Gb=function(){return!0},e.Ca=function(e,t,r){if(this.c)return Se(new xr("redirect-operation-pending"));var i=this,o=n.document,a=null,s=null,u=null,c=null;return this.c=Ee().then(function(){return Bi(t),lu(i)}).then(function(){return function(e,t,r,i){var o=function(){for(var e=20,t=[];0<e;)t.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.floor(62*Math.random()))),e--;return t.join("")}(),a=new Vi(t,i,null,o,new xr("no-auth-event")),s=or("BuildInfo.packageName",n);if("string"!=typeof s)throw new xr("invalid-cordova-configuration");var u=or("BuildInfo.displayName",n),c={};if(ir().toLowerCase().match(/iphone|ipad|ipod/))c.ibi=s;else{if(!ir().toLowerCase().match(/android/))return Se(new xr("operation-not-supported-in-this-environment"));c.apn=s}u&&(c.appDisplayName=u),o=cu(o),c.sessionId=o;var h=cs(e.m,e.i,e.l,t,r,null,i,e.o,c,e.u);return e.ga().then(function(){var t=e.h;return e.v.a.set(Ys,a.D(),t)}).then(function(){var t=or("cordova.plugins.browsertab.isAvailable",n);if("function"!=typeof t)throw new xr("invalid-cordova-configuration");var r=null;t(function(t){if(t){if("function"!=typeof(r=or("cordova.plugins.browsertab.openUrl",n)))throw new xr("invalid-cordova-configuration");r(h)}else{if("function"!=typeof(r=or("cordova.InAppBrowser.open",n)))throw new xr("invalid-cordova-configuration");t=!(!(t=ir()).match(/(iPad|iPhone|iPod).*OS 7_\d/i)&&!t.match(/(iPad|iPhone|iPod).*OS 8_\d/i)),e.a=r(h,t?"_blank":"_system","location=yes")}})})}(i,e,t,r)}).then(function(){return new pe(function(e,t){s=function(){var t=or("cordova.plugins.browsertab.close",n);return e(),"function"==typeof t&&t(),i.a&&"function"==typeof i.a.close&&(i.a.close(),i.a=null),!1},i.va(s),u=function(){a||(a=Lt(2e3).then(function(){t(new xr("redirect-cancelled-by-user"))}))},c=function(){vr()&&u()},o.addEventListener("resume",u,!1),ir().toLowerCase().match(/android/)||o.addEventListener("visibilitychange",c,!1)}).s(function(e){return du(i).then(function(){throw e})})}).ia(function(){u&&o.removeEventListener("resume",u,!1),c&&o.removeEventListener("visibilitychange",c,!1),a&&a.cancel(),s&&i.Ka(s),i.c=null})},e.va=function(e){this.b.push(e),lu(this).s(function(t){"auth/invalid-cordova-configuration"===t.code&&(t=new Vi("unknown",null,null,null,new xr("no-auth-event")),e(t))})},e.Ka=function(e){x(this.b,function(t){return t==e})};var fu={name:"pendingRedirect",A:"session"};function pu(e){return $s(e.b,fu,e.a)}function mu(e,t,n){this.u=e,this.l=t,this.m=n,this.h=[],this.f=!1,this.i=y(this.ab,this),this.b=new Cu,this.o=new Du,this.g=new function(e){this.a=e,this.b=Ws()}(this.l+":"+this.m),this.c={},this.c.unknown=this.b,this.c.signInViaRedirect=this.b,this.c.linkViaRedirect=this.b,this.c.reauthViaRedirect=this.b,this.c.signInViaPopup=this.o,this.c.linkViaPopup=this.o,this.c.reauthViaPopup=this.o,this.a=yu(this.u,this.l,this.m,Qa)}function yu(e,t,n,r){var i=firebase.SDK_VERSION||null;return Qn()?new su(e,t,n,i,r):new os(e,t,n,i,r)}function gu(e){e.f||(e.f=!0,e.a.va(e.i));var t=e.a;return e.a.ga().s(function(n){throw e.a==t&&e.reset(),n})}function vu(e){e.a.Lb()&&gu(e).s(function(t){var n=new Vi("unknown",null,null,null,new xr("operation-not-supported-in-this-environment"));Su(t)&&e.ab(n)}),e.a.Gb()||Iu(e.b)}(e=mu.prototype).reset=function(){this.f=!1,this.a.Ka(this.i),this.a=yu(this.u,this.l,this.m)},e.Xa=function(){this.b.Xa()},e.subscribe=function(e){if(M(this.h,e)||this.h.push(e),!this.f){var t=this;(function(e){return e.b.get(fu,e.a).then(function(e){return"pending"==e})})(this.g).then(function(e){e?pu(t.g).then(function(){gu(t).s(function(e){var n=new Vi("unknown",null,null,null,new xr("operation-not-supported-in-this-environment"));Su(e)&&t.ab(n)})}):vu(t)}).s(function(){vu(t)})}},e.unsubscribe=function(e){x(this.h,function(t){return t==e})},e.ab=function(e){if(!e)throw new xr("invalid-auth-event");for(var t=!1,n=0;n<this.h.length;n++){var r=this.h[n];if(r.ub(e.b,e.c)){(t=this.c[e.b])&&t.h(e,r),t=!0;break}}return Iu(this.b),t};var _u=new gr(2e3,1e4),bu=new gr(3e4,6e4);function Eu(e,t,n,r,i,o){return e.a.Bb(t,n,r,function(){e.f||(e.f=!0,e.a.va(e.i))},function(){e.reset()},i,o)}function Su(e){return!(!e||"auth/cordova-not-ready"!=e.code)}mu.prototype.fa=function(){return this.b.fa()},mu.prototype.Ca=function(e,t,n){var r,i=this;return function(e){return e.b.set(fu,"pending",e.a)}(this.g).then(function(){return i.a.Ca(e,t,n).s(function(e){if(Su(e))throw new xr("operation-not-supported-in-this-environment");return r=e,pu(i.g).then(function(){throw r})}).then(function(){return i.a.Pb()?new pe(function(){}):pu(i.g).then(function(){return i.fa()}).then(function(){}).s(function(){})})})},mu.prototype.Ea=function(e,t,n,r){return this.a.Ea(n,function(n){e.ha(t,null,n,r)},_u.get())};var Tu={};function wu(e,t,n){var r=t+":"+n;return Tu[r]||(Tu[r]=new mu(e,t,n)),Tu[r]}function Cu(){this.b=null,this.f=[],this.c=[],this.a=null,this.i=this.g=!1}function Iu(e){e.g||(e.g=!0,Ru(e,!1,null,null))}function Nu(e,t){if(e.b=function(){return Ee(t)},e.f.length)for(var n=0;n<e.f.length;n++)e.f[n](t)}function Ru(e,t,n,r){t?r?function(e,t){if(e.b=function(){return Se(t)},e.c.length)for(var n=0;n<e.c.length;n++)e.c[n](t)}(e,r):Nu(e,n):Nu(e,{user:null}),e.f=[],e.c=[]}function Du(){}function Au(){this.rb=!1,Object.defineProperty(this,"appVerificationDisabled",{get:function(){return this.rb},set:function(e){this.rb=e},enumerable:!1})}function Ou(e,t){this.a=t,Cr(this,"verificationId",e)}function Pu(e,t,n,r){return new Fi(e).Ta(t,n).then(function(e){return new Ou(e,r)})}function ku(e,t,n){if(this.h=e,this.i=t,this.g=n,this.c=3e4,this.f=96e4,this.b=null,this.a=this.c,this.f<this.c)throw Error("Proactive refresh lower bound greater than upper bound!")}function Lu(e){this.f=e,this.b=this.a=null,this.c=0}function Mu(e,t){var n=t[zo],r=t.refreshToken;t=Fu(t.expiresIn),e.b=n,e.c=t,e.a=r}function Fu(e){return v()+1e3*parseInt(e,10)}function xu(e,t){return function(e,t){return new pe(function(n,r){"refresh_token"==t.grant_type&&t.refresh_token||"authorization_code"==t.grant_type&&t.code?ia(e,e.i+"?key="+encodeURIComponent(e.b),function(e){e?e.error?r(Ha(e)):e.access_token&&e.refresh_token?n(e):r(new xr("internal-error")):r(new xr("network-request-failed"))},"POST",an(t).toString(),e.f,e.l.get()):r(new xr("internal-error"))})}(e.f,t).then(function(t){return e.b=t.access_token,e.c=Fu(t.expires_in),e.a=t.refresh_token,{accessToken:e.b,expirationTime:e.c,refreshToken:e.a}}).s(function(t){throw"auth/user-token-expired"==t.code&&(e.a=null),t})}function Uu(e,t){this.a=e||null,this.b=t||null,Ir(this,{lastSignInTime:_r(t||null),creationTime:_r(e||null)})}function Bu(e,t){for(var n in at.call(this,e),t)this[n]=t[n]}function Vu(e,t,n){this.G=[],this.m=e.apiKey,this.o=e.appName,this.u=e.authDomain||null,e=firebase.SDK_VERSION?rr(firebase.SDK_VERSION):null,this.b=new Yo(this.m,Xa(Qa),e),this.h=new Lu(this.b),Hu(this,t[zo]),Mu(this.h,t),Cr(this,"refreshToken",this.h.a),Xu(this,n||{}),Dt.call(this),this.I=!1,this.u&&sr()&&(this.a=wu(this.u,this.m,this.o)),this.N=[],this.i=null,this.w=function(e){return new ku(function(){return e.F(!0)},function(e){return!(!e||"auth/network-request-failed"!=e.code)},function(){var t=e.h.c-v()-3e5;return 0<t?t:0})}(this),this.V=y(this.Ha,this);var r=this;this.ka=null,this.sa=function(e){r.oa(e.g)},this.X=null,this.O=[],this.ra=function(e){ju(r,e.c)},this.W=null}function qu(e,t){e.X&&bt(e.X,"languageCodeChanged",e.sa),(e.X=t)&>(t,"languageCodeChanged",e.sa)}function ju(e,t){e.O=t,ra(e.b,firebase.SDK_VERSION?rr(firebase.SDK_VERSION,e.O):null)}function Wu(e,t){e.W&&bt(e.W,"frameworkChanged",e.ra),(e.W=t)&>(t,"frameworkChanged",e.ra)}function Ku(e){try{return firebase.app(e.o).auth()}catch(t){throw new xr("internal-error","No firebase.auth.Auth instance is available for the Firebase App '"+e.o+"'!")}}function Gu(e){e.C||e.w.b||(e.w.start(),bt(e,"tokenChanged",e.V),gt(e,"tokenChanged",e.V))}function $u(e){bt(e,"tokenChanged",e.V),e.w.stop()}function Hu(e,t){e.qa=t,Cr(e,"_lat",t)}function Qu(e){for(var t=[],n=0;n<e.N.length;n++)t.push(e.N[n](e));return we(t).then(function(){return e})}function Yu(e){e.a&&!e.I&&(e.I=!0,e.a.subscribe(e))}function Xu(e,t){Ir(e,{uid:t.uid,displayName:t.displayName||null,photoURL:t.photoURL||null,email:t.email||null,emailVerified:t.emailVerified||!1,phoneNumber:t.phoneNumber||null,isAnonymous:t.isAnonymous||!1,metadata:new Uu(t.createdAt,t.lastLoginAt),providerData:[]})}function zu(){}function Ju(e){return Ee().then(function(){if(e.C)throw new xr("app-deleted")})}function Zu(e){return k(e.providerData,function(e){return e.providerId})}function ec(e,t){t&&(tc(e,t.providerId),e.providerData.push(t))}function tc(e,t){x(e.providerData,function(e){return e.providerId==t})}function nc(e,t,n){("uid"!=t||n)&&e.hasOwnProperty(t)&&Cr(e,t,n)}function rc(e,t){e!=t&&(Ir(e,{uid:t.uid,displayName:t.displayName,photoURL:t.photoURL,email:t.email,emailVerified:t.emailVerified,phoneNumber:t.phoneNumber,isAnonymous:t.isAnonymous,providerData:[]}),t.metadata?Cr(e,"metadata",function(e){return new Uu(e.a,e.b)}(t.metadata)):Cr(e,"metadata",new Uu),P(t.providerData,function(t){ec(e,t)}),function(e,t){e.b=t.b,e.a=t.a,e.c=t.c}(e.h,t.h),Cr(e,"refreshToken",e.h.a))}function ic(e){return e.F().then(function(t){var n=e.isAnonymous;return function(e,t){return Ga(e.b,Ia,{idToken:t}).then(y(e.wc,e))}(e,t).then(function(){return n||nc(e,"isAnonymous",!1),t})})}function oc(e,t){t[zo]&&e.qa!=t[zo]&&(Mu(e.h,t),e.dispatchEvent(new Bu("tokenChanged")),Hu(e,t[zo]),nc(e,"refreshToken",e.h.a))}function ac(e,t){return ic(e).then(function(){if(M(Zu(e),t))return Qu(e).then(function(){throw new xr("provider-already-linked")})})}function sc(e,t,n){return Nr({user:e,credential:Ui(t),additionalUserInfo:t=si(t),operationType:n})}function uc(e,t){return oc(e,t),e.reload().then(function(){return e})}function cc(e,t,n,r,i){if(!sr())return Se(new xr("operation-not-supported-in-this-environment"));if(e.i&&!i)return Se(e.i);var o=ai(n.providerId),a=pr(e.uid+":::"),s=null;(!hr()||Yn())&&e.u&&n.isOAuthProvider&&(s=cs(e.u,e.m,e.o,t,n,null,a,firebase.SDK_VERSION||null));var u=Gn(s,o&&o.Ba,o&&o.Aa);return r=r().then(function(){if(lc(e),!i)return e.F().then(function(){})}).then(function(){return Eu(e.a,u,t,n,a,!!s)}).then(function(){return new pe(function(n,r){e.ha(t,null,new xr("cancelled-popup-request"),e.g||null),e.f=n,e.v=r,e.g=a,e.c=e.a.Ea(e,t,u,a)})}).then(function(e){return u&&Kn(u),e?Nr(e):null}).s(function(e){throw u&&Kn(u),e}),dc(e,r,i)}function hc(e,t,n,r,i){if(!sr())return Se(new xr("operation-not-supported-in-this-environment"));if(e.i&&!i)return Se(e.i);var o=null,a=pr(e.uid+":::");return r=r().then(function(){if(lc(e),!i)return e.F().then(function(){})}).then(function(){return e.aa=a,Qu(e)}).then(function(t){return e.ba&&(t=(t=e.ba).b.set(pc,e.D(),t.a)),t}).then(function(){return e.a.Ca(t,n,a)}).s(function(t){if(o=t,e.ba)return mc(e.ba);throw o}).then(function(){if(o)throw o}),dc(e,r,i)}function lc(e){if(!e.a||!e.I){if(e.a&&!e.I)throw new xr("internal-error");throw new xr("auth-domain-config-required")}}function dc(e,t,n){var r=function(e,t,n){return e.i&&!n?(t.cancel(),Se(e.i)):t.s(function(t){throw!t||"auth/user-disabled"!=t.code&&"auth/user-token-expired"!=t.code||(e.i||e.dispatchEvent(new Bu("userInvalidated")),e.i=t),t})}(e,t,n);return e.G.push(r),r.ia(function(){F(e.G,r)}),r}function fc(e){if(!e.apiKey)return null;var t={apiKey:e.apiKey,authDomain:e.authDomain,appName:e.appName},n={};if(!(e.stsTokenManager&&e.stsTokenManager.accessToken&&e.stsTokenManager.expirationTime))return null;n[zo]=e.stsTokenManager.accessToken,n.refreshToken=e.stsTokenManager.refreshToken||null,n.expiresIn=(e.stsTokenManager.expirationTime-v())/1e3;var r=new Vu(t,n,e);return e.providerData&&P(e.providerData,function(e){e&&ec(r,Nr(e))}),e.redirectEventId&&(r.aa=e.redirectEventId),r}Cu.prototype.reset=function(){this.b=null,this.a&&(this.a.cancel(),this.a=null)},Cu.prototype.h=function(e,t){if(e){this.reset(),this.g=!0;var n=e.b,r=e.c,i=e.a&&"auth/web-storage-unsupported"==e.a.code,o=e.a&&"auth/operation-not-supported-in-this-environment"==e.a.code;this.i=!(!i&&!o),"unknown"!=n||i||o?e.a?(Ru(this,!0,null,e.a),Ee()):t.wa(n,r)?function(e,t,n){n=n.wa(t.b,t.c);var r=t.f,i=t.g,o=!!t.b.match(/Redirect$/);n(r,i).then(function(t){Ru(e,o,t,null)}).s(function(t){Ru(e,o,null,t)})}(this,e,t):Se(new xr("invalid-auth-event")):(Ru(this,!1,null,null),Ee())}else Se(new xr("invalid-auth-event"))},Cu.prototype.Xa=function(){this.g&&!this.i&&Ru(this,!1,null,null)},Cu.prototype.fa=function(){var e=this;return new pe(function(t,n){e.b?e.b().then(t,n):(e.f.push(t),e.c.push(n),function(e){var t=new xr("timeout");e.a&&e.a.cancel(),e.a=Lt(bu.get()).then(function(){e.b||(e.g=!0,Ru(e,!0,null,t))})}(e))})},Du.prototype.h=function(e,t){if(e){var n=e.b,r=e.c;e.a?(t.ha(e.b,null,e.a,e.c),Ee()):t.wa(n,r)?function(e,t){var n=e.c,r=e.b;t.wa(r,n)(e.f,e.g).then(function(e){t.ha(r,e,null,n)}).s(function(e){t.ha(r,null,e,n)})}(e,t):Se(new xr("invalid-auth-event"))}else Se(new xr("invalid-auth-event"))},Ou.prototype.confirm=function(e){return e=xi(this.verificationId,e),this.a(e)},ku.prototype.start=function(){this.a=this.c,function e(t,r){t.stop();t.b=Lt(function(e,t){return t?(e.a=e.c,e.g()):(t=e.a,e.a*=2,e.a>e.f&&(e.a=e.f),t)}(t,r)).then(function(){return e=n.document,t=null,vr()||!e?Ee():new pe(function(n){t=function(){vr()&&(e.removeEventListener("visibilitychange",t,!1),n())},e.addEventListener("visibilitychange",t,!1)}).s(function(n){throw e.removeEventListener("visibilitychange",t,!1),n});var e,t}).then(function(){return t.h()}).then(function(){e(t,!0)}).s(function(n){t.i(n)&&e(t,!1)})}(this,!0)},ku.prototype.stop=function(){this.b&&(this.b.cancel(),this.b=null)},Lu.prototype.D=function(){return{apiKey:this.f.b,refreshToken:this.a,accessToken:this.b,expirationTime:this.c}},Lu.prototype.getToken=function(e){return e=!!e,this.b&&!this.a?Se(new xr("user-token-expired")):e||!this.b||v()>this.c-3e4?this.a?xu(this,{grant_type:"refresh_token",refresh_token:this.a}):Ee(null):Ee({accessToken:this.b,expirationTime:this.c,refreshToken:this.a})},Uu.prototype.D=function(){return{lastLoginAt:this.b,createdAt:this.a}},_(Bu,at),_(Vu,Dt),Vu.prototype.oa=function(e){this.ka=e,na(this.b,e)},Vu.prototype.ea=function(){return this.ka},Vu.prototype.xa=function(){return B(this.O)},Vu.prototype.Ha=function(){this.w.b&&(this.w.stop(),this.w.start())},Cr(Vu.prototype,"providerId","firebase"),(e=Vu.prototype).reload=function(){var e=this;return dc(this,Ju(this).then(function(){return ic(e).then(function(){return Qu(e)}).then(zu)}))},e.cc=function(e){return this.F(e).then(function(e){return new function(e){var t=ni(e);if(!(t&&t.exp&&t.auth_time&&t.iat))throw new xr("internal-error","An internal error occurred. The token obtained by Firebase appears to be malformed. Please retry the operation.");Ir(this,{token:e,expirationTime:_r(1e3*t.exp),authTime:_r(1e3*t.auth_time),issuedAtTime:_r(1e3*t.iat),signInProvider:t.firebase&&t.firebase.sign_in_provider?t.firebase.sign_in_provider:null,claims:t})}(e)})},e.F=function(e){var t=this;return dc(this,Ju(this).then(function(){return t.h.getToken(e)}).then(function(e){if(!e)throw new xr("internal-error");return e.accessToken!=t.qa&&(Hu(t,e.accessToken),t.dispatchEvent(new Bu("tokenChanged"))),nc(t,"refreshToken",e.refreshToken),e.accessToken}))},e.wc=function(e){if(!(e=e.users)||!e.length)throw new xr("internal-error");Xu(this,{uid:(e=e[0]).localId,displayName:e.displayName,photoURL:e.photoUrl,email:e.email,emailVerified:!!e.emailVerified,phoneNumber:e.phoneNumber,lastLoginAt:e.lastLoginAt,createdAt:e.createdAt});for(var t=function(e){return(e=e.providerUserInfo)&&e.length?k(e,function(e){return new function(e,t,n,r,i,o){Ir(this,{uid:e,displayName:r||null,photoURL:i||null,email:n||null,phoneNumber:o||null,providerId:t})}(e.rawId,e.providerId,e.email,e.displayName,e.photoUrl,e.phoneNumber)}):[]}(e),n=0;n<t.length;n++)ec(this,t[n]);nc(this,"isAnonymous",!(this.email&&e.passwordHash||this.providerData&&this.providerData.length))},e.fb=function(e){var t=this,n=null;return dc(this,e.f(this.b,this.uid).then(function(e){return oc(t,e),n=sc(t,e,"reauthenticate"),t.i=null,t.reload()}).then(function(){return n}),!0)},e.xc=function(e){return Tr("firebase.User.prototype.reauthenticateWithCredential is deprecated. Please use firebase.User.prototype.reauthenticateAndRetrieveDataWithCredential instead."),this.fb(e).then(function(){})},e.cb=function(e){var t=this,n=null;return dc(this,ac(this,e.providerId).then(function(){return t.F()}).then(function(n){return e.c(t.b,n)}).then(function(e){return n=sc(t,e,"link"),uc(t,e)}).then(function(){return n}))},e.oc=function(e){return Tr("firebase.User.prototype.linkWithCredential is deprecated. Please use firebase.User.prototype.linkAndRetrieveDataWithCredential instead."),this.cb(e).then(function(e){return e.user})},e.pc=function(e,t){var n=this;return dc(this,ac(this,"phone").then(function(){return Pu(Ku(n),e,t,y(n.cb,n))}))},e.yc=function(e,t){var n=this;return dc(this,Ee().then(function(){return Pu(Ku(n),e,t,y(n.fb,n))}),!0)},e.ob=function(e){var t=this;return dc(this,this.F().then(function(n){return t.b.ob(n,e)}).then(function(e){return oc(t,e),t.reload()}))},e.Qc=function(e){var t=this;return dc(this,this.F().then(function(n){return e.c(t.b,n)}).then(function(e){return oc(t,e),t.reload()}))},e.pb=function(e){var t=this;return dc(this,this.F().then(function(n){return t.b.pb(n,e)}).then(function(e){return oc(t,e),t.reload()}))},e.qb=function(e){if(void 0===e.displayName&&void 0===e.photoURL)return Ju(this);var t=this;return dc(this,this.F().then(function(n){return t.b.qb(n,{displayName:e.displayName,photoUrl:e.photoURL})}).then(function(e){return oc(t,e),nc(t,"displayName",e.displayName||null),nc(t,"photoURL",e.photoUrl||null),P(t.providerData,function(e){"password"===e.providerId&&(Cr(e,"displayName",t.displayName),Cr(e,"photoURL",t.photoURL))}),Qu(t)}).then(zu))},e.Oc=function(e){var t=this;return dc(this,ic(this).then(function(n){return M(Zu(t),e)?function(e,t,n){return Ga(e,Ta,{idToken:t,deleteProvider:n})}(t.b,n,[e]).then(function(e){var n={};return P(e.providerUserInfo||[],function(e){n[e.providerId]=!0}),P(Zu(t),function(e){n[e]||tc(t,e)}),n[Fi.PROVIDER_ID]||Cr(t,"phoneNumber",null),Qu(t)}):Qu(t).then(function(){throw new xr("no-such-provider")})}))},e.delete=function(){var e=this;return dc(this,this.F().then(function(t){return Ga(e.b,Sa,{idToken:t})}).then(function(){e.dispatchEvent(new Bu("userDeleted"))})).then(function(){for(var t=0;t<e.G.length;t++)e.G[t].cancel("app-deleted");qu(e,null),Wu(e,null),e.G=[],e.C=!0,$u(e),Cr(e,"refreshToken",null),e.a&&e.a.unsubscribe(e)})},e.ub=function(e,t){return!!("linkViaPopup"==e&&(this.g||null)==t&&this.f||"reauthViaPopup"==e&&(this.g||null)==t&&this.f||"linkViaRedirect"==e&&(this.aa||null)==t||"reauthViaRedirect"==e&&(this.aa||null)==t)},e.ha=function(e,t,n,r){"linkViaPopup"!=e&&"reauthViaPopup"!=e||r!=(this.g||null)||(n&&this.v?this.v(n):t&&!n&&this.f&&this.f(t),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.v)},e.wa=function(e,t){return"linkViaPopup"==e&&t==(this.g||null)?y(this.zb,this):"reauthViaPopup"==e&&t==(this.g||null)?y(this.Ab,this):"linkViaRedirect"==e&&(this.aa||null)==t?y(this.zb,this):"reauthViaRedirect"==e&&(this.aa||null)==t?y(this.Ab,this):null},e.qc=function(e){var t=this;return cc(this,"linkViaPopup",e,function(){return ac(t,e.providerId).then(function(){return Qu(t)})},!1)},e.zc=function(e){return cc(this,"reauthViaPopup",e,function(){return Ee()},!0)},e.rc=function(e){var t=this;return hc(this,"linkViaRedirect",e,function(){return ac(t,e.providerId)},!1)},e.Ac=function(e){return hc(this,"reauthViaRedirect",e,function(){return Ee()},!0)},e.zb=function(e,t){var n=this;this.c&&(this.c.cancel(),this.c=null);var r=null;return dc(this,this.F().then(function(r){return ma(n.b,{requestUri:e,sessionId:t,idToken:r})}).then(function(e){return r=sc(n,e,"link"),uc(n,e)}).then(function(){return r}))},e.Ab=function(e,t){var n=this;this.c&&(this.c.cancel(),this.c=null);var r=null;return dc(this,Ee().then(function(){return gi(ya(n.b,{requestUri:e,sessionId:t}),n.uid)}).then(function(e){return r=sc(n,e,"reauthenticate"),oc(n,e),n.i=null,n.reload()}).then(function(){return r}),!0)},e.ib=function(e){var t=this,n=null;return dc(this,this.F().then(function(t){return n=t,void 0===e||re(e)?{}:Xr(new qr(e))}).then(function(e){return t.b.ib(n,e)}).then(function(e){if(t.email!=e)return t.reload()}).then(function(){}))},e.toJSON=function(){return this.D()},e.D=function(){var e={uid:this.uid,displayName:this.displayName,photoURL:this.photoURL,email:this.email,emailVerified:this.emailVerified,phoneNumber:this.phoneNumber,isAnonymous:this.isAnonymous,providerData:[],apiKey:this.m,appName:this.o,authDomain:this.u,stsTokenManager:this.h.D(),redirectEventId:this.aa||null};return this.metadata&&ue(e,this.metadata.D()),P(this.providerData,function(t){e.providerData.push(function(e){var t,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}(t))}),e};var pc={name:"redirectUser",A:"session"};function mc(e){return $s(e.b,pc,e.a)}function yc(e){this.a=e,this.b=Ws(),this.c=null,this.f=function(e){var t=_c("local"),r=_c("session"),i=_c("none");return function(e,t,r){var i=Gs(t,r),o=Ks(e,t.A);return e.get(t,r).then(function(a){var s=null;try{s=fr(n.localStorage.getItem(i))}catch(e){}if(s&&!a)return n.localStorage.removeItem(i),e.set(t,s,r);s&&a&&"localStorage"!=o.type&&n.localStorage.removeItem(i)})}(e.b,t,e.a).then(function(){return e.b.get(r,e.a)}).then(function(n){return n?r:e.b.get(i,e.a).then(function(n){return n?i:e.b.get(t,e.a).then(function(n){return n?t:e.b.get(vc,e.a).then(function(e){return e?_c(e):t})})})}).then(function(t){return e.c=t,gc(e,t.A)}).s(function(){e.c||(e.c=t)})}(this),this.b.addListener(_c("local"),this.a,y(this.g,this))}function gc(e,t){var n,r=[];for(n in qs)qs[n]!==t&&r.push($s(e.b,_c(qs[n]),e.a));return r.push($s(e.b,vc,e.a)),function(e){return new pe(function(t,n){var r=e.length,i=[];if(r)for(var o=function(e,n){r--,i[e]=n,0==r&&t(i)},a=function(e){n(e)},s=0;s<e.length;s++)Te(e[s],g(o,s),a);else t(i)})}(r)}yc.prototype.g=function(){var e=this,t=_c("local");Tc(this,function(){return Ee().then(function(){return e.c&&"local"!=e.c.A?e.b.get(t,e.a):null}).then(function(n){if(n)return gc(e,"local").then(function(){e.c=t})})})};var vc={name:"persistence",A:"session"};function _c(e){return{name:"authUser",A:e}}function bc(e,t){return Tc(e,function(){return e.b.set(e.c,t.D(),e.a)})}function Ec(e){return Tc(e,function(){return $s(e.b,e.c,e.a)})}function Sc(e,t){return Tc(e,function(){return e.b.get(e.c,e.a).then(function(e){return e&&t&&(e.authDomain=t),fc(e||{})})})}function Tc(e,t){return e.f=e.f.then(t,t),e.f}function wc(e){if(this.m=!1,Cr(this,"settings",new Au),Cr(this,"app",e),!Oc(this).options||!Oc(this).options.apiKey)throw new xr("invalid-api-key");e=firebase.SDK_VERSION?rr(firebase.SDK_VERSION):null,this.b=new Yo(Oc(this).options&&Oc(this).options.apiKey,Xa(Qa),e),this.N=[],this.o=[],this.I=[],this.Sb=firebase.INTERNAL.createSubscribe(y(this.kc,this)),this.O=void 0,this.Tb=firebase.INTERNAL.createSubscribe(y(this.mc,this)),Dc(this,null),this.h=new yc(Oc(this).options.apiKey+":"+Oc(this).name),this.w=new function(e){this.a=e,this.b=Ws()}(Oc(this).options.apiKey+":"+Oc(this).name),this.V=Mc(this,function(e){var t=Oc(e).options.authDomain,n=function(e){var t=function(e,t){return e.b.get(pc,e.a).then(function(e){return e&&t&&(e.authDomain=t),fc(e||{})})}(e.w,Oc(e).options.authDomain).then(function(t){return(e.C=t)&&(t.ba=e.w),mc(e.w)});return Mc(e,t)}(e).then(function(){return Sc(e.h,t)}).then(function(t){return t?(t.ba=e.w,e.C&&(e.C.aa||null)==(t.aa||null)?t:t.reload().then(function(){return bc(e.h,t).then(function(){return t})}).s(function(n){return"auth/network-request-failed"==n.code?t:Ec(e.h)})):null}).then(function(t){Dc(e,t||null)});return Mc(e,n)}(this)),this.i=Mc(this,function(e){return e.V.then(function(){return e.fa()}).s(function(){}).then(function(){if(!e.m)return e.ka()}).s(function(){}).then(function(){if(!e.m){e.X=!0;var t=e.h;t.b.addListener(_c("local"),t.a,e.ka)}})}(this)),this.X=!1,this.ka=y(this.Lc,this),this.Ha=y(this.Z,this),this.qa=y(this.ac,this),this.ra=y(this.ic,this),this.sa=y(this.jc,this),function(e){var t=Oc(e).options.authDomain,n=Oc(e).options.apiKey;t&&sr()&&(e.Rb=e.V.then(function(){if(!e.m){if(e.a=wu(t,n,Oc(e).name),e.a.subscribe(e),Pc(e)&&Yu(Pc(e)),e.C){Yu(e.C);var r=e.C;r.oa(e.ea()),qu(r,e),ju(r=e.C,e.G),Wu(r,e),e.C=null}return e.a}}))}(this),this.INTERNAL={},this.INTERNAL.delete=y(this.delete,this),this.INTERNAL.logFramework=y(this.sc,this),this.u=0,Dt.call(this),function(e){Object.defineProperty(e,"lc",{get:function(){return this.ea()},set:function(e){this.oa(e)},enumerable:!1}),e.W=null}(this),this.G=[]}function Cc(e){at.call(this,"languageCodeChanged"),this.g=e}function Ic(e){at.call(this,"frameworkChanged"),this.c=e}function Nc(e){return e.Rb||Se(new xr("auth-domain-config-required"))}function Rc(e,t){var n={};return n.apiKey=Oc(e).options.apiKey,n.authDomain=Oc(e).options.authDomain,n.appName=Oc(e).name,e.V.then(function(){return function(e,t,n,r){var i=new Vu(e,t);return n&&(i.ba=n),r&&ju(i,r),i.reload().then(function(){return i})}(n,t,e.w,e.xa())}).then(function(t){return Pc(e)&&t.uid==Pc(e).uid?(rc(Pc(e),t),e.Z(t)):(Dc(e,t),Yu(t),e.Z(t))}).then(function(){Lc(e)})}function Dc(e,t){Pc(e)&&(function(e,t){x(e.N,function(e){return e==t})}(Pc(e),e.Ha),bt(Pc(e),"tokenChanged",e.qa),bt(Pc(e),"userDeleted",e.ra),bt(Pc(e),"userInvalidated",e.sa),$u(Pc(e))),t&&(t.N.push(e.Ha),gt(t,"tokenChanged",e.qa),gt(t,"userDeleted",e.ra),gt(t,"userInvalidated",e.sa),0<e.u&&Gu(t)),Cr(e,"currentUser",t),t&&(t.oa(e.ea()),qu(t,e),ju(t,e.G),Wu(t,e))}function Ac(e,t){var n=null,r=null;return Mc(e,t.then(function(t){return n=Ui(t),r=si(t),Rc(e,t)}).then(function(){return Nr({user:Pc(e),credential:n,additionalUserInfo:r,operationType:"signIn"})}))}function Oc(e){return e.app}function Pc(e){return e.currentUser}function kc(e){return Pc(e)&&Pc(e)._lat||null}function Lc(e){if(e.X){for(var t=0;t<e.o.length;t++)e.o[t]&&e.o[t](kc(e));if(e.O!==e.getUid()&&e.I.length)for(e.O=e.getUid(),t=0;t<e.I.length;t++)e.I[t]&&e.I[t](kc(e))}}function Mc(e,t){return e.N.push(t),t.ia(function(){F(e.N,t)}),t}function Fc(){}function xc(){this.a={},this.b=1e12}yc.prototype.lb=function(e){var t=null,n=this;return function(e){var t=new xr("invalid-persistence-type"),n=new xr("unsupported-persistence-type");e:{for(r in qs)if(qs[r]==e){var r=!0;break e}r=!1}if(!r||"string"!=typeof e)throw t;switch(zn()){case"ReactNative":if("session"===e)throw n;break;case"Node":if("none"!==e)throw n;break;default:if(!ar()&&"none"!==e)throw n}}(e),Tc(this,function(){return e!=n.c.A?n.b.get(n.c,n.a).then(function(r){return t=r,gc(n,e)}).then(function(){if(n.c=_c(e),t)return n.b.set(n.c,t,n.a)}):Ee()})},_(wc,Dt),_(Cc,at),_(Ic,at),(e=wc.prototype).lb=function(e){return Mc(this,e=this.h.lb(e))},e.oa=function(e){this.W===e||this.m||(this.W=e,na(this.b,this.W),this.dispatchEvent(new Cc(this.ea())))},e.ea=function(){return this.W},e.Rc=function(){var e=n.navigator;this.oa(e&&(e.languages&&e.languages[0]||e.language||e.userLanguage)||null)},e.sc=function(e){this.G.push(e),ra(this.b,firebase.SDK_VERSION?rr(firebase.SDK_VERSION,this.G):null),this.dispatchEvent(new Ic(this.G))},e.xa=function(){return B(this.G)},e.toJSON=function(){return{apiKey:Oc(this).options.apiKey,authDomain:Oc(this).options.authDomain,appName:Oc(this).name,currentUser:Pc(this)&&Pc(this).D()}},e.ub=function(e,t){switch(e){case"unknown":case"signInViaRedirect":return!0;case"signInViaPopup":return this.g==t&&!!this.f;default:return!1}},e.ha=function(e,t,n,r){"signInViaPopup"==e&&this.g==r&&(n&&this.v?this.v(n):t&&!n&&this.f&&this.f(t),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.v)},e.wa=function(e,t){return"signInViaRedirect"==e||"signInViaPopup"==e&&this.g==t&&this.f?y(this.$b,this):null},e.$b=function(e,t){var n=this;e={requestUri:e,sessionId:t},this.c&&(this.c.cancel(),this.c=null);var r=null,i=null,o=pa(n.b,e).then(function(e){return r=Ui(e),i=si(e),e});return Mc(this,e=n.V.then(function(){return o}).then(function(e){return Rc(n,e)}).then(function(){return Nr({user:Pc(n),credential:r,additionalUserInfo:i,operationType:"signIn"})}))},e.Jc=function(e){if(!sr())return Se(new xr("operation-not-supported-in-this-environment"));var t=this,n=ai(e.providerId),r=pr(),i=null;(!hr()||Yn())&&Oc(this).options.authDomain&&e.isOAuthProvider&&(i=cs(Oc(this).options.authDomain,Oc(this).options.apiKey,Oc(this).name,"signInViaPopup",e,null,r,firebase.SDK_VERSION||null));var o=Gn(i,n&&n.Ba,n&&n.Aa);return Mc(this,n=Nc(this).then(function(t){return Eu(t,o,"signInViaPopup",e,r,!!i)}).then(function(){return new pe(function(e,n){t.ha("signInViaPopup",null,new xr("cancelled-popup-request"),t.g),t.f=e,t.v=n,t.g=r,t.c=t.a.Ea(t,"signInViaPopup",o,r)})}).then(function(e){return o&&Kn(o),e?Nr(e):null}).s(function(e){throw o&&Kn(o),e}))},e.Kc=function(e){if(!sr())return Se(new xr("operation-not-supported-in-this-environment"));var t=this;return Mc(this,Nc(this).then(function(){return Tc(e=t.h,function(){return e.b.set(vc,e.c.A,e.a)});var e}).then(function(){return t.a.Ca("signInViaRedirect",e)}))},e.fa=function(){if(!sr())return Se(new xr("operation-not-supported-in-this-environment"));var e=this;return Mc(this,Nc(this).then(function(){return e.a.fa()}).then(function(e){return e?Nr(e):null}))},e.Pc=function(e){if(!e)return Se(new xr("null-user"));var t=this,n={};n.apiKey=Oc(this).options.apiKey,n.authDomain=Oc(this).options.authDomain,n.appName=Oc(this).name;var r=function(e,t,n,r){t=t||{apiKey:e.m,authDomain:e.u,appName:e.o};var i=e.h,o={};return o[zo]=i.b,o.refreshToken=i.a,o.expiresIn=(i.c-v())/1e3,t=new Vu(t,o),n&&(t.ba=n),r&&ju(t,r),rc(t,e),t}(e,n,t.w,t.xa());return Mc(this,this.i.then(function(){if(Oc(t).options.apiKey!=e.m)return r.reload()}).then(function(){return Pc(t)&&e.uid==Pc(t).uid?(rc(Pc(t),e),t.Z(e)):(Dc(t,r),Yu(r),t.Z(r))}).then(function(){Lc(t)}))},e.mb=function(){var e=this;return Mc(this,this.i.then(function(){return Pc(e)?(Dc(e,null),Ec(e.h).then(function(){Lc(e)})):Ee()}))},e.Lc=function(){var e=this;return Sc(this.h,Oc(this).options.authDomain).then(function(t){if(!e.m){var n;if(n=Pc(e)&&t){n=Pc(e).uid;var r=t.uid;n=void 0!==n&&null!==n&&""!==n&&void 0!==r&&null!==r&&""!==r&&n==r}if(n)return rc(Pc(e),t),Pc(e).F();(Pc(e)||t)&&(Dc(e,t),t&&(Yu(t),t.ba=e.w),e.a&&e.a.subscribe(e),Lc(e))}})},e.Z=function(e){return bc(this.h,e)},e.ac=function(){Lc(this),this.Z(Pc(this))},e.ic=function(){this.mb()},e.jc=function(){this.mb()},e.kc=function(e){var t=this;this.addAuthTokenListener(function(){e.next(Pc(t))})},e.mc=function(e){var t=this;!function(e,t){e.I.push(t),Mc(e,e.i.then(function(){!e.m&&M(e.I,t)&&e.O!==e.getUid()&&(e.O=e.getUid(),t(kc(e)))}))}(this,function(){e.next(Pc(t))})},e.uc=function(e,t,n){var r=this;return this.X&&firebase.Promise.resolve().then(function(){h(e)?e(Pc(r)):h(e.next)&&e.next(Pc(r))}),this.Sb(e,t,n)},e.tc=function(e,t,n){var r=this;return this.X&&firebase.Promise.resolve().then(function(){r.O=r.getUid(),h(e)?e(Pc(r)):h(e.next)&&e.next(Pc(r))}),this.Tb(e,t,n)},e.bc=function(e){var t=this;return Mc(this,this.i.then(function(){return Pc(t)?Pc(t).F(e).then(function(e){return{accessToken:e}}):null}))},e.Mb=function(e){var t=this;return this.i.then(function(){return Ac(t,Ga(t.b,Va,{token:e}))}).then(function(e){var n=e.user;return nc(n,"isAnonymous",!1),t.Z(n),e})},e.Dc=function(e){return Tr("firebase.auth.Auth.prototype.signInAndRetrieveDataWithCustomToken is deprecated. Please use firebase.auth.Auth.prototype.signInWithCustomToken instead."),this.Mb(e)},e.Ec=function(e,t){return Tr("firebase.auth.Auth.prototype.signInAndRetrieveDataWithEmailAndPassword is deprecated. Please use firebase.auth.Auth.prototype.signInWithEmailAndPassword instead."),this.Nb(e,t)},e.Nb=function(e,t){var n=this;return this.i.then(function(){return Ac(n,Ga(n.b,qa,{email:e,password:t}))})},e.wb=function(e,t){var n=this;return this.i.then(function(){return Ac(n,Ga(n.b,ba,{email:e,password:t}))})},e.Vb=function(e,t){return Tr("firebase.auth.Auth.prototype.createUserAndRetrieveDataWithEmailAndPassword is deprecated. Please use firebase.auth.Auth.prototype.createUserWithEmailAndPassword instead."),this.wb(e,t)},e.Gc=function(e){return Tr("firebase.auth.Auth.prototype.signInWithCredential is deprecated. Please use firebase.auth.Auth.prototype.signInAndRetrieveDataWithCredential instead."),this.Oa(e).then(function(e){return e.user})},e.Oa=function(e){var t=this;return this.i.then(function(){return Ac(t,e.ya(t.b))})},e.Pa=function(){var e=this;return this.i.then(function(){var t=Pc(e);return t&&t.isAnonymous?Nr({user:t,credential:null,additionalUserInfo:Nr({providerId:null,isNewUser:!1}),operationType:"signIn"}):Ac(e,e.b.Pa()).then(function(t){var n=t.user;return nc(n,"isAnonymous",!0),e.Z(n),t})})},e.Fc=function(){return Tr("firebase.auth.Auth.prototype.signInAnonymouslyAndRetrieveData is deprecated. Please use firebase.auth.Auth.prototype.signInAnonymously instead."),this.Pa()},e.getUid=function(){return Pc(this)&&Pc(this).uid||null},e.Ub=function(e){this.addAuthTokenListener(e),this.u++,0<this.u&&Pc(this)&&Gu(Pc(this))},e.Bc=function(e){var t=this;P(this.o,function(n){n==e&&t.u--}),0>this.u&&(this.u=0),0==this.u&&Pc(this)&&$u(Pc(this)),this.removeAuthTokenListener(e)},e.addAuthTokenListener=function(e){var t=this;this.o.push(e),Mc(this,this.i.then(function(){t.m||M(t.o,e)&&e(kc(t))}))},e.removeAuthTokenListener=function(e){x(this.o,function(t){return t==e})},e.delete=function(){this.m=!0;for(var e=0;e<this.N.length;e++)this.N[e].cancel("app-deleted");return this.N=[],this.h&&(e=this.h).b.removeListener(_c("local"),e.a,this.ka),this.a&&(this.a.unsubscribe(this),this.a.Xa()),firebase.Promise.resolve()},e.Yb=function(e){return Tr("firebase.auth.Auth.prototype.fetchProvidersForEmail is deprecated. Please use firebase.auth.Auth.prototype.fetchSignInMethodsForEmail instead."),Mc(this,function(e,t){return Ga(e,Ea,{identifier:t,continueUri:ur()?qn():"http://localhost"}).then(function(e){return e.allProviders||[]})}(this.b,e))},e.Zb=function(e){return Mc(this,function(e,t){return Ga(e,Ea,{identifier:t,continueUri:ur()?qn():"http://localhost"}).then(function(e){return e.signinMethods||[]})}(this.b,e))},e.nc=function(e){return!!ki(e)},e.kb=function(e,t){var n=this;return Mc(this,Ee().then(function(){var e=new qr(t);if(!e.c)throw new xr("argument-error",Wr+" must be true when sending sign in link to email");return Xr(e)}).then(function(t){return n.b.kb(e,t)}).then(function(){}))},e.Sc=function(e){return this.Ja(e).then(function(e){return e.data.email})},e.Ya=function(e,t){return Mc(this,this.b.Ya(e,t).then(function(){}))},e.Ja=function(e){return Mc(this,this.b.Ja(e).then(function(e){return new function(e){var t={},n=e[Ar],r=e[Or];if(!(e=e[Pr])||e!=Dr&&!n)throw Error("Invalid provider user info!");t[Lr]=r||null,t[kr]=n||null,Cr(this,Fr,e),Cr(this,Mr,Rr(t))}(e)}))},e.Va=function(e){return Mc(this,this.b.Va(e).then(function(){}))},e.jb=function(e,t){var n=this;return Mc(this,Ee().then(function(){return void 0===t||re(t)?{}:Xr(new qr(t))}).then(function(t){return n.b.jb(e,t)}).then(function(){}))},e.Ic=function(e,t){return Mc(this,Pu(this,e,t,y(this.Oa,this)))},e.Hc=function(e,t){var n=this;return Mc(this,Ee().then(function(){var r=Pi(e,t||qn());return n.Oa(r)}))},Fc.prototype.render=function(){},Fc.prototype.reset=function(){},Fc.prototype.getResponse=function(){},Fc.prototype.execute=function(){};var Uc=null;function Bc(e,t){return(t=Vc(t))&&e.a[t]||null}function Vc(e){return(e=void 0===e?1e12:e)?e.toString():null}function qc(e,t){this.g=!1,this.c=t,this.a=this.b=null,this.h="invisible"!==this.c.size,this.f=On(e);var n=this;this.i=function(){n.execute()},this.h?this.execute():gt(this.f,"click",this.i)}function jc(e){if(e.g)throw Error("reCAPTCHA mock was already deleted!")}function Wc(){}xc.prototype.render=function(e,t){return this.a[this.b.toString()]=new qc(e,t),this.b++},xc.prototype.reset=function(e){var t=Bc(this,e);e=Vc(e),t&&e&&(t.delete(),delete this.a[e])},xc.prototype.getResponse=function(e){return(e=Bc(this,e))?e.getResponse():null},xc.prototype.execute=function(e){(e=Bc(this,e))&&e.execute()},qc.prototype.getResponse=function(){return jc(this),this.b},qc.prototype.execute=function(){jc(this);var e=this;this.a||(this.a=setTimeout(function(){e.b=function(){for(var e=50,t=[];0<e;)t.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.floor(62*Math.random()))),e--;return t.join("")}();var t=e.c.callback,n=e.c["expired-callback"];if(t)try{t(e.b)}catch(e){}e.a=setTimeout(function(){if(e.a=null,e.b=null,n)try{n()}catch(e){}e.h&&e.execute()},6e4)},500))},qc.prototype.delete=function(){jc(this),this.g=!0,clearTimeout(this.a),this.a=null,bt(this.f,"click",this.i)},Wc.prototype.g=function(){return Uc||(Uc=new xc),Ee(Uc)},Wc.prototype.c=function(){};var Kc=null;function Gc(){this.b=n.grecaptcha?1/0:0,this.f=null,this.a="__rcb"+Math.floor(1e6*Math.random()).toString()}var $c=mn("https://www.google.com/recaptcha/api.js?onload=%{onload}&render=explicit&hl=%{hl}"),Hc=new gr(3e4,6e4);Gc.prototype.g=function(e){var t=this;return new pe(function(r,i){var o=setTimeout(function(){i(new xr("network-request-failed"))},Hc.get());!n.grecaptcha||e!==t.f&&!t.b?(n[t.a]=function(){if(n.grecaptcha){t.f=e;var a=n.grecaptcha.render;n.grecaptcha.render=function(e,n){return e=a(e,n),t.b++,e},clearTimeout(o),r(n.grecaptcha)}else clearTimeout(o),i(new xr("internal-error"));delete n[t.a]},Ee(jo(vn($c,{onload:t.a,hl:e||""}))).s(function(){clearTimeout(o),i(new xr("internal-error","Unable to load external reCAPTCHA dependencies!"))})):(clearTimeout(o),r(n.grecaptcha))})},Gc.prototype.c=function(){this.b--};var Qc=null;function Yc(e,t,r,i,o,a,s){if(Cr(this,"type","recaptcha"),this.c=this.f=null,this.C=!1,this.m=t,this.g=null,s?(Kc||(Kc=new Wc),s=Kc):(Qc||(Qc=new Gc),s=Qc),this.o=s,this.a=r||{theme:"light",type:"image"},this.h=[],this.a[Jc])throw new xr("argument-error","sitekey should not be provided for reCAPTCHA as one is automatically provisioned for the current project.");if(this.i="invisible"===this.a[Zc],!n.document)throw new xr("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment with DOM support.");if(!On(t)||!this.i&&On(t).hasChildNodes())throw new xr("argument-error","reCAPTCHA container is either not found or already contains inner elements!");this.u=new Yo(e,a||null,o||null),this.v=i||function(){return null};var u=this;this.l=[];var c=this.a[Xc];this.a[Xc]=function(e){if(eh(u,e),"function"==typeof c)c(e);else if("string"==typeof c){var t=or(c,n);"function"==typeof t&&t(e)}};var h=this.a[zc];this.a[zc]=function(){if(eh(u,null),"function"==typeof h)h();else if("string"==typeof h){var e=or(h,n);"function"==typeof e&&e()}}}var Xc="callback",zc="expired-callback",Jc="sitekey",Zc="size";function eh(e,t){for(var n=0;n<e.l.length;n++)try{e.l[n](t)}catch(e){}}function th(e,t){return e.h.push(t),t.ia(function(){F(e.h,t)}),t}function nh(e){if(e.C)throw new xr("internal-error","RecaptchaVerifier instance has been destroyed.")}function rh(e,t,n){var r=!1;try{this.b=n||firebase.app()}catch(e){throw new xr("argument-error","No firebase.app.App instance is currently initialized.")}if(!this.b.options||!this.b.options.apiKey)throw new xr("invalid-api-key");n=this.b.options.apiKey;var i=this,o=null;try{o=this.b.auth().xa()}catch(e){}try{r=this.b.auth().settings.appVerificationDisabledForTesting}catch(e){}o=firebase.SDK_VERSION?rr(firebase.SDK_VERSION,o):null,Yc.call(this,n,e,t,function(){try{var e=i.b.auth().ea()}catch(t){e=null}return e},o,Xa(Qa),r)}function ih(e,t,n,r){e:{n=Array.prototype.slice.call(n);for(var i=0,o=!1,a=0;a<t.length;a++)if(t[a].optional)o=!0;else{if(o)throw new xr("internal-error","Argument validator encountered a required argument after an optional argument.");i++}if(o=t.length,n.length<i||o<n.length)r="Expected "+(i==o?1==i?"1 argument":i+" arguments":i+"-"+o+" arguments")+" but got "+n.length+".";else{for(i=0;i<n.length;i++)if(o=t[i].optional&&void 0===n[i],!t[i].M(n[i])&&!o){if(t=t[i],0>i||i>=oh.length)throw new xr("internal-error","Argument validator received an unsupported number of arguments.");n=oh[i],r=(r?"":n+" argument ")+(t.name?'"'+t.name+'" ':"")+"must be "+t.K+".";break e}r=null}}if(r)throw new xr("argument-error",e+" failed: "+r)}(e=Yc.prototype).za=function(){var e=this;return this.f?this.f:this.f=th(this,Ee().then(function(){if(ur()&&!Xn())return Hn();throw new xr("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment.")}).then(function(){return e.o.g(e.v())}).then(function(t){return e.g=t,Ga(e.u,Oa,{})}).then(function(t){e.a[Jc]=t.recaptchaSiteKey}).s(function(t){throw e.f=null,t}))},e.render=function(){nh(this);var e=this;return th(this,this.za().then(function(){if(null===e.c){var t=e.m;if(!e.i){var n=On(t);t=Ln("DIV"),n.appendChild(t)}e.c=e.g.render(t,e.a)}return e.c}))},e.verify=function(){nh(this);var e=this;return th(this,this.render().then(function(t){return new pe(function(n){var r=e.g.getResponse(t);if(r)n(r);else{var i=function(t){t&&(function(e,t){x(e.l,function(e){return e==t})}(e,i),n(t))};e.l.push(i),e.i&&e.g.execute(e.c)}})}))},e.reset=function(){nh(this),null!==this.c&&this.g.reset(this.c)},e.clear=function(){nh(this),this.C=!0,this.o.c();for(var e=0;e<this.h.length;e++)this.h[e].cancel("RecaptchaVerifier instance has been destroyed.");if(!this.i){e=On(this.m);for(var t;t=e.firstChild;)e.removeChild(t)}},_(rh,Yc);var oh="First Second Third Fourth Fifth Sixth Seventh Eighth Ninth".split(" ");function ah(e,t){return{name:e||"",K:"a valid string",optional:!!t,M:r}}function sh(e,t){return{name:e||"",K:"a boolean",optional:!!t,M:i}}function uh(e,t){return{name:e||"",K:"a valid object",optional:!!t,M:l}}function ch(e,t){return{name:e||"",K:"a function",optional:!!t,M:h}}function hh(e,t){return{name:e||"",K:"null",optional:!!t,M:s}}function lh(e){return{name:e?e+"Credential":"credential",K:e?"a valid "+e+" credential":"a valid credential",optional:!1,M:function(t){if(!t)return!1;var n=!e||t.providerId===e;return!(!t.ya||!n)}}}function dh(){return{name:"applicationVerifier",K:"an implementation of firebase.auth.ApplicationVerifier",optional:!1,M:function(e){return!!(e&&r(e.type)&&h(e.verify))}}}function fh(e,t,n,r){return{name:n||"",K:e.K+" or "+t.K,optional:!!r,M:function(n){return e.M(n)||t.M(n)}}}function ph(e,t){for(var n in t){var r=t[n].name;e[r]=gh(r,e[n],t[n].j)}}function mh(e,t){for(var n in t){var r=t[n].name;r!==n&&Object.defineProperty(e,r,{get:g(function(e){return this[e]},n),set:g(function(e,t,n,r){ih(e,[n],[r],!0),this[t]=r},r,n,t[n].sb),enumerable:!0})}}function yh(e,t,n,r){e[t]=gh(t,n,r)}function gh(e,t,n){function r(){var e=Array.prototype.slice.call(arguments);return ih(o,n,e),t.apply(this,e)}if(!n)return t;var i,o=function(e){return(e=e.split("."))[e.length-1]}(e);for(i in t)r[i]=t[i];for(i in t.prototype)r.prototype[i]=t.prototype[i];return r}ph(wc.prototype,{Va:{name:"applyActionCode",j:[ah("code")]},Ja:{name:"checkActionCode",j:[ah("code")]},Ya:{name:"confirmPasswordReset",j:[ah("code"),ah("newPassword")]},wb:{name:"createUserWithEmailAndPassword",j:[ah("email"),ah("password")]},Vb:{name:"createUserAndRetrieveDataWithEmailAndPassword",j:[ah("email"),ah("password")]},Yb:{name:"fetchProvidersForEmail",j:[ah("email")]},Zb:{name:"fetchSignInMethodsForEmail",j:[ah("email")]},fa:{name:"getRedirectResult",j:[]},nc:{name:"isSignInWithEmailLink",j:[ah("emailLink")]},tc:{name:"onAuthStateChanged",j:[fh(uh(),ch(),"nextOrObserver"),ch("opt_error",!0),ch("opt_completed",!0)]},uc:{name:"onIdTokenChanged",j:[fh(uh(),ch(),"nextOrObserver"),ch("opt_error",!0),ch("opt_completed",!0)]},jb:{name:"sendPasswordResetEmail",j:[ah("email"),fh(uh("opt_actionCodeSettings",!0),hh(null,!0),"opt_actionCodeSettings",!0)]},kb:{name:"sendSignInLinkToEmail",j:[ah("email"),uh("actionCodeSettings")]},lb:{name:"setPersistence",j:[ah("persistence")]},Oa:{name:"signInAndRetrieveDataWithCredential",j:[lh()]},Pa:{name:"signInAnonymously",j:[]},Fc:{name:"signInAnonymouslyAndRetrieveData",j:[]},Gc:{name:"signInWithCredential",j:[lh()]},Mb:{name:"signInWithCustomToken",j:[ah("token")]},Dc:{name:"signInAndRetrieveDataWithCustomToken",j:[ah("token")]},Nb:{name:"signInWithEmailAndPassword",j:[ah("email"),ah("password")]},Hc:{name:"signInWithEmailLink",j:[ah("email"),ah("emailLink",!0)]},Ec:{name:"signInAndRetrieveDataWithEmailAndPassword",j:[ah("email"),ah("password")]},Ic:{name:"signInWithPhoneNumber",j:[ah("phoneNumber"),dh()]},Jc:{name:"signInWithPopup",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(e){return!!(e&&e.providerId&&e.hasOwnProperty&&e.hasOwnProperty("isOAuthProvider"))}}]},Kc:{name:"signInWithRedirect",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(e){return!!(e&&e.providerId&&e.hasOwnProperty&&e.hasOwnProperty("isOAuthProvider"))}}]},Pc:{name:"updateCurrentUser",j:[fh({name:"user",K:"an instance of Firebase User",optional:!1,M:function(e){return!!(e&&e instanceof Vu)}},hh(),"user")]},mb:{name:"signOut",j:[]},toJSON:{name:"toJSON",j:[ah(null,!0)]},Rc:{name:"useDeviceLanguage",j:[]},Sc:{name:"verifyPasswordResetCode",j:[ah("code")]}}),mh(wc.prototype,{lc:{name:"languageCode",sb:fh(ah(),hh(),"languageCode")}}),wc.Persistence=qs,wc.Persistence.LOCAL="local",wc.Persistence.SESSION="session",wc.Persistence.NONE="none",ph(Vu.prototype,{delete:{name:"delete",j:[]},cc:{name:"getIdTokenResult",j:[sh("opt_forceRefresh",!0)]},F:{name:"getIdToken",j:[sh("opt_forceRefresh",!0)]},cb:{name:"linkAndRetrieveDataWithCredential",j:[lh()]},oc:{name:"linkWithCredential",j:[lh()]},pc:{name:"linkWithPhoneNumber",j:[ah("phoneNumber"),dh()]},qc:{name:"linkWithPopup",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(e){return!!(e&&e.providerId&&e.hasOwnProperty&&e.hasOwnProperty("isOAuthProvider"))}}]},rc:{name:"linkWithRedirect",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(e){return!!(e&&e.providerId&&e.hasOwnProperty&&e.hasOwnProperty("isOAuthProvider"))}}]},fb:{name:"reauthenticateAndRetrieveDataWithCredential",j:[lh()]},xc:{name:"reauthenticateWithCredential",j:[lh()]},yc:{name:"reauthenticateWithPhoneNumber",j:[ah("phoneNumber"),dh()]},zc:{name:"reauthenticateWithPopup",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(e){return!!(e&&e.providerId&&e.hasOwnProperty&&e.hasOwnProperty("isOAuthProvider"))}}]},Ac:{name:"reauthenticateWithRedirect",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(e){return!!(e&&e.providerId&&e.hasOwnProperty&&e.hasOwnProperty("isOAuthProvider"))}}]},reload:{name:"reload",j:[]},ib:{name:"sendEmailVerification",j:[fh(uh("opt_actionCodeSettings",!0),hh(null,!0),"opt_actionCodeSettings",!0)]},toJSON:{name:"toJSON",j:[ah(null,!0)]},Oc:{name:"unlink",j:[ah("provider")]},ob:{name:"updateEmail",j:[ah("email")]},pb:{name:"updatePassword",j:[ah("password")]},Qc:{name:"updatePhoneNumber",j:[lh("phone")]},qb:{name:"updateProfile",j:[uh("profile")]}}),ph(xc.prototype,{execute:{name:"execute"},render:{name:"render"},reset:{name:"reset"},getResponse:{name:"getResponse"}}),ph(Fc.prototype,{execute:{name:"execute"},render:{name:"render"},reset:{name:"reset"},getResponse:{name:"getResponse"}}),ph(pe.prototype,{ia:{name:"finally"},s:{name:"catch"},then:{name:"then"}}),mh(Au.prototype,{appVerificationDisabled:{name:"appVerificationDisabledForTesting",sb:sh("appVerificationDisabledForTesting")}}),ph(Ou.prototype,{confirm:{name:"confirm",j:[ah("verificationCode")]}}),yh(Oi,"credential",function(e,t){return new Ai(e,t)},[ah("email"),ah("password")]),ph(Si.prototype,{ta:{name:"addScope",j:[ah("scope")]},Da:{name:"setCustomParameters",j:[uh("customOAuthParameters")]}}),yh(Si,"credential",Ti,[fh(ah(),uh(),"token")]),yh(Oi,"credentialWithLink",Pi,[ah("email"),ah("emailLink")]),ph(wi.prototype,{ta:{name:"addScope",j:[ah("scope")]},Da:{name:"setCustomParameters",j:[uh("customOAuthParameters")]}}),yh(wi,"credential",Ci,[fh(ah(),uh(),"token")]),ph(Ii.prototype,{ta:{name:"addScope",j:[ah("scope")]},Da:{name:"setCustomParameters",j:[uh("customOAuthParameters")]}}),yh(Ii,"credential",Ni,[fh(ah(),fh(uh(),hh()),"idToken"),fh(ah(),hh(),"accessToken",!0)]),ph(Ri.prototype,{Da:{name:"setCustomParameters",j:[uh("customOAuthParameters")]}}),yh(Ri,"credential",Di,[fh(ah(),uh(),"token"),ah("secret",!0)]),ph(Ei.prototype,{ta:{name:"addScope",j:[ah("scope")]},credential:{name:"credential",j:[fh(ah(),hh(),"idToken",!0),fh(ah(),hh(),"accessToken",!0)]},Da:{name:"setCustomParameters",j:[uh("customOAuthParameters")]}}),yh(Fi,"credential",xi,[ah("verificationId"),ah("verificationCode")]),ph(Fi.prototype,{Ta:{name:"verifyPhoneNumber",j:[ah("phoneNumber"),dh()]}}),ph(xr.prototype,{toJSON:{name:"toJSON",j:[ah(null,!0)]}}),ph(Gi.prototype,{toJSON:{name:"toJSON",j:[ah(null,!0)]}}),ph(Ki.prototype,{toJSON:{name:"toJSON",j:[ah(null,!0)]}}),ph(rh.prototype,{clear:{name:"clear",j:[]},render:{name:"render",j:[]},verify:{name:"verify",j:[]}}),function(){if(void 0===firebase||!firebase.INTERNAL||!firebase.INTERNAL.registerService)throw Error("Cannot find the firebase namespace; be sure to include firebase-app.js before this library.");var e={Auth:wc,Error:xr};yh(e,"EmailAuthProvider",Oi,[]),yh(e,"FacebookAuthProvider",Si,[]),yh(e,"GithubAuthProvider",wi,[]),yh(e,"GoogleAuthProvider",Ii,[]),yh(e,"TwitterAuthProvider",Ri,[]),yh(e,"OAuthProvider",Ei,[ah("providerId")]),yh(e,"PhoneAuthProvider",Fi,[{name:"auth",K:"an instance of Firebase Auth",optional:!0,M:function(e){return!!(e&&e instanceof wc)}}]),yh(e,"RecaptchaVerifier",rh,[fh(ah(),{name:"",K:"an HTML element",optional:!1,M:function(e){return!!(e&&e instanceof Element)}},"recaptchaContainer"),uh("recaptchaParameters",!0),{name:"app",K:"an instance of Firebase App",optional:!0,M:function(e){return!!(e&&e instanceof firebase.app.App)}}]),firebase.INTERNAL.registerService("auth",function(e,t){return t({INTERNAL:{getUid:y((e=new wc(e)).getUid,e),getToken:y(e.bc,e),addAuthTokenListener:y(e.Ub,e),removeAuthTokenListener:y(e.Bc,e)}}),e},e,function(e,t){if("create"===e)try{t.auth()}catch(e){}}),firebase.INTERNAL.extendNamespace({User:Vu})}()}).call("undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(LogLevel||(LogLevel={}));var defaultLogLevel=LogLevel.INFO,defaultLogHandler=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(t<e.logLevel)){var i=(new Date).toISOString();switch(t){case LogLevel.DEBUG:case LogLevel.VERBOSE:console.log.apply(console,["["+i+"] "+e.name+":"].concat(n));break;case LogLevel.INFO:console.info.apply(console,["["+i+"] "+e.name+":"].concat(n));break;case LogLevel.WARN:console.warn.apply(console,["["+i+"] "+e.name+":"].concat(n));break;case LogLevel.ERROR:console.error.apply(console,["["+i+"] "+e.name+":"].concat(n));break;default:throw new Error("Attempted to log a message with an invalid logType (value: "+t+")")}}},Logger=function(){function e(e){this.name=e,this._logLevel=defaultLogLevel,this._logHandler=defaultLogHandler}return Object.defineProperty(e.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){if(!(e in LogLevel))throw new TypeError("Invalid value assigned to `logLevel`");this._logLevel=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"logHandler",{get:function(){return this._logHandler},set:function(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e},enumerable:!0,configurable:!0}),e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logHandler.apply(this,[this,LogLevel.DEBUG].concat(e))},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logHandler.apply(this,[this,LogLevel.VERBOSE].concat(e))},e.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logHandler.apply(this,[this,LogLevel.INFO].concat(e))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logHandler.apply(this,[this,LogLevel.WARN].concat(e))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logHandler.apply(this,[this,LogLevel.ERROR].concat(e))},e}(),DOMStorageWrapper=function(){function e(e){this.domStorage_=e,this.prefix_="firebase:"}return e.prototype.set=function(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),stringify(t))},e.prototype.get=function(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:jsonEval(t)},e.prototype.remove=function(e){this.domStorage_.removeItem(this.prefixedName_(e))},e.prototype.prefixedName_=function(e){return this.prefix_+e},e.prototype.toString=function(){return this.domStorage_.toString()},e}(),MemoryStorage=function(){function e(){this.cache_={},this.isInMemoryStorage=!0}return e.prototype.set=function(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t},e.prototype.get=function(e){return contains(this.cache_,e)?this.cache_[e]:null},e.prototype.remove=function(e){delete this.cache_[e]},e}(),createStoragefor=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){var t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new DOMStorageWrapper(t)}}catch(e){}return new MemoryStorage},PersistentStorage=createStoragefor("localStorage"),SessionStorage=createStoragefor("sessionStorage"),logClient=new Logger("@firebase/database"),LUIDGenerator=function(){var e=1;return function(){return e++}}(),sha1=function(e){var t=stringToByteArray$1(e),n=new Sha1;n.update(t);var r=n.digest();return base64.encodeByteArray(r)},buildLogMessage_=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n="",r=0;r<e.length;r++)Array.isArray(e[r])||e[r]&&"object"==typeof e[r]&&"number"==typeof e[r].length?n+=buildLogMessage_.apply(null,e[r]):"object"==typeof e[r]?n+=stringify(e[r]):n+=e[r],n+=" ";return n},logger=null,firstLog_=!0,enableLogging=function(e,t){assert(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(logClient.logLevel=LogLevel.VERBOSE,logger=logClient.log.bind(logClient),t&&SessionStorage.set("logging_enabled",!0)):"function"==typeof e?logger=e:(logger=null,SessionStorage.remove("logging_enabled"))},log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(!0===firstLog_&&(firstLog_=!1,null===logger&&!0===SessionStorage.get("logging_enabled")&&enableLogging(!0)),logger){var n=buildLogMessage_.apply(null,e);logger(n)}},logWrapper=function(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];log.apply(void 0,[e].concat(t))}},error$1=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="FIREBASE INTERNAL ERROR: "+buildLogMessage_.apply(void 0,e);logClient.error(n)},fatal=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="FIREBASE FATAL ERROR: "+buildLogMessage_.apply(void 0,e);throw logClient.error(n),new Error(n)},warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="FIREBASE WARNING: "+buildLogMessage_.apply(void 0,e);logClient.warn(n)},warnIfPageIsSecure=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&warn("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},isInvalidJSONNumber=function(e){return"number"==typeof e&&(e!=e||e==Number.POSITIVE_INFINITY||e==Number.NEGATIVE_INFINITY)},executeWhenDOMReady=function(e){if(isNodeSdk()||"complete"===document.readyState)e();else{var t=!1,n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}},MIN_NAME="[MIN_NAME]",MAX_NAME="[MAX_NAME]",nameCompare=function(e,t){if(e===t)return 0;if(e===MIN_NAME||t===MAX_NAME)return-1;if(t===MIN_NAME||e===MAX_NAME)return 1;var n=tryParseInt(e),r=tryParseInt(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null!==r?1:e<t?-1:1},stringCompare=function(e,t){return e===t?0:e<t?-1:1},requireKey=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+stringify(t))},ObjectToUniqueKey=function(e){if("object"!=typeof e||null===e)return stringify(e);var t=[];for(var n in e)t.push(n);t.sort();for(var r="{",i=0;i<t.length;i++)0!==i&&(r+=","),r+=stringify(t[i]),r+=":",r+=ObjectToUniqueKey(e[t[i]]);return r+="}"},splitStringBySize=function(e,t){var n=e.length;if(n<=t)return[e];for(var r=[],i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r},each=function(e,t){if(Array.isArray(e))for(var n=0;n<e.length;++n)t(n,e[n]);else forEach(e,function(e,n){return t(n,e)})},doubleToIEEE754String=function(e){assert(!isInvalidJSONNumber(e),"Invalid JSON number");var t,n,r,i,o,a,s;for(0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(n=(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023))+1023,r=Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,r=Math.round(e/Math.pow(2,-1074)))),a=[],o=52;o;o-=1)a.push(r%2?1:0),r=Math.floor(r/2);for(o=11;o;o-=1)a.push(n%2?1:0),n=Math.floor(n/2);a.push(t?1:0),a.reverse(),s=a.join("");var u="";for(o=0;o<64;o+=8){var c=parseInt(s.substr(o,8),2).toString(16);1===c.length&&(c="0"+c),u+=c}return u.toLowerCase()},isChromeExtensionContentScript=function(){return!("object"!=typeof window||!window.chrome||!window.chrome.extension||/^chrome/.test(window.location.href))},isWindowsStoreApp=function(){return"object"==typeof Windows&&"object"==typeof Windows.UI},errorForServerCode=function(e,t){var n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"==e?n="Client doesn't have permission to access the desired data.":"unavailable"==e&&(n="The service is unavailable");var r=new Error(e+" at "+t.path.toString()+": "+n);return r.code=e.toUpperCase(),r},INTEGER_REGEXP_=new RegExp("^-?\\d{1,10}$"),tryParseInt=function(e){if(INTEGER_REGEXP_.test(e)){var t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},exceptionGuard=function(e){try{e()}catch(e){setTimeout(function(){var t=e.stack||"";throw warn("Exception was thrown by user callback.",t),e},Math.floor(0))}},beingCrawled=function(){return("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},setTimeoutNonBlocking=function(e,t){var n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n},Path=function(){function e(e,t){if(void 0===t){this.pieces_=e.split("/");for(var n=0,r=0;r<this.pieces_.length;r++)this.pieces_[r].length>0&&(this.pieces_[n]=this.pieces_[r],n++);this.pieces_.length=n,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}return Object.defineProperty(e,"Empty",{get:function(){return new e("")},enumerable:!0,configurable:!0}),e.prototype.getFront=function(){return this.pieceNum_>=this.pieces_.length?null:this.pieces_[this.pieceNum_]},e.prototype.getLength=function(){return this.pieces_.length-this.pieceNum_},e.prototype.popFront=function(){var t=this.pieceNum_;return t<this.pieces_.length&&t++,new e(this.pieces_,t)},e.prototype.getBack=function(){return this.pieceNum_<this.pieces_.length?this.pieces_[this.pieces_.length-1]:null},e.prototype.toString=function(){for(var e="",t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"},e.prototype.toUrlEncodedString=function(){for(var e="",t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+encodeURIComponent(String(this.pieces_[t])));return e||"/"},e.prototype.slice=function(e){return void 0===e&&(e=0),this.pieces_.slice(this.pieceNum_+e)},e.prototype.parent=function(){if(this.pieceNum_>=this.pieces_.length)return null;for(var t=[],n=this.pieceNum_;n<this.pieces_.length-1;n++)t.push(this.pieces_[n]);return new e(t,0)},e.prototype.child=function(t){for(var n=[],r=this.pieceNum_;r<this.pieces_.length;r++)n.push(this.pieces_[r]);if(t instanceof e)for(r=t.pieceNum_;r<t.pieces_.length;r++)n.push(t.pieces_[r]);else{var i=t.split("/");for(r=0;r<i.length;r++)i[r].length>0&&n.push(i[r])}return new e(n,0)},e.prototype.isEmpty=function(){return this.pieceNum_>=this.pieces_.length},e.relativePath=function(t,n){var r=t.getFront(),i=n.getFront();if(null===r)return n;if(r===i)return e.relativePath(t.popFront(),n.popFront());throw new Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+t+")")},e.comparePaths=function(e,t){for(var n=e.slice(),r=t.slice(),i=0;i<n.length&&i<r.length;i++){var o=nameCompare(n[i],r[i]);if(0!==o)return o}return n.length===r.length?0:n.length<r.length?-1:1},e.prototype.equals=function(e){if(this.getLength()!==e.getLength())return!1;for(var t=this.pieceNum_,n=e.pieceNum_;t<=this.pieces_.length;t++,n++)if(this.pieces_[t]!==e.pieces_[n])return!1;return!0},e.prototype.contains=function(e){var t=this.pieceNum_,n=e.pieceNum_;if(this.getLength()>e.getLength())return!1;for(;t<this.pieces_.length;){if(this.pieces_[t]!==e.pieces_[n])return!1;++t,++n}return!0},e}(),ValidationPath=function(){function e(e,t){this.errorPrefix_=t,this.parts_=e.slice(),this.byteLength_=Math.max(1,this.parts_.length);for(var n=0;n<this.parts_.length;n++)this.byteLength_+=stringLength(this.parts_[n]);this.checkValid_()}return Object.defineProperty(e,"MAX_PATH_DEPTH",{get:function(){return 32},enumerable:!0,configurable:!0}),Object.defineProperty(e,"MAX_PATH_LENGTH_BYTES",{get:function(){return 768},enumerable:!0,configurable:!0}),e.prototype.push=function(e){this.parts_.length>0&&(this.byteLength_+=1),this.parts_.push(e),this.byteLength_+=stringLength(e),this.checkValid_()},e.prototype.pop=function(){var e=this.parts_.pop();this.byteLength_-=stringLength(e),this.parts_.length>0&&(this.byteLength_-=1)},e.prototype.checkValid_=function(){if(this.byteLength_>e.MAX_PATH_LENGTH_BYTES)throw new Error(this.errorPrefix_+"has a key path longer than "+e.MAX_PATH_LENGTH_BYTES+" bytes ("+this.byteLength_+").");if(this.parts_.length>e.MAX_PATH_DEPTH)throw new Error(this.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+e.MAX_PATH_DEPTH+") or object contains a cycle "+this.toErrorString())},e.prototype.toErrorString=function(){return 0==this.parts_.length?"":"in property '"+this.parts_.join(".")+"'"},e}(),PROTOCOL_VERSION="5",VERSION_PARAM="v",TRANSPORT_SESSION_PARAM="s",REFERER_PARAM="r",FORGE_REF="f",FORGE_DOMAIN="firebaseio.com",LAST_SESSION_PARAM="ls",WEBSOCKET="websocket",LONG_POLLING="long_polling",RepoInfo=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this.secure=t,this.namespace=n,this.webSocketOnly=r,this.persistenceKey=i,this.host=e.toLowerCase(),this.domain=this.host.substr(this.host.indexOf(".")+1),this.internalHost=PersistentStorage.get("host:"+e)||this.host}return e.prototype.needsQueryParam=function(){return this.host!==this.internalHost||this.isCustomHost()},e.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},e.prototype.isDemoHost=function(){return"firebaseio-demo.com"===this.domain},e.prototype.isCustomHost=function(){return"firebaseio.com"!==this.domain&&"firebaseio-demo.com"!==this.domain},e.prototype.updateHost=function(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&PersistentStorage.set("host:"+this.host,this.internalHost))},e.prototype.connectionURL=function(e,t){var n;if(assert("string"==typeof e,"typeof type must == string"),assert("object"==typeof t,"typeof params must == object"),e===WEBSOCKET)n=(this.secure?"wss://":"ws://")+this.internalHost+"/.ws?";else{if(e!==LONG_POLLING)throw new Error("Unknown connection type: "+e);n=(this.secure?"https://":"http://")+this.internalHost+"/.lp?"}this.needsQueryParam()&&(t.ns=this.namespace);var r=[];return forEach(t,function(e,t){r.push(e+"="+t)}),n+r.join("&")},e.prototype.toString=function(){var e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e},e.prototype.toURLString=function(){return(this.secure?"https://":"http://")+this.host},e}();function decodePath(e){for(var t="",n=e.split("/"),r=0;r<n.length;r++)if(n[r].length>0){var i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}function decodeQuery(e){var t={};"?"===e.charAt(0)&&(e=e.substring(1));for(var n=0,r=e.split("&");n<r.length;n++){var i=r[n];if(0!==i.length){var o=i.split("=");2===o.length?t[decodeURIComponent(o[0])]=decodeURIComponent(o[1]):warn("Invalid query segment '"+i+"' in query '"+e+"'")}}return t}var parseRepoInfo=function(e){var t=parseURL(e),n=t.subdomain;"firebase"===t.domain&&fatal(t.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),n&&"undefined"!=n||"localhost"===t.domain||fatal("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),t.secure||warnIfPageIsSecure();var r="ws"===t.scheme||"wss"===t.scheme;return{repoInfo:new RepoInfo(t.host,t.secure,n,r),path:new Path(t.pathString)}},parseURL=function(e){var t="",n="",r="",i="",o=!0,a="https",s=443;if("string"==typeof e){var u=e.indexOf("//");u>=0&&(a=e.substring(0,u-1),e=e.substring(u+2));var c=e.indexOf("/");-1===c&&(c=e.length);var h=e.indexOf("?");-1===h&&(h=e.length),t=e.substring(0,Math.min(c,h)),c<h&&(i=decodePath(e.substring(c,h)));var l=decodeQuery(e.substring(Math.min(e.length,h)));(u=t.indexOf(":"))>=0?(o="https"===a||"wss"===a,s=parseInt(t.substring(u+1),10)):u=e.length;var d=t.split(".");3===d.length?(n=d[1],r=d[0].toLowerCase()):2===d.length?n=d[0]:"localhost"===d[0].slice(0,u).toLowerCase()&&(n="localhost"),""===r&&"ns"in l&&(r=l.ns)}return{host:t,port:s,domain:n,subdomain:r,secure:o,scheme:a,pathString:i}},INVALID_KEY_REGEX_=/[\[\].#$\/\u0000-\u001F\u007F]/,INVALID_PATH_REGEX_=/[\[\].#$\u0000-\u001F\u007F]/,MAX_LEAF_SIZE_=10485760,isValidKey=function(e){return"string"==typeof e&&0!==e.length&&!INVALID_KEY_REGEX_.test(e)},isValidPathString=function(e){return"string"==typeof e&&0!==e.length&&!INVALID_PATH_REGEX_.test(e)},isValidRootPathString=function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),isValidPathString(e)},isValidPriority=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!isInvalidJSONNumber(e)||e&&"object"==typeof e&&contains(e,".sv")},validateFirebaseDataArg=function(e,t,n,r,i){i&&void 0===n||validateFirebaseData(errorPrefix(e,t,i),n,r)},validateFirebaseData=function(e,t,n){var r=n instanceof Path?new ValidationPath(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+r.toErrorString());if("function"==typeof t)throw new Error(e+"contains a function "+r.toErrorString()+" with contents = "+t.toString());if(isInvalidJSONNumber(t))throw new Error(e+"contains "+t.toString()+" "+r.toErrorString());if("string"==typeof t&&t.length>MAX_LEAF_SIZE_/3&&stringLength(t)>MAX_LEAF_SIZE_)throw new Error(e+"contains a string greater than "+MAX_LEAF_SIZE_+" utf8 bytes "+r.toErrorString()+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){var i=!1,o=!1;if(forEach(t,function(t,n){if(".value"===t)i=!0;else if(".priority"!==t&&".sv"!==t&&(o=!0,!isValidKey(t)))throw new Error(e+" contains an invalid key ("+t+") "+r.toErrorString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');r.push(t),validateFirebaseData(e,n,r),r.pop()}),i&&o)throw new Error(e+' contains ".value" child '+r.toErrorString()+" in addition to actual children.")}},validateFirebaseMergePaths=function(e,t){var n,r;for(n=0;n<t.length;n++)for(var i=(r=t[n]).slice(),o=0;o<i.length;o++)if(".priority"===i[o]&&o===i.length-1);else if(!isValidKey(i[o]))throw new Error(e+"contains an invalid key ("+i[o]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');t.sort(Path.comparePaths);var a=null;for(n=0;n<t.length;n++){if(r=t[n],null!==a&&a.contains(r))throw new Error(e+"contains a path "+a.toString()+" that is ancestor of another path "+r.toString());a=r}},validateFirebaseMergeDataArg=function(e,t,n,r,i){if(!i||void 0!==n){var o=errorPrefix(e,t,i);if(!n||"object"!=typeof n||Array.isArray(n))throw new Error(o+" must be an object containing the children to replace.");var a=[];forEach(n,function(e,t){var n=new Path(e);if(validateFirebaseData(o,t,r.child(n)),".priority"===n.getBack()&&!isValidPriority(t))throw new Error(o+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");a.push(n)}),validateFirebaseMergePaths(o,a)}},validatePriority=function(e,t,n,r){if(!r||void 0!==n){if(isInvalidJSONNumber(n))throw new Error(errorPrefix(e,t,r)+"is "+n.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!isValidPriority(n))throw new Error(errorPrefix(e,t,r)+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},validateEventType=function(e,t,n,r){if(!r||void 0!==n)switch(n){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(errorPrefix(e,t,r)+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}},validateKey=function(e,t,n,r){if(!(r&&void 0===n||isValidKey(n)))throw new Error(errorPrefix(e,t,r)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},validatePathString=function(e,t,n,r){if(!(r&&void 0===n||isValidPathString(n)))throw new Error(errorPrefix(e,t,r)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},validateRootPathString=function(e,t,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),validatePathString(e,t,n,r)},validateWritablePath=function(e,t){if(".info"===t.getFront())throw new Error(e+" failed = Can't modify data under /.info/")},validateUrl=function(e,t,n){var r=n.path.toString();if("string"!=typeof n.repoInfo.host||0===n.repoInfo.host.length||!isValidKey(n.repoInfo.namespace)&&"localhost"!==n.repoInfo.host.split(":")[0]||0!==r.length&&!isValidRootPathString(r))throw new Error(errorPrefix(e,t,!1)+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')},validateBoolean=function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(errorPrefix(e,t,r)+"must be a boolean.")},OnDisconnect=function(){function e(e,t){this.repo_=e,this.path_=t}return e.prototype.cancel=function(e){validateArgCount("OnDisconnect.cancel",0,1,arguments.length),validateCallback("OnDisconnect.cancel",1,e,!0);var t=new Deferred;return this.repo_.onDisconnectCancel(this.path_,t.wrapCallback(e)),t.promise},e.prototype.remove=function(e){validateArgCount("OnDisconnect.remove",0,1,arguments.length),validateWritablePath("OnDisconnect.remove",this.path_),validateCallback("OnDisconnect.remove",1,e,!0);var t=new Deferred;return this.repo_.onDisconnectSet(this.path_,null,t.wrapCallback(e)),t.promise},e.prototype.set=function(e,t){validateArgCount("OnDisconnect.set",1,2,arguments.length),validateWritablePath("OnDisconnect.set",this.path_),validateFirebaseDataArg("OnDisconnect.set",1,e,this.path_,!1),validateCallback("OnDisconnect.set",2,t,!0);var n=new Deferred;return this.repo_.onDisconnectSet(this.path_,e,n.wrapCallback(t)),n.promise},e.prototype.setWithPriority=function(e,t,n){validateArgCount("OnDisconnect.setWithPriority",2,3,arguments.length),validateWritablePath("OnDisconnect.setWithPriority",this.path_),validateFirebaseDataArg("OnDisconnect.setWithPriority",1,e,this.path_,!1),validatePriority("OnDisconnect.setWithPriority",2,t,!1),validateCallback("OnDisconnect.setWithPriority",3,n,!0);var r=new Deferred;return this.repo_.onDisconnectSetWithPriority(this.path_,e,t,r.wrapCallback(n)),r.promise},e.prototype.update=function(e,t){if(validateArgCount("OnDisconnect.update",1,2,arguments.length),validateWritablePath("OnDisconnect.update",this.path_),Array.isArray(e)){for(var n={},r=0;r<e.length;++r)n[""+r]=e[r];e=n,warn("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}validateFirebaseMergeDataArg("OnDisconnect.update",1,e,this.path_,!1),validateCallback("OnDisconnect.update",2,t,!0);var i=new Deferred;return this.repo_.onDisconnectUpdate(this.path_,e,i.wrapCallback(t)),i.promise},e}(),TransactionResult=function(){function e(e,t){this.committed=e,this.snapshot=t}return e.prototype.toJSON=function(){return validateArgCount("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}},e}(),nextPushId=(PUSH_CHARS="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",lastPushTime=0,lastRandChars=[],function(e){var t,n=e===lastPushTime;lastPushTime=e;var r=new Array(8);for(t=7;t>=0;t--)r[t]=PUSH_CHARS.charAt(e%64),e=Math.floor(e/64);assert(0===e,"Cannot push at time == 0");var i=r.join("");if(n){for(t=11;t>=0&&63===lastRandChars[t];t--)lastRandChars[t]=0;lastRandChars[t]++}else for(t=0;t<12;t++)lastRandChars[t]=Math.floor(64*Math.random());for(t=0;t<12;t++)i+=PUSH_CHARS.charAt(lastRandChars[t]);return assert(20===i.length,"nextPushId: Length should be 20."),i}),PUSH_CHARS,lastPushTime,lastRandChars,NamedNode=function(){function e(e,t){this.name=e,this.node=t}return e.Wrap=function(t,n){return new e(t,n)},e}(),Index=function(){function e(){}return e.prototype.getCompare=function(){return this.compare.bind(this)},e.prototype.indexedValueChanged=function(e,t){var n=new NamedNode(MIN_NAME,e),r=new NamedNode(MIN_NAME,t);return 0!==this.compare(n,r)},e.prototype.minPost=function(){return NamedNode.MIN},e}(),__EMPTY_NODE,KeyIndex=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),Object.defineProperty(t,"__EMPTY_NODE",{get:function(){return __EMPTY_NODE},set:function(e){__EMPTY_NODE=e},enumerable:!0,configurable:!0}),t.prototype.compare=function(e,t){return nameCompare(e.name,t.name)},t.prototype.isDefinedOn=function(e){throw assertionError("KeyIndex.isDefinedOn not expected to be called.")},t.prototype.indexedValueChanged=function(e,t){return!1},t.prototype.minPost=function(){return NamedNode.MIN},t.prototype.maxPost=function(){return new NamedNode(MAX_NAME,__EMPTY_NODE)},t.prototype.makePost=function(e,t){return assert("string"==typeof e,"KeyIndex indexValue must always be a string."),new NamedNode(e,__EMPTY_NODE)},t.prototype.toString=function(){return".key"},t}(Index),KEY_INDEX=new KeyIndex,MAX_NODE;function setMaxNode(e){MAX_NODE=e}var priorityHashText=function(e){return"number"==typeof e?"number:"+doubleToIEEE754String(e):"string:"+e},validatePriorityNode=function(e){if(e.isLeafNode()){var t=e.val();assert("string"==typeof t||"number"==typeof t||"object"==typeof t&&contains(t,".sv"),"Priority must be a string or number.")}else assert(e===MAX_NODE||e.isEmpty(),"priority of unexpected type.");assert(e===MAX_NODE||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")},__childrenNodeConstructor,LeafNode=function(){function e(t,n){void 0===n&&(n=e.__childrenNodeConstructor.EMPTY_NODE),this.value_=t,this.priorityNode_=n,this.lazyHash_=null,assert(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),validatePriorityNode(this.priorityNode_)}return Object.defineProperty(e,"__childrenNodeConstructor",{get:function(){return __childrenNodeConstructor},set:function(e){__childrenNodeConstructor=e},enumerable:!0,configurable:!0}),e.prototype.isLeafNode=function(){return!0},e.prototype.getPriority=function(){return this.priorityNode_},e.prototype.updatePriority=function(t){return new e(this.value_,t)},e.prototype.getImmediateChild=function(t){return".priority"===t?this.priorityNode_:e.__childrenNodeConstructor.EMPTY_NODE},e.prototype.getChild=function(t){return t.isEmpty()?this:".priority"===t.getFront()?this.priorityNode_:e.__childrenNodeConstructor.EMPTY_NODE},e.prototype.hasChild=function(){return!1},e.prototype.getPredecessorChildName=function(e,t){return null},e.prototype.updateImmediateChild=function(t,n){return".priority"===t?this.updatePriority(n):n.isEmpty()&&".priority"!==t?this:e.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(t,n).updatePriority(this.priorityNode_)},e.prototype.updateChild=function(t,n){var r=t.getFront();return null===r?n:n.isEmpty()&&".priority"!==r?this:(assert(".priority"!==r||1===t.getLength(),".priority must be the last token in a path"),this.updateImmediateChild(r,e.__childrenNodeConstructor.EMPTY_NODE.updateChild(t.popFront(),n)))},e.prototype.isEmpty=function(){return!1},e.prototype.numChildren=function(){return 0},e.prototype.forEachChild=function(e,t){return!1},e.prototype.val=function(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()},e.prototype.hash=function(){if(null===this.lazyHash_){var e="";this.priorityNode_.isEmpty()||(e+="priority:"+priorityHashText(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"===t?doubleToIEEE754String(this.value_):this.value_,this.lazyHash_=sha1(e)}return this.lazyHash_},e.prototype.getValue=function(){return this.value_},e.prototype.compareTo=function(t){return t===e.__childrenNodeConstructor.EMPTY_NODE?1:t instanceof e.__childrenNodeConstructor?-1:(assert(t.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(t))},e.prototype.compareToLeafNode_=function(t){var n=typeof t.value_,r=typeof this.value_,i=e.VALUE_TYPE_ORDER.indexOf(n),o=e.VALUE_TYPE_ORDER.indexOf(r);return assert(i>=0,"Unknown leaf type: "+n),assert(o>=0,"Unknown leaf type: "+r),i===o?"object"===r?0:this.value_<t.value_?-1:this.value_===t.value_?0:1:o-i},e.prototype.withIndex=function(){return this},e.prototype.isIndexed=function(){return!0},e.prototype.equals=function(e){if(e===this)return!0;if(e.isLeafNode()){var t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1},e.VALUE_TYPE_ORDER=["object","boolean","number","string"],e}(),nodeFromJSON,MAX_NODE$1;function setNodeFromJSON(e){nodeFromJSON=e}function setMaxNode$1(e){MAX_NODE$1=e}var PriorityIndex=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.compare=function(e,t){var n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?nameCompare(e.name,t.name):i},t.prototype.isDefinedOn=function(e){return!e.getPriority().isEmpty()},t.prototype.indexedValueChanged=function(e,t){return!e.getPriority().equals(t.getPriority())},t.prototype.minPost=function(){return NamedNode.MIN},t.prototype.maxPost=function(){return new NamedNode(MAX_NAME,new LeafNode("[PRIORITY-POST]",MAX_NODE$1))},t.prototype.makePost=function(e,t){var n=nodeFromJSON(e);return new NamedNode(t,new LeafNode("[PRIORITY-POST]",n))},t.prototype.toString=function(){return".priority"},t}(Index),PRIORITY_INDEX=new PriorityIndex,SortedMapIterator=function(){function e(e,t,n,r,i){void 0===i&&(i=null),this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];for(var o=1;!e.isEmpty();)if(e=e,o=t?n(e.key,t):1,r&&(o*=-1),o<0)e=this.isReverse_?e.left:e.right;else{if(0===o){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}return e.prototype.getNext=function(){if(0===this.nodeStack_.length)return null;var e,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e},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 this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}},e}(),LLRBNode=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:SortedMap.EMPTY_NODE,this.right=null!=o?o:SortedMap.EMPTY_NODE}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.count=function(){return this.left.count()+1+this.right.count()},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,i;return(i=(r=n(e,(i=this).key))<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n))).fixUp_()},e.prototype.removeMin_=function(){if(this.left.isEmpty())return SortedMap.EMPTY_NODE;var e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),(e=e.copy(null,null,null,e.left.removeMin_(),null)).fixUp_()},e.prototype.remove=function(e,t){var n,r;if(t(e,(n=this).key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return SortedMap.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.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.count()+1},e.prototype.check_=function(){var e;if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");if((e=this.left.check_())!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)},e.RED=!0,e.BLACK=!1,e}(),LLRBEmptyNode=function(){function e(){}return e.prototype.copy=function(e,t,n,r,i){return this},e.prototype.insert=function(e,t,n){return new LLRBNode(e,t,null)},e.prototype.remove=function(e,t){return this},e.prototype.count=function(){return 0},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.check_=function(){return 0},e.prototype.isRed_=function(){return!1},e}(),SortedMap=function(){function e(t,n){void 0===n&&(n=e.EMPTY_NODE),this.comparator_=t,this.root_=n}return e.prototype.insert=function(t,n){return new e(this.comparator_,this.root_.insert(t,n,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))},e.prototype.remove=function(t){return new e(this.comparator_,this.root_.remove(t,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))},e.prototype.get=function(e){for(var t,n=this.root_;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null},e.prototype.getPredecessorKey=function(e){for(var t,n=this.root_,r=null;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")},e.prototype.isEmpty=function(){return this.root_.isEmpty()},e.prototype.count=function(){return this.root_.count()},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.reverseTraversal=function(e){return this.root_.reverseTraversal(e)},e.prototype.getIterator=function(e){return new SortedMapIterator(this.root_,null,this.comparator_,!1,e)},e.prototype.getIteratorFrom=function(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,!1,t)},e.prototype.getReverseIteratorFrom=function(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,!0,t)},e.prototype.getReverseIterator=function(e){return new SortedMapIterator(this.root_,null,this.comparator_,!0,e)},e.EMPTY_NODE=new LLRBEmptyNode,e}(),LOG_2=Math.log(2),Base12Num=function(){function e(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/LOG_2,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}return e.prototype.nextBitIsOne=function(){var e=!(this.bits_&1<<this.current_);return this.current_--,e},e}(),buildChildSet=function(e,t,n,r){e.sort(t);var i=function(t,r){var o,a,s=r-t;if(0==s)return null;if(1==s)return o=e[t],a=n?n(o):o,new LLRBNode(a,o.node,LLRBNode.BLACK,null,null);var u=parseInt(s/2,10)+t,c=i(t,u),h=i(u+1,r);return o=e[u],a=n?n(o):o,new LLRBNode(a,o.node,LLRBNode.BLACK,c,h)},o=function(t){for(var r=null,o=null,a=e.length,s=function(t,r){var o=a-t,s=a;a-=t;var c=i(o+1,s),h=e[o],l=n?n(h):h;u(new LLRBNode(l,h.node,r,null,c))},u=function(e){r?(r.left=e,r=e):(o=e,r=e)},c=0;c<t.count;++c){var h=t.nextBitIsOne(),l=Math.pow(2,t.count-(c+1));h?s(l,LLRBNode.BLACK):(s(l,LLRBNode.BLACK),s(l,LLRBNode.RED))}return o}(new Base12Num(e.length));return new SortedMap(r||t,o)},_defaultIndexMap,fallbackObject={},IndexMap=function(){function e(e,t){this.indexes_=e,this.indexSet_=t}return Object.defineProperty(e,"Default",{get:function(){return assert(fallbackObject&&PRIORITY_INDEX,"ChildrenNode.ts has not been loaded"),_defaultIndexMap=_defaultIndexMap||new e({".priority":fallbackObject},{".priority":PRIORITY_INDEX})},enumerable:!0,configurable:!0}),e.prototype.get=function(e){var t=safeGet(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t===fallbackObject?null:t},e.prototype.hasIndex=function(e){return contains(this.indexSet_,e.toString())},e.prototype.addIndex=function(t,n){assert(t!==KEY_INDEX,"KeyIndex always exists and isn't meant to be added to the IndexMap.");for(var r,i=[],o=!1,a=n.getIterator(NamedNode.Wrap),s=a.getNext();s;)o=o||t.isDefinedOn(s.node),i.push(s),s=a.getNext();r=o?buildChildSet(i,t.getCompare()):fallbackObject;var u=t.toString(),c=clone(this.indexSet_);c[u]=t;var h=clone(this.indexes_);return h[u]=r,new e(h,c)},e.prototype.addToIndexes=function(t,n){var r=this;return new e(map(this.indexes_,function(e,i){var o=safeGet(r.indexSet_,i);if(assert(o,"Missing index implementation for "+i),e===fallbackObject){if(o.isDefinedOn(t.node)){for(var a=[],s=n.getIterator(NamedNode.Wrap),u=s.getNext();u;)u.name!=t.name&&a.push(u),u=s.getNext();return a.push(t),buildChildSet(a,o.getCompare())}return fallbackObject}var c=n.get(t.name),h=e;return c&&(h=h.remove(new NamedNode(t.name,c))),h.insert(t,t.node)}),this.indexSet_)},e.prototype.removeFromIndexes=function(t,n){return new e(map(this.indexes_,function(e){if(e===fallbackObject)return e;var r=n.get(t.name);return r?e.remove(new NamedNode(t.name,r)):e}),this.indexSet_)},e}(),EMPTY_NODE;function NAME_ONLY_COMPARATOR(e,t){return nameCompare(e.name,t.name)}function NAME_COMPARATOR(e,t){return nameCompare(e,t)}var ChildrenNode=function(){function e(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&validatePriorityNode(this.priorityNode_),this.children_.isEmpty()&&assert(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}return Object.defineProperty(e,"EMPTY_NODE",{get:function(){return EMPTY_NODE||(EMPTY_NODE=new e(new SortedMap(NAME_COMPARATOR),null,IndexMap.Default))},enumerable:!0,configurable:!0}),e.prototype.isLeafNode=function(){return!1},e.prototype.getPriority=function(){return this.priorityNode_||EMPTY_NODE},e.prototype.updatePriority=function(t){return this.children_.isEmpty()?this:new e(this.children_,t,this.indexMap_)},e.prototype.getImmediateChild=function(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?EMPTY_NODE:t},e.prototype.getChild=function(e){var t=e.getFront();return null===t?this:this.getImmediateChild(t).getChild(e.popFront())},e.prototype.hasChild=function(e){return null!==this.children_.get(e)},e.prototype.updateImmediateChild=function(t,n){if(assert(n,"We should always be passing snapshot nodes"),".priority"===t)return this.updatePriority(n);var r=new NamedNode(t,n),i=void 0,o=void 0;return n.isEmpty()?(i=this.children_.remove(t),o=this.indexMap_.removeFromIndexes(r,this.children_)):(i=this.children_.insert(t,n),o=this.indexMap_.addToIndexes(r,this.children_)),new e(i,i.isEmpty()?EMPTY_NODE:this.priorityNode_,o)},e.prototype.updateChild=function(e,t){var n=e.getFront();if(null===n)return t;assert(".priority"!==e.getFront()||1===e.getLength(),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(e.popFront(),t);return this.updateImmediateChild(n,r)},e.prototype.isEmpty=function(){return this.children_.isEmpty()},e.prototype.numChildren=function(){return this.children_.count()},e.prototype.val=function(t){if(this.isEmpty())return null;var n={},r=0,i=0,o=!0;if(this.forEachChild(PRIORITY_INDEX,function(a,s){n[a]=s.val(t),r++,o&&e.INTEGER_REGEXP_.test(a)?i=Math.max(i,Number(a)):o=!1}),!t&&o&&i<2*r){var a=[];for(var s in n)a[s]=n[s];return a}return t&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n},e.prototype.hash=function(){if(null===this.lazyHash_){var e="";this.getPriority().isEmpty()||(e+="priority:"+priorityHashText(this.getPriority().val())+":"),this.forEachChild(PRIORITY_INDEX,function(t,n){var r=n.hash();""!==r&&(e+=":"+t+":"+r)}),this.lazyHash_=""===e?"":sha1(e)}return this.lazyHash_},e.prototype.getPredecessorChildName=function(e,t,n){var r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new NamedNode(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)},e.prototype.getFirstChildName=function(e){var t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()},e.prototype.getFirstChild=function(e){var t=this.getFirstChildName(e);return t?new NamedNode(t,this.children_.get(t)):null},e.prototype.getLastChildName=function(e){var t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()},e.prototype.getLastChild=function(e){var t=this.getLastChildName(e);return t?new NamedNode(t,this.children_.get(t)):null},e.prototype.forEachChild=function(e,t){var n=this.resolveIndex_(e);return n?n.inorderTraversal(function(e){return t(e.name,e.node)}):this.children_.inorderTraversal(t)},e.prototype.getIterator=function(e){return this.getIteratorFrom(e.minPost(),e)},e.prototype.getIteratorFrom=function(e,t){var n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,function(e){return e});for(var r=this.children_.getIteratorFrom(e.name,NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)<0;)r.getNext(),i=r.peek();return r},e.prototype.getReverseIterator=function(e){return this.getReverseIteratorFrom(e.maxPost(),e)},e.prototype.getReverseIteratorFrom=function(e,t){var n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,function(e){return e});for(var r=this.children_.getReverseIteratorFrom(e.name,NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)>0;)r.getNext(),i=r.peek();return r},e.prototype.compareTo=function(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===MAX_NODE$2?-1:0},e.prototype.withIndex=function(t){if(t===KEY_INDEX||this.indexMap_.hasIndex(t))return this;var n=this.indexMap_.addIndex(t,this.children_);return new e(this.children_,this.priorityNode_,n)},e.prototype.isIndexed=function(e){return e===KEY_INDEX||this.indexMap_.hasIndex(e)},e.prototype.equals=function(e){if(e===this)return!0;if(e.isLeafNode())return!1;var t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){for(var n=this.getIterator(PRIORITY_INDEX),r=t.getIterator(PRIORITY_INDEX),i=n.getNext(),o=r.getNext();i&&o;){if(i.name!==o.name||!i.node.equals(o.node))return!1;i=n.getNext(),o=r.getNext()}return null===i&&null===o}return!1}return!1},e.prototype.resolveIndex_=function(e){return e===KEY_INDEX?null:this.indexMap_.get(e.toString())},e.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/,e}(),MaxNode=function(e){function t(){return e.call(this,new SortedMap(NAME_COMPARATOR),ChildrenNode.EMPTY_NODE,IndexMap.Default)||this}return __extends(t,e),t.prototype.compareTo=function(e){return e===this?0:1},t.prototype.equals=function(e){return e===this},t.prototype.getPriority=function(){return this},t.prototype.getImmediateChild=function(e){return ChildrenNode.EMPTY_NODE},t.prototype.isEmpty=function(){return!1},t}(ChildrenNode),MAX_NODE$2=new MaxNode;Object.defineProperties(NamedNode,{MIN:{value:new NamedNode(MIN_NAME,ChildrenNode.EMPTY_NODE)},MAX:{value:new NamedNode(MAX_NAME,MAX_NODE$2)}}),KeyIndex.__EMPTY_NODE=ChildrenNode.EMPTY_NODE,LeafNode.__childrenNodeConstructor=ChildrenNode,setMaxNode(MAX_NODE$2),setMaxNode$1(MAX_NODE$2);var USE_HINZE=!0;function nodeFromJSON$1(e,t){if(void 0===t&&(t=null),null===e)return ChildrenNode.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),assert(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e)return new LeafNode(e,nodeFromJSON$1(t));if(e instanceof Array||!USE_HINZE){var n=ChildrenNode.EMPTY_NODE,r=e;return forEach(r,function(e,t){if(contains(r,e)&&"."!==e.substring(0,1)){var i=nodeFromJSON$1(t);!i.isLeafNode()&&i.isEmpty()||(n=n.updateImmediateChild(e,i))}}),n.updatePriority(nodeFromJSON$1(t))}var i=[],o=!1,a=e;if(forEach(a,function(e,t){if("string"!=typeof e||"."!==e.substring(0,1)){var n=nodeFromJSON$1(a[e]);n.isEmpty()||(o=o||!n.getPriority().isEmpty(),i.push(new NamedNode(e,n)))}}),0==i.length)return ChildrenNode.EMPTY_NODE;var s=buildChildSet(i,NAME_ONLY_COMPARATOR,function(e){return e.name},NAME_COMPARATOR);if(o){var u=buildChildSet(i,PRIORITY_INDEX.getCompare());return new ChildrenNode(s,nodeFromJSON$1(t),new IndexMap({".priority":u},{".priority":PRIORITY_INDEX}))}return new ChildrenNode(s,nodeFromJSON$1(t),IndexMap.Default)}setNodeFromJSON(nodeFromJSON$1);var ValueIndex=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.compare=function(e,t){var n=e.node.compareTo(t.node);return 0===n?nameCompare(e.name,t.name):n},t.prototype.isDefinedOn=function(e){return!0},t.prototype.indexedValueChanged=function(e,t){return!e.equals(t)},t.prototype.minPost=function(){return NamedNode.MIN},t.prototype.maxPost=function(){return NamedNode.MAX},t.prototype.makePost=function(e,t){var n=nodeFromJSON$1(e);return new NamedNode(t,n)},t.prototype.toString=function(){return".value"},t}(Index),VALUE_INDEX=new ValueIndex,PathIndex=function(e){function t(t){var n=e.call(this)||this;return n.indexPath_=t,assert(!t.isEmpty()&&".priority"!==t.getFront(),"Can't create PathIndex with empty path or .priority key"),n}return __extends(t,e),t.prototype.extractChild=function(e){return e.getChild(this.indexPath_)},t.prototype.isDefinedOn=function(e){return!e.getChild(this.indexPath_).isEmpty()},t.prototype.compare=function(e,t){var n=this.extractChild(e.node),r=this.extractChild(t.node),i=n.compareTo(r);return 0===i?nameCompare(e.name,t.name):i},t.prototype.makePost=function(e,t){var n=nodeFromJSON$1(e),r=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,n);return new NamedNode(t,r)},t.prototype.maxPost=function(){var e=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,MAX_NODE$2);return new NamedNode(MAX_NAME,e)},t.prototype.toString=function(){return this.indexPath_.slice().join("/")},t}(Index),DataSnapshot=function(){function e(e,t,n){this.node_=e,this.ref_=t,this.index_=n}return e.prototype.val=function(){return validateArgCount("DataSnapshot.val",0,0,arguments.length),this.node_.val()},e.prototype.exportVal=function(){return validateArgCount("DataSnapshot.exportVal",0,0,arguments.length),this.node_.val(!0)},e.prototype.toJSON=function(){return validateArgCount("DataSnapshot.toJSON",0,1,arguments.length),this.exportVal()},e.prototype.exists=function(){return validateArgCount("DataSnapshot.exists",0,0,arguments.length),!this.node_.isEmpty()},e.prototype.child=function(t){validateArgCount("DataSnapshot.child",0,1,arguments.length),t=String(t),validatePathString("DataSnapshot.child",1,t,!1);var n=new Path(t),r=this.ref_.child(n);return new e(this.node_.getChild(n),r,PRIORITY_INDEX)},e.prototype.hasChild=function(e){validateArgCount("DataSnapshot.hasChild",1,1,arguments.length),validatePathString("DataSnapshot.hasChild",1,e,!1);var t=new Path(e);return!this.node_.getChild(t).isEmpty()},e.prototype.getPriority=function(){return validateArgCount("DataSnapshot.getPriority",0,0,arguments.length),this.node_.getPriority().val()},e.prototype.forEach=function(t){var n=this;return validateArgCount("DataSnapshot.forEach",1,1,arguments.length),validateCallback("DataSnapshot.forEach",1,t,!1),!this.node_.isLeafNode()&&!!this.node_.forEachChild(this.index_,function(r,i){return t(new e(i,n.ref_.child(r),PRIORITY_INDEX))})},e.prototype.hasChildren=function(){return validateArgCount("DataSnapshot.hasChildren",0,0,arguments.length),!this.node_.isLeafNode()&&!this.node_.isEmpty()},Object.defineProperty(e.prototype,"key",{get:function(){return this.ref_.getKey()},enumerable:!0,configurable:!0}),e.prototype.numChildren=function(){return validateArgCount("DataSnapshot.numChildren",0,0,arguments.length),this.node_.numChildren()},e.prototype.getRef=function(){return validateArgCount("DataSnapshot.ref",0,0,arguments.length),this.ref_},Object.defineProperty(e.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),e}(),DataEvent=function(){function e(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}return e.prototype.getPath=function(){var e=this.snapshot.getRef();return"value"===this.eventType?e.path:e.getParent().path},e.prototype.getEventType=function(){return this.eventType},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.getPath().toString()+":"+this.eventType+":"+stringify(this.snapshot.exportVal())},e}(),CancelEvent=function(){function e(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}return e.prototype.getPath=function(){return this.path},e.prototype.getEventType=function(){return"cancel"},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.path.toString()+":cancel"},e}(),ValueEventRegistration=function(){function e(e,t,n){this.callback_=e,this.cancelCallback_=t,this.context_=n}return e.prototype.respondsTo=function(e){return"value"===e},e.prototype.createEvent=function(e,t){var n=t.getQueryParams().getIndex();return new DataEvent("value",this,new DataSnapshot(e.snapshotNode,t.getRef(),n))},e.prototype.getEventRunner=function(e){var t=this.context_;if("cancel"===e.getEventType()){assert(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(t,e.error)}}var r=this.callback_;return function(){r.call(t,e.snapshot)}},e.prototype.createCancelEvent=function(e,t){return this.cancelCallback_?new CancelEvent(this,e,t):null},e.prototype.matches=function(t){return t instanceof e&&(!t.callback_||!this.callback_||t.callback_===this.callback_&&t.context_===this.context_)},e.prototype.hasAnyCallback=function(){return null!==this.callback_},e}(),ChildEventRegistration=function(){function e(e,t,n){this.callbacks_=e,this.cancelCallback_=t,this.context_=n}return e.prototype.respondsTo=function(e){var t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,contains(this.callbacks_,t)},e.prototype.createCancelEvent=function(e,t){return this.cancelCallback_?new CancelEvent(this,e,t):null},e.prototype.createEvent=function(e,t){assert(null!=e.childName,"Child events should have a childName.");var n=t.getRef().child(e.childName),r=t.getQueryParams().getIndex();return new DataEvent(e.type,this,new DataSnapshot(e.snapshotNode,n,r),e.prevName)},e.prototype.getEventRunner=function(e){var t=this.context_;if("cancel"===e.getEventType()){assert(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(t,e.error)}}var r=this.callbacks_[e.eventType];return function(){r.call(t,e.snapshot,e.prevName)}},e.prototype.matches=function(t){if(t instanceof e){if(!this.callbacks_||!t.callbacks_)return!0;if(this.context_===t.context_){var n=getCount(t.callbacks_);if(n===getCount(this.callbacks_)){if(1===n){var r=getAnyKey(t.callbacks_),i=getAnyKey(this.callbacks_);return!(i!==r||t.callbacks_[r]&&this.callbacks_[i]&&t.callbacks_[r]!==this.callbacks_[i])}return every(this.callbacks_,function(e,n){return t.callbacks_[e]===n})}}}return!1},e.prototype.hasAnyCallback=function(){return null!==this.callbacks_},e}(),__referenceConstructor,Query=function(){function e(e,t,n,r){this.repo=e,this.path=t,this.queryParams_=n,this.orderByCalled_=r}return Object.defineProperty(e,"__referenceConstructor",{get:function(){return assert(__referenceConstructor,"Reference.ts has not been loaded"),__referenceConstructor},set:function(e){__referenceConstructor=e},enumerable:!0,configurable:!0}),e.validateQueryEndpoints_=function(e){var t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===KEY_INDEX){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), endAt(),or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!=MIN_NAME)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!=MAX_NAME)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===PRIORITY_INDEX){if(null!=t&&!isValidPriority(t)||null!=n&&!isValidPriority(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), endAt(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(assert(e.getIndex()instanceof PathIndex||e.getIndex()===VALUE_INDEX,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), endAt(), or equalTo() cannot be an object.")},e.validateLimit_=function(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.")},e.prototype.validateNoPreviousOrderByCall_=function(e){if(!0===this.orderByCalled_)throw new Error(e+": You can't combine multiple orderBy calls.")},e.prototype.getQueryParams=function(){return this.queryParams_},e.prototype.getRef=function(){return validateArgCount("Query.ref",0,0,arguments.length),new e.__referenceConstructor(this.repo,this.path)},e.prototype.on=function(t,n,r,i){validateArgCount("Query.on",2,4,arguments.length),validateEventType("Query.on",1,t,!1),validateCallback("Query.on",2,n,!1);var o=e.getCancelAndContextArgs_("Query.on",r,i);if("value"===t)this.onValueEvent(n,o.cancel,o.context);else{var a={};a[t]=n,this.onChildEvent(a,o.cancel,o.context)}return n},e.prototype.onValueEvent=function(e,t,n){var r=new ValueEventRegistration(e,t||null,n||null);this.repo.addEventCallbackForQuery(this,r)},e.prototype.onChildEvent=function(e,t,n){var r=new ChildEventRegistration(e,t,n);this.repo.addEventCallbackForQuery(this,r)},e.prototype.off=function(e,t,n){validateArgCount("Query.off",0,3,arguments.length),validateEventType("Query.off",1,e,!0),validateCallback("Query.off",2,t,!0),validateContextObject("Query.off",3,n,!0);var r=null,i=null;"value"===e?r=new ValueEventRegistration(t||null,null,n||null):e&&(t&&((i={})[e]=t),r=new ChildEventRegistration(i,null,n||null));this.repo.removeEventCallbackForQuery(this,r)},e.prototype.once=function(t,n,r,i){var o=this;validateArgCount("Query.once",1,4,arguments.length),validateEventType("Query.once",1,t,!1),validateCallback("Query.once",2,n,!0);var a=e.getCancelAndContextArgs_("Query.once",r,i),s=!0,u=new Deferred;u.promise.catch(function(){});var c=function(e){s&&(s=!1,o.off(t,c),n&&n.bind(a.context)(e),u.resolve(e))};return this.on(t,c,function(e){o.off(t,c),a.cancel&&a.cancel.bind(a.context)(e),u.reject(e)}),u.promise},e.prototype.limitToFirst=function(t){if(validateArgCount("Query.limitToFirst",1,1,arguments.length),"number"!=typeof t||Math.floor(t)!==t||t<=0)throw new Error("Query.limitToFirst: First argument must be a positive integer.");if(this.queryParams_.hasLimit())throw new Error("Query.limitToFirst: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new e(this.repo,this.path,this.queryParams_.limitToFirst(t),this.orderByCalled_)},e.prototype.limitToLast=function(t){if(validateArgCount("Query.limitToLast",1,1,arguments.length),"number"!=typeof t||Math.floor(t)!==t||t<=0)throw new Error("Query.limitToLast: First argument must be a positive integer.");if(this.queryParams_.hasLimit())throw new Error("Query.limitToLast: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new e(this.repo,this.path,this.queryParams_.limitToLast(t),this.orderByCalled_)},e.prototype.orderByChild=function(t){if(validateArgCount("Query.orderByChild",1,1,arguments.length),"$key"===t)throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.');if("$priority"===t)throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.');if("$value"===t)throw new Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.');validatePathString("Query.orderByChild",1,t,!1),this.validateNoPreviousOrderByCall_("Query.orderByChild");var n=new Path(t);if(n.isEmpty())throw new Error("Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.");var r=new PathIndex(n),i=this.queryParams_.orderBy(r);return e.validateQueryEndpoints_(i),new e(this.repo,this.path,i,!0)},e.prototype.orderByKey=function(){validateArgCount("Query.orderByKey",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByKey");var t=this.queryParams_.orderBy(KEY_INDEX);return e.validateQueryEndpoints_(t),new e(this.repo,this.path,t,!0)},e.prototype.orderByPriority=function(){validateArgCount("Query.orderByPriority",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByPriority");var t=this.queryParams_.orderBy(PRIORITY_INDEX);return e.validateQueryEndpoints_(t),new e(this.repo,this.path,t,!0)},e.prototype.orderByValue=function(){validateArgCount("Query.orderByValue",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByValue");var t=this.queryParams_.orderBy(VALUE_INDEX);return e.validateQueryEndpoints_(t),new e(this.repo,this.path,t,!0)},e.prototype.startAt=function(t,n){void 0===t&&(t=null),validateArgCount("Query.startAt",0,2,arguments.length),validateFirebaseDataArg("Query.startAt",1,t,this.path,!0),validateKey("Query.startAt",2,n,!0);var r=this.queryParams_.startAt(t,n);if(e.validateLimit_(r),e.validateQueryEndpoints_(r),this.queryParams_.hasStart())throw new Error("Query.startAt: Starting point was already set (by another call to startAt or equalTo).");return void 0===t&&(t=null,n=null),new e(this.repo,this.path,r,this.orderByCalled_)},e.prototype.endAt=function(t,n){void 0===t&&(t=null),validateArgCount("Query.endAt",0,2,arguments.length),validateFirebaseDataArg("Query.endAt",1,t,this.path,!0),validateKey("Query.endAt",2,n,!0);var r=this.queryParams_.endAt(t,n);if(e.validateLimit_(r),e.validateQueryEndpoints_(r),this.queryParams_.hasEnd())throw new Error("Query.endAt: Ending point was already set (by another call to endAt or equalTo).");return new e(this.repo,this.path,r,this.orderByCalled_)},e.prototype.equalTo=function(e,t){if(validateArgCount("Query.equalTo",1,2,arguments.length),validateFirebaseDataArg("Query.equalTo",1,e,this.path,!1),validateKey("Query.equalTo",2,t,!0),this.queryParams_.hasStart())throw new Error("Query.equalTo: Starting point was already set (by another call to startAt or equalTo).");if(this.queryParams_.hasEnd())throw new Error("Query.equalTo: Ending point was already set (by another call to endAt or equalTo).");return this.startAt(e,t).endAt(e,t)},e.prototype.toString=function(){return validateArgCount("Query.toString",0,0,arguments.length),this.repo.toString()+this.path.toUrlEncodedString()},e.prototype.toJSON=function(){return validateArgCount("Query.toJSON",0,1,arguments.length),this.toString()},e.prototype.queryObject=function(){return this.queryParams_.getQueryObject()},e.prototype.queryIdentifier=function(){var e=this.queryObject(),t=ObjectToUniqueKey(e);return"{}"===t?"default":t},e.prototype.isEqual=function(t){if(validateArgCount("Query.isEqual",1,1,arguments.length),!(t instanceof e)){throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}var n=this.repo===t.repo,r=this.path.equals(t.path),i=this.queryIdentifier()===t.queryIdentifier();return n&&r&&i},e.getCancelAndContextArgs_=function(e,t,n){var r={cancel:null,context:null};if(t&&n)r.cancel=t,validateCallback(e,3,r.cancel,!0),r.context=n,validateContextObject(e,4,r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(errorPrefix(e,3,!0)+" must either be a cancel callback or a context object.");r.cancel=t}return r},Object.defineProperty(e.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),e}(),CountedSet=function(){function e(){this.set={}}return e.prototype.add=function(e,t){this.set[e]=null===t||t},e.prototype.contains=function(e){return contains(this.set,e)},e.prototype.get=function(e){return this.contains(e)?this.set[e]:void 0},e.prototype.remove=function(e){delete this.set[e]},e.prototype.clear=function(){this.set={}},e.prototype.isEmpty=function(){return isEmpty(this.set)},e.prototype.count=function(){return getCount(this.set)},e.prototype.each=function(e){forEach(this.set,function(t,n){return e(t,n)})},e.prototype.keys=function(){var e=[];return forEach(this.set,function(t){e.push(t)}),e},e}(),SparseSnapshotTree=function(){function e(){this.value_=null,this.children_=null}return e.prototype.find=function(e){if(null!=this.value_)return this.value_.getChild(e);if(e.isEmpty()||null==this.children_)return null;var t=e.getFront();return e=e.popFront(),this.children_.contains(t)?this.children_.get(t).find(e):null},e.prototype.remember=function(t,n){if(t.isEmpty())this.value_=n,this.children_=null;else if(null!==this.value_)this.value_=this.value_.updateChild(t,n);else{null==this.children_&&(this.children_=new CountedSet);var r=t.getFront();this.children_.contains(r)||this.children_.add(r,new e);var i=this.children_.get(r);t=t.popFront(),i.remember(t,n)}},e.prototype.forget=function(e){if(e.isEmpty())return this.value_=null,this.children_=null,!0;if(null!==this.value_){if(this.value_.isLeafNode())return!1;var t=this.value_;this.value_=null;var n=this;return t.forEachChild(PRIORITY_INDEX,function(e,t){n.remember(new Path(e),t)}),this.forget(e)}if(null!==this.children_){var r=e.getFront();if(e=e.popFront(),this.children_.contains(r))this.children_.get(r).forget(e)&&this.children_.remove(r);return!!this.children_.isEmpty()&&(this.children_=null,!0)}return!0},e.prototype.forEachTree=function(e,t){null!==this.value_?t(e,this.value_):this.forEachChild(function(n,r){var i=new Path(e.toString()+"/"+n);r.forEachTree(i,t)})},e.prototype.forEachChild=function(e){null!==this.children_&&this.children_.each(function(t,n){e(t,n)})},e}(),generateWithValues=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},resolveDeferredValue=function(e,t){return e&&"object"==typeof e?(assert(".sv"in e,"Unexpected leaf node or priority contents"),t[e[".sv"]]):e},resolveDeferredValueTree=function(e,t){var n=new SparseSnapshotTree;return e.forEachTree(new Path(""),function(e,r){n.remember(e,resolveDeferredValueSnapshot(r,t))}),n},resolveDeferredValueSnapshot=function(e,t){var n,r=e.getPriority().val(),i=resolveDeferredValue(r,t);if(e.isLeafNode()){var o=e,a=resolveDeferredValue(o.getValue(),t);return a!==o.getValue()||i!==o.getPriority().val()?new LeafNode(a,nodeFromJSON$1(i)):e}var s=e;return n=s,i!==s.getPriority().val()&&(n=n.updatePriority(new LeafNode(i))),s.forEachChild(PRIORITY_INDEX,function(e,r){var i=resolveDeferredValueSnapshot(r,t);i!==r&&(n=n.updateImmediateChild(e,i))}),n},OperationType;!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(OperationType||(OperationType={}));var OperationSource=function(){function e(e,t,n,r){this.fromUser=e,this.fromServer=t,this.queryId=n,this.tagged=r,assert(!r||t,"Tagged queries must be from server.")}return e.User=new e(!0,!1,null,!1),e.Server=new e(!1,!0,null,!1),e.forServerTaggedQuery=function(t){return new e(!1,!0,t,!0)},e}(),AckUserWrite=function(){function e(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=OperationType.ACK_USER_WRITE,this.source=OperationSource.User}return e.prototype.operationForChild=function(t){if(this.path.isEmpty()){if(null!=this.affectedTree.value)return assert(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var n=this.affectedTree.subtree(new Path(t));return new e(Path.Empty,n,this.revert)}return assert(this.path.getFront()===t,"operationForChild called for unrelated child."),new e(this.path.popFront(),this.affectedTree,this.revert)},e}(),emptyChildrenSingleton,EmptyChildren=function(){return emptyChildrenSingleton||(emptyChildrenSingleton=new SortedMap(stringCompare)),emptyChildrenSingleton},ImmutableTree=function(){function e(e,t){void 0===t&&(t=EmptyChildren()),this.value=e,this.children=t}return e.fromObject=function(t){var n=e.Empty;return forEach(t,function(e,t){n=n.set(new Path(e),t)}),n},e.prototype.isEmpty=function(){return null===this.value&&this.children.isEmpty()},e.prototype.findRootMostMatchingPathAndValue=function(e,t){if(null!=this.value&&t(this.value))return{path:Path.Empty,value:this.value};if(e.isEmpty())return null;var n=e.getFront(),r=this.children.get(n);if(null!==r){var i=r.findRootMostMatchingPathAndValue(e.popFront(),t);return null!=i?{path:new Path(n).child(i.path),value:i.value}:null}return null},e.prototype.findRootMostValueAndPath=function(e){return this.findRootMostMatchingPathAndValue(e,function(){return!0})},e.prototype.subtree=function(t){if(t.isEmpty())return this;var n=t.getFront(),r=this.children.get(n);return null!==r?r.subtree(t.popFront()):e.Empty},e.prototype.set=function(t,n){if(t.isEmpty())return new e(n,this.children);var r=t.getFront(),i=(this.children.get(r)||e.Empty).set(t.popFront(),n),o=this.children.insert(r,i);return new e(this.value,o)},e.prototype.remove=function(t){if(t.isEmpty())return this.children.isEmpty()?e.Empty:new e(null,this.children);var n=t.getFront(),r=this.children.get(n);if(r){var i=r.remove(t.popFront()),o=void 0;return o=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&o.isEmpty()?e.Empty:new e(this.value,o)}return this},e.prototype.get=function(e){if(e.isEmpty())return this.value;var t=e.getFront(),n=this.children.get(t);return n?n.get(e.popFront()):null},e.prototype.setTree=function(t,n){if(t.isEmpty())return n;var r=t.getFront(),i=(this.children.get(r)||e.Empty).setTree(t.popFront(),n),o=void 0;return o=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new e(this.value,o)},e.prototype.fold=function(e){return this.fold_(Path.Empty,e)},e.prototype.fold_=function(e,t){var n={};return this.children.inorderTraversal(function(r,i){n[r]=i.fold_(e.child(r),t)}),t(e,this.value,n)},e.prototype.findOnPath=function(e,t){return this.findOnPath_(e,Path.Empty,t)},e.prototype.findOnPath_=function(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(e.isEmpty())return null;var i=e.getFront(),o=this.children.get(i);return o?o.findOnPath_(e.popFront(),t.child(i),n):null},e.prototype.foreachOnPath=function(e,t){return this.foreachOnPath_(e,Path.Empty,t)},e.prototype.foreachOnPath_=function(t,n,r){if(t.isEmpty())return this;this.value&&r(n,this.value);var i=t.getFront(),o=this.children.get(i);return o?o.foreachOnPath_(t.popFront(),n.child(i),r):e.Empty},e.prototype.foreach=function(e){this.foreach_(Path.Empty,e)},e.prototype.foreach_=function(e,t){this.children.inorderTraversal(function(n,r){r.foreach_(e.child(n),t)}),this.value&&t(e,this.value)},e.prototype.foreachChild=function(e){this.children.inorderTraversal(function(t,n){n.value&&e(t,n.value)})},e.Empty=new e(null),e}(),ListenComplete=function(){function e(e,t){this.source=e,this.path=t,this.type=OperationType.LISTEN_COMPLETE}return e.prototype.operationForChild=function(t){return this.path.isEmpty()?new e(this.source,Path.Empty):new e(this.source,this.path.popFront())},e}(),Overwrite=function(){function e(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=OperationType.OVERWRITE}return e.prototype.operationForChild=function(t){return this.path.isEmpty()?new e(this.source,Path.Empty,this.snap.getImmediateChild(t)):new e(this.source,this.path.popFront(),this.snap)},e}(),Merge=function(){function e(e,t,n){this.source=e,this.path=t,this.children=n,this.type=OperationType.MERGE}return e.prototype.operationForChild=function(t){if(this.path.isEmpty()){var n=this.children.subtree(new Path(t));return n.isEmpty()?null:n.value?new Overwrite(this.source,Path.Empty,n.value):new e(this.source,Path.Empty,n)}return assert(this.path.getFront()===t,"Can't get a merge for a child not on the path of the operation"),new e(this.source,this.path.popFront(),this.children)},e.prototype.toString=function(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"},e}(),CacheNode=function(){function e(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}return e.prototype.isFullyInitialized=function(){return this.fullyInitialized_},e.prototype.isFiltered=function(){return this.filtered_},e.prototype.isCompleteForPath=function(e){if(e.isEmpty())return this.isFullyInitialized()&&!this.filtered_;var t=e.getFront();return this.isCompleteForChild(t)},e.prototype.isCompleteForChild=function(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)},e.prototype.getNode=function(){return this.node_},e}(),ViewCache=function(){function e(e,t){this.eventCache_=e,this.serverCache_=t}return e.prototype.updateEventSnap=function(t,n,r){return new e(new CacheNode(t,n,r),this.serverCache_)},e.prototype.updateServerSnap=function(t,n,r){return new e(this.eventCache_,new CacheNode(t,n,r))},e.prototype.getEventCache=function(){return this.eventCache_},e.prototype.getCompleteEventSnap=function(){return this.eventCache_.isFullyInitialized()?this.eventCache_.getNode():null},e.prototype.getServerCache=function(){return this.serverCache_},e.prototype.getCompleteServerSnap=function(){return this.serverCache_.isFullyInitialized()?this.serverCache_.getNode():null},e.Empty=new e(new CacheNode(ChildrenNode.EMPTY_NODE,!1,!1),new CacheNode(ChildrenNode.EMPTY_NODE,!1,!1)),e}(),Change=function(){function e(e,t,n,r,i){this.type=e,this.snapshotNode=t,this.childName=n,this.oldSnap=r,this.prevName=i}return e.valueChange=function(t){return new e(e.VALUE,t)},e.childAddedChange=function(t,n){return new e(e.CHILD_ADDED,n,t)},e.childRemovedChange=function(t,n){return new e(e.CHILD_REMOVED,n,t)},e.childChangedChange=function(t,n,r){return new e(e.CHILD_CHANGED,n,t,r)},e.childMovedChange=function(t,n){return new e(e.CHILD_MOVED,n,t)},e.CHILD_ADDED="child_added",e.CHILD_REMOVED="child_removed",e.CHILD_CHANGED="child_changed",e.CHILD_MOVED="child_moved",e.VALUE="value",e}(),IndexedFilter=function(){function e(e){this.index_=e}return e.prototype.updateChild=function(e,t,n,r,i,o){assert(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");var a=e.getImmediateChild(t);return a.getChild(r).equals(n.getChild(r))&&a.isEmpty()==n.isEmpty()?e:(null!=o&&(n.isEmpty()?e.hasChild(t)?o.trackChildChange(Change.childRemovedChange(t,a)):assert(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(Change.childAddedChange(t,n)):o.trackChildChange(Change.childChangedChange(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))},e.prototype.updateFullNode=function(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(PRIORITY_INDEX,function(e,r){t.hasChild(e)||n.trackChildChange(Change.childRemovedChange(e,r))}),t.isLeafNode()||t.forEachChild(PRIORITY_INDEX,function(t,r){if(e.hasChild(t)){var i=e.getImmediateChild(t);i.equals(r)||n.trackChildChange(Change.childChangedChange(t,r,i))}else n.trackChildChange(Change.childAddedChange(t,r))})),t.withIndex(this.index_)},e.prototype.updatePriority=function(e,t){return e.isEmpty()?ChildrenNode.EMPTY_NODE:e.updatePriority(t)},e.prototype.filtersNodes=function(){return!1},e.prototype.getIndexedFilter=function(){return this},e.prototype.getIndex=function(){return this.index_},e}(),ChildChangeAccumulator=function(){function e(){this.changeMap_={}}return e.prototype.trackChildChange=function(e){var t=e.type,n=e.childName;assert(t==Change.CHILD_ADDED||t==Change.CHILD_CHANGED||t==Change.CHILD_REMOVED,"Only child changes supported for tracking"),assert(".priority"!==n,"Only non-priority child changes can be tracked.");var r=safeGet(this.changeMap_,n);if(r){var i=r.type;if(t==Change.CHILD_ADDED&&i==Change.CHILD_REMOVED)this.changeMap_[n]=Change.childChangedChange(n,e.snapshotNode,r.snapshotNode);else if(t==Change.CHILD_REMOVED&&i==Change.CHILD_ADDED)delete this.changeMap_[n];else if(t==Change.CHILD_REMOVED&&i==Change.CHILD_CHANGED)this.changeMap_[n]=Change.childRemovedChange(n,r.oldSnap);else if(t==Change.CHILD_CHANGED&&i==Change.CHILD_ADDED)this.changeMap_[n]=Change.childAddedChange(n,e.snapshotNode);else{if(t!=Change.CHILD_CHANGED||i!=Change.CHILD_CHANGED)throw assertionError("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap_[n]=Change.childChangedChange(n,e.snapshotNode,r.oldSnap)}}else this.changeMap_[n]=e},e.prototype.getChanges=function(){return getValues(this.changeMap_)},e}(),NoCompleteChildSource_=function(){function e(){}return e.prototype.getCompleteChild=function(e){return null},e.prototype.getChildAfterChild=function(e,t,n){return null},e}(),NO_COMPLETE_CHILD_SOURCE=new NoCompleteChildSource_,WriteTreeCompleteChildSource=function(){function e(e,t,n){void 0===n&&(n=null),this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}return e.prototype.getCompleteChild=function(e){var t=this.viewCache_.getEventCache();if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new CacheNode(this.optCompleteServerCache_,!0,!1):this.viewCache_.getServerCache();return this.writes_.calcCompleteChild(e,n)},e.prototype.getChildAfterChild=function(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:this.viewCache_.getCompleteServerSnap(),i=this.writes_.calcIndexedSlice(r,t,1,n,e);return 0===i.length?null:i[0]},e}(),ProcessorResult=function(){return function(e,t){this.viewCache=e,this.changes=t}}(),ViewProcessor=function(){function e(e){this.filter_=e}return e.prototype.assertIndexed=function(e){assert(e.getEventCache().getNode().isIndexed(this.filter_.getIndex()),"Event snap not indexed"),assert(e.getServerCache().getNode().isIndexed(this.filter_.getIndex()),"Server snap not indexed")},e.prototype.applyOperation=function(t,n,r,i){var o,a,s=new ChildChangeAccumulator;if(n.type===OperationType.OVERWRITE){var u=n;u.source.fromUser?o=this.applyUserOverwrite_(t,u.path,u.snap,r,i,s):(assert(u.source.fromServer,"Unknown source."),a=u.source.tagged||t.getServerCache().isFiltered()&&!u.path.isEmpty(),o=this.applyServerOverwrite_(t,u.path,u.snap,r,i,a,s))}else if(n.type===OperationType.MERGE){var c=n;c.source.fromUser?o=this.applyUserMerge_(t,c.path,c.children,r,i,s):(assert(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.getServerCache().isFiltered(),o=this.applyServerMerge_(t,c.path,c.children,r,i,a,s))}else if(n.type===OperationType.ACK_USER_WRITE){var h=n;o=h.revert?this.revertUserWrite_(t,h.path,r,i,s):this.ackUserWrite_(t,h.path,h.affectedTree,r,i,s)}else{if(n.type!==OperationType.LISTEN_COMPLETE)throw assertionError("Unknown operation type: "+n.type);o=this.listenComplete_(t,n.path,r,s)}var l=s.getChanges();return e.maybeAddValueEvent_(t,o,l),new ProcessorResult(o,l)},e.maybeAddValueEvent_=function(e,t,n){var r=t.getEventCache();if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty(),o=e.getCompleteEventSnap();(n.length>0||!e.getEventCache().isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(Change.valueChange(t.getCompleteEventSnap()))}},e.prototype.generateEventCacheAfterServerEvent_=function(e,t,n,r,i){var o=e.getEventCache();if(null!=n.shadowingWrite(t))return e;var a=void 0,s=void 0;if(t.isEmpty())if(assert(e.getServerCache().isFullyInitialized(),"If change path is empty, we must have complete server data"),e.getServerCache().isFiltered()){var u=e.getCompleteServerSnap(),c=u instanceof ChildrenNode?u:ChildrenNode.EMPTY_NODE,h=n.calcCompleteEventChildren(c);a=this.filter_.updateFullNode(e.getEventCache().getNode(),h,i)}else{var l=n.calcCompleteEventCache(e.getCompleteServerSnap());a=this.filter_.updateFullNode(e.getEventCache().getNode(),l,i)}else{var d=t.getFront();if(".priority"==d){assert(1==t.getLength(),"Can't have a priority with additional path components");var f=o.getNode();s=e.getServerCache().getNode();var p=n.calcEventCacheAfterServerOverwrite(t,f,s);a=null!=p?this.filter_.updatePriority(f,p):o.getNode()}else{var m=t.popFront(),y=void 0;if(o.isCompleteForChild(d)){s=e.getServerCache().getNode();var g=n.calcEventCacheAfterServerOverwrite(t,o.getNode(),s);y=null!=g?o.getNode().getImmediateChild(d).updateChild(m,g):o.getNode().getImmediateChild(d)}else y=n.calcCompleteChild(d,e.getServerCache());a=null!=y?this.filter_.updateChild(o.getNode(),d,y,m,r,i):o.getNode()}}return e.updateEventSnap(a,o.isFullyInitialized()||t.isEmpty(),this.filter_.filtersNodes())},e.prototype.applyServerOverwrite_=function(e,t,n,r,i,o,a){var s,u=e.getServerCache(),c=o?this.filter_:this.filter_.getIndexedFilter();if(t.isEmpty())s=c.updateFullNode(u.getNode(),n,null);else if(c.filtersNodes()&&!u.isFiltered()){var h=u.getNode().updateChild(t,n);s=c.updateFullNode(u.getNode(),h,null)}else{var l=t.getFront();if(!u.isCompleteForPath(t)&&t.getLength()>1)return e;var d=t.popFront(),f=u.getNode().getImmediateChild(l).updateChild(d,n);s=".priority"==l?c.updatePriority(u.getNode(),f):c.updateChild(u.getNode(),l,f,d,NO_COMPLETE_CHILD_SOURCE,null)}var p=e.updateServerSnap(s,u.isFullyInitialized()||t.isEmpty(),c.filtersNodes()),m=new WriteTreeCompleteChildSource(r,p,i);return this.generateEventCacheAfterServerEvent_(p,t,r,m,a)},e.prototype.applyUserOverwrite_=function(e,t,n,r,i,o){var a,s,u=e.getEventCache(),c=new WriteTreeCompleteChildSource(r,e,i);if(t.isEmpty())s=this.filter_.updateFullNode(e.getEventCache().getNode(),n,o),a=e.updateEventSnap(s,!0,this.filter_.filtersNodes());else{var h=t.getFront();if(".priority"===h)s=this.filter_.updatePriority(e.getEventCache().getNode(),n),a=e.updateEventSnap(s,u.isFullyInitialized(),u.isFiltered());else{var l=t.popFront(),d=u.getNode().getImmediateChild(h),f=void 0;if(l.isEmpty())f=n;else{var p=c.getCompleteChild(h);f=null!=p?".priority"===l.getBack()&&p.getChild(l.parent()).isEmpty()?p:p.updateChild(l,n):ChildrenNode.EMPTY_NODE}if(d.equals(f))a=e;else{var m=this.filter_.updateChild(u.getNode(),h,f,l,c,o);a=e.updateEventSnap(m,u.isFullyInitialized(),this.filter_.filtersNodes())}}}return a},e.cacheHasChild_=function(e,t){return e.getEventCache().isCompleteForChild(t)},e.prototype.applyUserMerge_=function(t,n,r,i,o,a){var s=this,u=t;return r.foreach(function(r,c){var h=n.child(r);e.cacheHasChild_(t,h.getFront())&&(u=s.applyUserOverwrite_(u,h,c,i,o,a))}),r.foreach(function(r,c){var h=n.child(r);e.cacheHasChild_(t,h.getFront())||(u=s.applyUserOverwrite_(u,h,c,i,o,a))}),u},e.prototype.applyMerge_=function(e,t){return t.foreach(function(t,n){e=e.updateChild(t,n)}),e},e.prototype.applyServerMerge_=function(e,t,n,r,i,o,a){var s=this;if(e.getServerCache().getNode().isEmpty()&&!e.getServerCache().isFullyInitialized())return e;var u,c=e;u=t.isEmpty()?n:ImmutableTree.Empty.setTree(t,n);var h=e.getServerCache().getNode();return u.children.inorderTraversal(function(t,n){if(h.hasChild(t)){var u=e.getServerCache().getNode().getImmediateChild(t),l=s.applyMerge_(u,n);c=s.applyServerOverwrite_(c,new Path(t),l,r,i,o,a)}}),u.children.inorderTraversal(function(t,n){var u=!e.getServerCache().isCompleteForChild(t)&&null==n.value;if(!h.hasChild(t)&&!u){var l=e.getServerCache().getNode().getImmediateChild(t),d=s.applyMerge_(l,n);c=s.applyServerOverwrite_(c,new Path(t),d,r,i,o,a)}}),c},e.prototype.ackUserWrite_=function(e,t,n,r,i,o){if(null!=r.shadowingWrite(t))return e;var a=e.getServerCache().isFiltered(),s=e.getServerCache();if(null!=n.value){if(t.isEmpty()&&s.isFullyInitialized()||s.isCompleteForPath(t))return this.applyServerOverwrite_(e,t,s.getNode().getChild(t),r,i,a,o);if(t.isEmpty()){var u=ImmutableTree.Empty;return s.getNode().forEachChild(KEY_INDEX,function(e,t){u=u.set(new Path(e),t)}),this.applyServerMerge_(e,t,u,r,i,a,o)}return e}var c=ImmutableTree.Empty;return n.foreach(function(e,n){var r=t.child(e);s.isCompleteForPath(r)&&(c=c.set(e,s.getNode().getChild(r)))}),this.applyServerMerge_(e,t,c,r,i,a,o)},e.prototype.listenComplete_=function(e,t,n,r){var i=e.getServerCache(),o=e.updateServerSnap(i.getNode(),i.isFullyInitialized()||t.isEmpty(),i.isFiltered());return this.generateEventCacheAfterServerEvent_(o,t,n,NO_COMPLETE_CHILD_SOURCE,r)},e.prototype.revertUserWrite_=function(e,t,n,r,i){var o;if(null!=n.shadowingWrite(t))return e;var a=new WriteTreeCompleteChildSource(n,e,r),s=e.getEventCache().getNode(),u=void 0;if(t.isEmpty()||".priority"===t.getFront()){var c=void 0;if(e.getServerCache().isFullyInitialized())c=n.calcCompleteEventCache(e.getCompleteServerSnap());else{var h=e.getServerCache().getNode();assert(h instanceof ChildrenNode,"serverChildren would be complete if leaf node"),c=n.calcCompleteEventChildren(h)}c=c,u=this.filter_.updateFullNode(s,c,i)}else{var l=t.getFront(),d=n.calcCompleteChild(l,e.getServerCache());null==d&&e.getServerCache().isCompleteForChild(l)&&(d=s.getImmediateChild(l)),(u=null!=d?this.filter_.updateChild(s,l,d,t.popFront(),a,i):e.getEventCache().getNode().hasChild(l)?this.filter_.updateChild(s,l,ChildrenNode.EMPTY_NODE,t.popFront(),a,i):s).isEmpty()&&e.getServerCache().isFullyInitialized()&&(o=n.calcCompleteEventCache(e.getCompleteServerSnap())).isLeafNode()&&(u=this.filter_.updateFullNode(u,o,i))}return o=e.getServerCache().isFullyInitialized()||null!=n.shadowingWrite(Path.Empty),e.updateEventSnap(u,o,this.filter_.filtersNodes())},e}(),EventGenerator=function(){function e(e){this.query_=e,this.index_=this.query_.getQueryParams().getIndex()}return e.prototype.generateEventsForChanges=function(e,t,n){var r=this,i=[],o=[];return e.forEach(function(e){e.type===Change.CHILD_CHANGED&&r.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&o.push(Change.childMovedChange(e.childName,e.snapshotNode))}),this.generateEventsForType_(i,Change.CHILD_REMOVED,e,n,t),this.generateEventsForType_(i,Change.CHILD_ADDED,e,n,t),this.generateEventsForType_(i,Change.CHILD_MOVED,o,n,t),this.generateEventsForType_(i,Change.CHILD_CHANGED,e,n,t),this.generateEventsForType_(i,Change.VALUE,e,n,t),i},e.prototype.generateEventsForType_=function(e,t,n,r,i){var o=this,a=n.filter(function(e){return e.type===t});a.sort(this.compareChanges_.bind(this)),a.forEach(function(t){var n=o.materializeSingleChange_(t,i);r.forEach(function(r){r.respondsTo(t.type)&&e.push(r.createEvent(n,o.query_))})})},e.prototype.materializeSingleChange_=function(e,t){return"value"===e.type||"child_removed"===e.type?e:(e.prevName=t.getPredecessorChildName(e.childName,e.snapshotNode,this.index_),e)},e.prototype.compareChanges_=function(e,t){if(null==e.childName||null==t.childName)throw assertionError("Should only compare child_ events.");var n=new NamedNode(e.childName,e.snapshotNode),r=new NamedNode(t.childName,t.snapshotNode);return this.index_.compare(n,r)},e}(),View=function(){function e(e,t){this.query_=e,this.eventRegistrations_=[];var n=this.query_.getQueryParams(),r=new IndexedFilter(n.getIndex()),i=n.getNodeFilter();this.processor_=new ViewProcessor(i);var o=t.getServerCache(),a=t.getEventCache(),s=r.updateFullNode(ChildrenNode.EMPTY_NODE,o.getNode(),null),u=i.updateFullNode(ChildrenNode.EMPTY_NODE,a.getNode(),null),c=new CacheNode(s,o.isFullyInitialized(),r.filtersNodes()),h=new CacheNode(u,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=new ViewCache(h,c),this.eventGenerator_=new EventGenerator(this.query_)}return e.prototype.getQuery=function(){return this.query_},e.prototype.getServerCache=function(){return this.viewCache_.getServerCache().getNode()},e.prototype.getCompleteServerCache=function(e){var t=this.viewCache_.getCompleteServerSnap();return t&&(this.query_.getQueryParams().loadsAllData()||!e.isEmpty()&&!t.getImmediateChild(e.getFront()).isEmpty())?t.getChild(e):null},e.prototype.isEmpty=function(){return 0===this.eventRegistrations_.length},e.prototype.addEventRegistration=function(e){this.eventRegistrations_.push(e)},e.prototype.removeEventRegistration=function(e,t){var n=[];if(t){assert(null==e,"A cancel should cancel all event registrations.");var r=this.query_.path;this.eventRegistrations_.forEach(function(e){t=t;var i=e.createCancelEvent(t,r);i&&n.push(i)})}if(e){for(var i=[],o=0;o<this.eventRegistrations_.length;++o){var a=this.eventRegistrations_[o];if(a.matches(e)){if(e.hasAnyCallback()){i=i.concat(this.eventRegistrations_.slice(o+1));break}}else i.push(a)}this.eventRegistrations_=i}else this.eventRegistrations_=[];return n},e.prototype.applyOperation=function(e,t,n){e.type===OperationType.MERGE&&null!==e.source.queryId&&(assert(this.viewCache_.getCompleteServerSnap(),"We should always have a full cache before handling merges"),assert(this.viewCache_.getCompleteEventSnap(),"Missing event cache, even though we have a server cache"));var r=this.viewCache_,i=this.processor_.applyOperation(r,e,t,n);return this.processor_.assertIndexed(i.viewCache),assert(i.viewCache.getServerCache().isFullyInitialized()||!r.getServerCache().isFullyInitialized(),"Once a server snap is complete, it should never go back"),this.viewCache_=i.viewCache,this.generateEventsForChanges_(i.changes,i.viewCache.getEventCache().getNode(),null)},e.prototype.getInitialEvents=function(e){var t=this.viewCache_.getEventCache(),n=[];t.getNode().isLeafNode()||t.getNode().forEachChild(PRIORITY_INDEX,function(e,t){n.push(Change.childAddedChange(e,t))});return t.isFullyInitialized()&&n.push(Change.valueChange(t.getNode())),this.generateEventsForChanges_(n,t.getNode(),e)},e.prototype.generateEventsForChanges_=function(e,t,n){var r=n?[n]:this.eventRegistrations_;return this.eventGenerator_.generateEventsForChanges(e,t,r)},e}(),__referenceConstructor$1,SyncPoint=function(){function e(){this.views_={}}return Object.defineProperty(e,"__referenceConstructor",{get:function(){return assert(__referenceConstructor$1,"Reference.ts has not been loaded"),__referenceConstructor$1},set:function(e){assert(!__referenceConstructor$1,"__referenceConstructor has already been defined"),__referenceConstructor$1=e},enumerable:!0,configurable:!0}),e.prototype.isEmpty=function(){return isEmpty(this.views_)},e.prototype.applyOperation=function(e,t,n){var r=e.source.queryId;if(null!==r){var i=safeGet(this.views_,r);return assert(null!=i,"SyncTree gave us an op for an invalid query."),i.applyOperation(e,t,n)}var o=[];return forEach(this.views_,function(r,i){o=o.concat(i.applyOperation(e,t,n))}),o},e.prototype.addEventRegistration=function(e,t,n,r,i){var o=e.queryIdentifier(),a=safeGet(this.views_,o);if(!a){var s=n.calcCompleteEventCache(i?r:null),u=!1;s?u=!0:r instanceof ChildrenNode?(s=n.calcCompleteEventChildren(r),u=!1):(s=ChildrenNode.EMPTY_NODE,u=!1);var c=new ViewCache(new CacheNode(s,u,!1),new CacheNode(r,i,!1));a=new View(e,c),this.views_[o]=a}return a.addEventRegistration(t),a.getInitialEvents(t)},e.prototype.removeEventRegistration=function(t,n,r){var i=t.queryIdentifier(),o=[],a=[],s=this.hasCompleteView();if("default"===i){var u=this;forEach(this.views_,function(e,t){a=a.concat(t.removeEventRegistration(n,r)),t.isEmpty()&&(delete u.views_[e],t.getQuery().getQueryParams().loadsAllData()||o.push(t.getQuery()))})}else{var c=safeGet(this.views_,i);c&&(a=a.concat(c.removeEventRegistration(n,r)),c.isEmpty()&&(delete this.views_[i],c.getQuery().getQueryParams().loadsAllData()||o.push(c.getQuery())))}return s&&!this.hasCompleteView()&&o.push(new e.__referenceConstructor(t.repo,t.path)),{removed:o,events:a}},e.prototype.getQueryViews=function(){var e=this;return Object.keys(this.views_).map(function(t){return e.views_[t]}).filter(function(e){return!e.getQuery().getQueryParams().loadsAllData()})},e.prototype.getCompleteServerCache=function(e){var t=null;return forEach(this.views_,function(n,r){t=t||r.getCompleteServerCache(e)}),t},e.prototype.viewForQuery=function(e){if(e.getQueryParams().loadsAllData())return this.getCompleteView();var t=e.queryIdentifier();return safeGet(this.views_,t)},e.prototype.viewExistsForQuery=function(e){return null!=this.viewForQuery(e)},e.prototype.hasCompleteView=function(){return null!=this.getCompleteView()},e.prototype.getCompleteView=function(){return findValue(this.views_,function(e){return e.getQuery().getQueryParams().loadsAllData()})||null},e}(),CompoundWrite=function(){function e(e){this.writeTree_=e}return e.prototype.addWrite=function(t,n){if(t.isEmpty())return new e(new ImmutableTree(n));var r=this.writeTree_.findRootMostValueAndPath(t);if(null!=r){var i=r.path,o=r.value,a=Path.relativePath(i,t);return o=o.updateChild(a,n),new e(this.writeTree_.set(i,o))}var s=new ImmutableTree(n);return new e(this.writeTree_.setTree(t,s))},e.prototype.addWrites=function(e,t){var n=this;return forEach(t,function(t,r){n=n.addWrite(e.child(t),r)}),n},e.prototype.removeWrite=function(t){return t.isEmpty()?e.Empty:new e(this.writeTree_.setTree(t,ImmutableTree.Empty))},e.prototype.hasCompleteWrite=function(e){return null!=this.getCompleteNode(e)},e.prototype.getCompleteNode=function(e){var t=this.writeTree_.findRootMostValueAndPath(e);return null!=t?this.writeTree_.get(t.path).getChild(Path.relativePath(t.path,e)):null},e.prototype.getCompleteChildren=function(){var e=[],t=this.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(PRIORITY_INDEX,function(t,n){e.push(new NamedNode(t,n))}):this.writeTree_.children.inorderTraversal(function(t,n){null!=n.value&&e.push(new NamedNode(t,n.value))}),e},e.prototype.childCompoundWrite=function(t){if(t.isEmpty())return this;var n=this.getCompleteNode(t);return new e(null!=n?new ImmutableTree(n):this.writeTree_.subtree(t))},e.prototype.isEmpty=function(){return this.writeTree_.isEmpty()},e.prototype.apply=function(t){return e.applySubtreeWrite_(Path.Empty,this.writeTree_,t)},e.Empty=new e(new ImmutableTree(null)),e.applySubtreeWrite_=function(t,n,r){if(null!=n.value)return r.updateChild(t,n.value);var i=null;return n.children.inorderTraversal(function(n,o){".priority"===n?(assert(null!==o.value,"Priority writes must always be leaf nodes"),i=o.value):r=e.applySubtreeWrite_(t.child(n),o,r)}),r.getChild(t).isEmpty()||null===i||(r=r.updateChild(t.child(".priority"),i)),r},e}(),WriteTree=function(){function e(){this.visibleWrites_=CompoundWrite.Empty,this.allWrites_=[],this.lastWriteId_=-1}return e.prototype.childWrites=function(e){return new WriteTreeRef(e,this)},e.prototype.addOverwrite=function(e,t,n,r){assert(n>this.lastWriteId_,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),this.allWrites_.push({path:e,snap:t,writeId:n,visible:r}),r&&(this.visibleWrites_=this.visibleWrites_.addWrite(e,t)),this.lastWriteId_=n},e.prototype.addMerge=function(e,t,n){assert(n>this.lastWriteId_,"Stacking an older merge on top of newer ones"),this.allWrites_.push({path:e,children:t,writeId:n,visible:!0}),this.visibleWrites_=this.visibleWrites_.addWrites(e,t),this.lastWriteId_=n},e.prototype.getWrite=function(e){for(var t=0;t<this.allWrites_.length;t++){var n=this.allWrites_[t];if(n.writeId===e)return n}return null},e.prototype.removeWrite=function(e){var t=this,n=this.allWrites_.findIndex(function(t){return t.writeId===e});assert(n>=0,"removeWrite called with nonexistent writeId.");var r=this.allWrites_[n];this.allWrites_.splice(n,1);for(var i=r.visible,o=!1,a=this.allWrites_.length-1;i&&a>=0;){var s=this.allWrites_[a];s.visible&&(a>=n&&this.recordContainsPath_(s,r.path)?i=!1:r.path.contains(s.path)&&(o=!0)),a--}if(i){if(o)return this.resetTree_(),!0;if(r.snap)this.visibleWrites_=this.visibleWrites_.removeWrite(r.path);else{var u=r.children;forEach(u,function(e){t.visibleWrites_=t.visibleWrites_.removeWrite(r.path.child(e))})}return!0}return!1},e.prototype.getCompleteWriteData=function(e){return this.visibleWrites_.getCompleteNode(e)},e.prototype.calcCompleteEventCache=function(t,n,r,i){if(r||i){var o=this.visibleWrites_.childCompoundWrite(t);if(!i&&o.isEmpty())return n;if(i||null!=n||o.hasCompleteWrite(Path.Empty)){var a=e.layerTree_(this.allWrites_,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(e.path.contains(t)||t.contains(e.path))},t);c=n||ChildrenNode.EMPTY_NODE;return a.apply(c)}return null}var s=this.visibleWrites_.getCompleteNode(t);if(null!=s)return s;var u=this.visibleWrites_.childCompoundWrite(t);if(u.isEmpty())return n;if(null!=n||u.hasCompleteWrite(Path.Empty)){var c=n||ChildrenNode.EMPTY_NODE;return u.apply(c)}return null},e.prototype.calcCompleteEventChildren=function(e,t){var n=ChildrenNode.EMPTY_NODE,r=this.visibleWrites_.getCompleteNode(e);if(r)return r.isLeafNode()||r.forEachChild(PRIORITY_INDEX,function(e,t){n=n.updateImmediateChild(e,t)}),n;if(t){var i=this.visibleWrites_.childCompoundWrite(e);return t.forEachChild(PRIORITY_INDEX,function(e,t){var r=i.childCompoundWrite(new Path(e)).apply(t);n=n.updateImmediateChild(e,r)}),i.getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n}return this.visibleWrites_.childCompoundWrite(e).getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n},e.prototype.calcEventCacheAfterServerOverwrite=function(e,t,n,r){assert(n||r,"Either existingEventSnap or existingServerSnap must exist");var i=e.child(t);if(this.visibleWrites_.hasCompleteWrite(i))return null;var o=this.visibleWrites_.childCompoundWrite(i);return o.isEmpty()?r.getChild(t):o.apply(r.getChild(t))},e.prototype.calcCompleteChild=function(e,t,n){var r=e.child(t),i=this.visibleWrites_.getCompleteNode(r);return null!=i?i:n.isCompleteForChild(t)?this.visibleWrites_.childCompoundWrite(r).apply(n.getNode().getImmediateChild(t)):null},e.prototype.shadowingWrite=function(e){return this.visibleWrites_.getCompleteNode(e)},e.prototype.calcIndexedSlice=function(e,t,n,r,i,o){var a,s=this.visibleWrites_.childCompoundWrite(e),u=s.getCompleteNode(Path.Empty);if(null!=u)a=u;else{if(null==t)return[];a=s.apply(t)}if((a=a.withIndex(o)).isEmpty()||a.isLeafNode())return[];for(var c=[],h=o.getCompare(),l=i?a.getReverseIteratorFrom(n,o):a.getIteratorFrom(n,o),d=l.getNext();d&&c.length<r;)0!==h(d,n)&&c.push(d),d=l.getNext();return c},e.prototype.recordContainsPath_=function(e,t){return e.snap?e.path.contains(t):!!findKey(e.children,function(n,r){return e.path.child(r).contains(t)})},e.prototype.resetTree_=function(){this.visibleWrites_=e.layerTree_(this.allWrites_,e.DefaultFilter_,Path.Empty),this.allWrites_.length>0?this.lastWriteId_=this.allWrites_[this.allWrites_.length-1].writeId:this.lastWriteId_=-1},e.DefaultFilter_=function(e){return e.visible},e.layerTree_=function(e,t,n){for(var r=CompoundWrite.Empty,i=0;i<e.length;++i){var o=e[i];if(t(o)){var a=o.path,s=void 0;if(o.snap)n.contains(a)?(s=Path.relativePath(n,a),r=r.addWrite(s,o.snap)):a.contains(n)&&(s=Path.relativePath(a,n),r=r.addWrite(Path.Empty,o.snap.getChild(s)));else{if(!o.children)throw assertionError("WriteRecord should have .snap or .children");if(n.contains(a))s=Path.relativePath(n,a),r=r.addWrites(s,o.children);else if(a.contains(n))if((s=Path.relativePath(a,n)).isEmpty())r=r.addWrites(Path.Empty,o.children);else{var u=safeGet(o.children,s.getFront());if(u){var c=u.getChild(s.popFront());r=r.addWrite(Path.Empty,c)}}}}}return r},e}(),WriteTreeRef=function(){function e(e,t){this.treePath_=e,this.writeTree_=t}return e.prototype.calcCompleteEventCache=function(e,t,n){return this.writeTree_.calcCompleteEventCache(this.treePath_,e,t,n)},e.prototype.calcCompleteEventChildren=function(e){return this.writeTree_.calcCompleteEventChildren(this.treePath_,e)},e.prototype.calcEventCacheAfterServerOverwrite=function(e,t,n){return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_,e,t,n)},e.prototype.shadowingWrite=function(e){return this.writeTree_.shadowingWrite(this.treePath_.child(e))},e.prototype.calcIndexedSlice=function(e,t,n,r,i){return this.writeTree_.calcIndexedSlice(this.treePath_,e,t,n,r,i)},e.prototype.calcCompleteChild=function(e,t){return this.writeTree_.calcCompleteChild(this.treePath_,e,t)},e.prototype.child=function(t){return new e(this.treePath_.child(t),this.writeTree_)},e}(),SyncTree=function(){function e(e){this.listenProvider_=e,this.syncPointTree_=ImmutableTree.Empty,this.pendingWriteTree_=new WriteTree,this.tagToQueryMap_={},this.queryToTagMap_={}}return e.prototype.applyUserOverwrite=function(e,t,n,r){return this.pendingWriteTree_.addOverwrite(e,t,n,r),r?this.applyOperationToSyncPoints_(new Overwrite(OperationSource.User,e,t)):[]},e.prototype.applyUserMerge=function(e,t,n){this.pendingWriteTree_.addMerge(e,t,n);var r=ImmutableTree.fromObject(t);return this.applyOperationToSyncPoints_(new Merge(OperationSource.User,e,r))},e.prototype.ackUserWrite=function(e,t){void 0===t&&(t=!1);var n=this.pendingWriteTree_.getWrite(e);if(this.pendingWriteTree_.removeWrite(e)){var r=ImmutableTree.Empty;return null!=n.snap?r=r.set(Path.Empty,!0):forEach(n.children,function(e,t){r=r.set(new Path(e),t)}),this.applyOperationToSyncPoints_(new AckUserWrite(n.path,r,t))}return[]},e.prototype.applyServerOverwrite=function(e,t){return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.Server,e,t))},e.prototype.applyServerMerge=function(e,t){var n=ImmutableTree.fromObject(t);return this.applyOperationToSyncPoints_(new Merge(OperationSource.Server,e,n))},e.prototype.applyListenComplete=function(e){return this.applyOperationToSyncPoints_(new ListenComplete(OperationSource.Server,e))},e.prototype.applyTaggedQueryOverwrite=function(t,n,r){var i=this.queryKeyForTag_(r);if(null!=i){var o=e.parseQueryKey_(i),a=o.path,s=o.queryId,u=Path.relativePath(a,t),c=new Overwrite(OperationSource.forServerTaggedQuery(s),u,n);return this.applyTaggedOperation_(a,c)}return[]},e.prototype.applyTaggedQueryMerge=function(t,n,r){var i=this.queryKeyForTag_(r);if(i){var o=e.parseQueryKey_(i),a=o.path,s=o.queryId,u=Path.relativePath(a,t),c=ImmutableTree.fromObject(n),h=new Merge(OperationSource.forServerTaggedQuery(s),u,c);return this.applyTaggedOperation_(a,h)}return[]},e.prototype.applyTaggedListenComplete=function(t,n){var r=this.queryKeyForTag_(n);if(r){var i=e.parseQueryKey_(r),o=i.path,a=i.queryId,s=Path.relativePath(o,t),u=new ListenComplete(OperationSource.forServerTaggedQuery(a),s);return this.applyTaggedOperation_(o,u)}return[]},e.prototype.addEventRegistration=function(t,n){var r=t.path,i=null,o=!1;this.syncPointTree_.foreachOnPath(r,function(e,t){var n=Path.relativePath(e,r);i=i||t.getCompleteServerCache(n),o=o||t.hasCompleteView()});var a,s=this.syncPointTree_.get(r);(s?(o=o||s.hasCompleteView(),i=i||s.getCompleteServerCache(Path.Empty)):(s=new SyncPoint,this.syncPointTree_=this.syncPointTree_.set(r,s)),null!=i)?a=!0:(a=!1,i=ChildrenNode.EMPTY_NODE,this.syncPointTree_.subtree(r).foreachChild(function(e,t){var n=t.getCompleteServerCache(Path.Empty);n&&(i=i.updateImmediateChild(e,n))}));var u=s.viewExistsForQuery(t);if(!u&&!t.getQueryParams().loadsAllData()){var c=e.makeQueryKey_(t);assert(!(c in this.queryToTagMap_),"View does not exist, but we have a tag");var h=e.getNextQueryTag_();this.queryToTagMap_[c]=h,this.tagToQueryMap_["_"+h]=c}var l=this.pendingWriteTree_.childWrites(r),d=s.addEventRegistration(t,n,l,i,a);if(!u&&!o){var f=s.viewForQuery(t);d=d.concat(this.setupListener_(t,f))}return d},e.prototype.removeEventRegistration=function(t,n,r){var i=this,o=t.path,a=this.syncPointTree_.get(o),s=[];if(a&&("default"===t.queryIdentifier()||a.viewExistsForQuery(t))){var u=a.removeEventRegistration(t,n,r);a.isEmpty()&&(this.syncPointTree_=this.syncPointTree_.remove(o));var c=u.removed;s=u.events;var h=-1!==c.findIndex(function(e){return e.getQueryParams().loadsAllData()}),l=this.syncPointTree_.findOnPath(o,function(e,t){return t.hasCompleteView()});if(h&&!l){var d=this.syncPointTree_.subtree(o);if(!d.isEmpty())for(var f=this.collectDistinctViewsForSubTree_(d),p=0;p<f.length;++p){var m=f[p],y=m.getQuery(),g=this.createListenerForView_(m);this.listenProvider_.startListening(e.queryForListening_(y),this.tagForQuery_(y),g.hashFn,g.onComplete)}}if(!l&&c.length>0&&!r)if(h){this.listenProvider_.stopListening(e.queryForListening_(t),null)}else c.forEach(function(t){var n=i.queryToTagMap_[e.makeQueryKey_(t)];i.listenProvider_.stopListening(e.queryForListening_(t),n)});this.removeTags_(c)}return s},e.prototype.calcCompleteEventCache=function(e,t){var n=this.pendingWriteTree_,r=this.syncPointTree_.findOnPath(e,function(t,n){var r=Path.relativePath(t,e),i=n.getCompleteServerCache(r);if(i)return i});return n.calcCompleteEventCache(e,r,t,!0)},e.prototype.collectDistinctViewsForSubTree_=function(e){return e.fold(function(e,t,n){if(t&&t.hasCompleteView())return[t.getCompleteView()];var r=[];return t&&(r=t.getQueryViews()),forEach(n,function(e,t){r=r.concat(t)}),r})},e.prototype.removeTags_=function(t){for(var n=0;n<t.length;++n){var r=t[n];if(!r.getQueryParams().loadsAllData()){var i=e.makeQueryKey_(r),o=this.queryToTagMap_[i];delete this.queryToTagMap_[i],delete this.tagToQueryMap_["_"+o]}}},e.queryForListening_=function(e){return e.getQueryParams().loadsAllData()&&!e.getQueryParams().isDefault()?e.getRef():e},e.prototype.setupListener_=function(t,n){var r=t.path,i=this.tagForQuery_(t),o=this.createListenerForView_(n),a=this.listenProvider_.startListening(e.queryForListening_(t),i,o.hashFn,o.onComplete),s=this.syncPointTree_.subtree(r);if(i)assert(!s.value.hasCompleteView(),"If we're adding a query, it shouldn't be shadowed");else for(var u=s.fold(function(e,t,n){if(!e.isEmpty()&&t&&t.hasCompleteView())return[t.getCompleteView().getQuery()];var r=[];return t&&(r=r.concat(t.getQueryViews().map(function(e){return e.getQuery()}))),forEach(n,function(e,t){r=r.concat(t)}),r}),c=0;c<u.length;++c){var h=u[c];this.listenProvider_.stopListening(e.queryForListening_(h),this.tagForQuery_(h))}return a},e.prototype.createListenerForView_=function(e){var t=this,n=e.getQuery(),r=this.tagForQuery_(n);return{hashFn:function(){return(e.getServerCache()||ChildrenNode.EMPTY_NODE).hash()},onComplete:function(e){if("ok"===e)return r?t.applyTaggedListenComplete(n.path,r):t.applyListenComplete(n.path);var i=errorForServerCode(e,n);return t.removeEventRegistration(n,null,i)}}},e.makeQueryKey_=function(e){return e.path.toString()+"$"+e.queryIdentifier()},e.parseQueryKey_=function(e){var t=e.indexOf("$");return assert(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new Path(e.substr(0,t))}},e.prototype.queryKeyForTag_=function(e){return this.tagToQueryMap_["_"+e]},e.prototype.tagForQuery_=function(t){var n=e.makeQueryKey_(t);return safeGet(this.queryToTagMap_,n)},e.getNextQueryTag_=function(){return e.nextQueryTag_++},e.prototype.applyTaggedOperation_=function(e,t){var n=this.syncPointTree_.get(e);assert(n,"Missing sync point for query tag that we're tracking");var r=this.pendingWriteTree_.childWrites(e);return n.applyOperation(t,r,null)},e.prototype.applyOperationToSyncPoints_=function(e){return this.applyOperationHelper_(e,this.syncPointTree_,null,this.pendingWriteTree_.childWrites(Path.Empty))},e.prototype.applyOperationHelper_=function(e,t,n,r){if(e.path.isEmpty())return this.applyOperationDescendantsHelper_(e,t,n,r);var i=t.get(Path.Empty);null==n&&null!=i&&(n=i.getCompleteServerCache(Path.Empty));var o=[],a=e.path.getFront(),s=e.operationForChild(a),u=t.children.get(a);if(u&&s){var c=n?n.getImmediateChild(a):null,h=r.child(a);o=o.concat(this.applyOperationHelper_(s,u,c,h))}return i&&(o=o.concat(i.applyOperation(e,r,n))),o},e.prototype.applyOperationDescendantsHelper_=function(e,t,n,r){var i=this,o=t.get(Path.Empty);null==n&&null!=o&&(n=o.getCompleteServerCache(Path.Empty));var a=[];return t.children.inorderTraversal(function(t,o){var s=n?n.getImmediateChild(t):null,u=r.child(t),c=e.operationForChild(t);c&&(a=a.concat(i.applyOperationDescendantsHelper_(c,o,s,u)))}),o&&(a=a.concat(o.applyOperation(e,r,n))),a},e.nextQueryTag_=1,e}(),SnapshotHolder=function(){function e(){this.rootNode_=ChildrenNode.EMPTY_NODE}return e.prototype.getNode=function(e){return this.rootNode_.getChild(e)},e.prototype.updateSnapshot=function(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)},e}(),AuthTokenProvider=function(){function e(e){this.app_=e}return e.prototype.getToken=function(e){return this.app_.INTERNAL.getToken(e).then(null,function(e){return e&&"auth/token-not-initialized"===e.code?(log("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)})},e.prototype.addTokenChangeListener=function(e){this.app_.INTERNAL.addAuthTokenListener(e)},e.prototype.removeTokenChangeListener=function(e){this.app_.INTERNAL.removeAuthTokenListener(e)},e.prototype.notifyForInvalidToken=function(){var e='Provided authentication credentials for the app named "'+this.app_.name+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.app_.options?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.app_.options?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',warn(e)},e}(),StatsCollection=function(){function e(){this.counters_={}}return e.prototype.incrementCounter=function(e,t){void 0===t&&(t=1),contains(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t},e.prototype.get=function(){return deepCopy(this.counters_)},e}(),StatsManager=function(){function e(){}return e.getCollection=function(e){var t=e.toString();return this.collections_[t]||(this.collections_[t]=new StatsCollection),this.collections_[t]},e.getOrCreateReporter=function(e,t){var n=e.toString();return this.reporters_[n]||(this.reporters_[n]=t()),this.reporters_[n]},e.collections_={},e.reporters_={},e}(),StatsListener=function(){function e(e){this.collection_=e,this.last_=null}return e.prototype.get=function(){var e=this.collection_.get(),t=clone(e);return this.last_&&forEach(this.last_,function(e,n){t[e]=t[e]-n}),this.last_=e,t},e}(),FIRST_STATS_MIN_TIME=1e4,FIRST_STATS_MAX_TIME=3e4,REPORT_STATS_INTERVAL=3e5,StatsReporter=function(){function e(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new StatsListener(e);var n=FIRST_STATS_MIN_TIME+(FIRST_STATS_MAX_TIME-FIRST_STATS_MIN_TIME)*Math.random();setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(n))}return e.prototype.includeStat=function(e){this.statsToReport_[e]=!0},e.prototype.reportStats_=function(){var e=this,t=this.statsListener_.get(),n={},r=!1;forEach(t,function(t,i){i>0&&contains(e.statsToReport_,t)&&(n[t]=i,r=!0)}),r&&this.server_.reportStats(n),setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(2*Math.random()*REPORT_STATS_INTERVAL))},e}(),EventQueue=function(){function e(){this.eventLists_=[],this.recursionDepth_=0}return e.prototype.queueEvents=function(e){for(var t=null,n=0;n<e.length;n++){var r=e[n],i=r.getPath();null===t||i.equals(t.getPath())||(this.eventLists_.push(t),t=null),null===t&&(t=new EventList(i)),t.add(r)}t&&this.eventLists_.push(t)},e.prototype.raiseEventsAtPath=function(e,t){this.queueEvents(t),this.raiseQueuedEventsMatchingPredicate_(function(t){return t.equals(e)})},e.prototype.raiseEventsForChangedPath=function(e,t){this.queueEvents(t),this.raiseQueuedEventsMatchingPredicate_(function(t){return t.contains(e)||e.contains(t)})},e.prototype.raiseQueuedEventsMatchingPredicate_=function(e){this.recursionDepth_++;for(var t=!0,n=0;n<this.eventLists_.length;n++){var r=this.eventLists_[n];if(r)e(r.getPath())?(this.eventLists_[n].raise(),this.eventLists_[n]=null):t=!1}t&&(this.eventLists_=[]),this.recursionDepth_--},e}(),EventList=function(){function e(e){this.path_=e,this.events_=[]}return e.prototype.add=function(e){this.events_.push(e)},e.prototype.raise=function(){for(var e=0;e<this.events_.length;e++){var t=this.events_[e];if(null!==t){this.events_[e]=null;var n=t.getEventRunner();logger&&log("event: "+t.toString()),exceptionGuard(n)}}},e.prototype.getPath=function(){return this.path_},e}(),EventEmitter=function(){function e(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}return e.prototype.trigger=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(Array.isArray(this.listeners_[e]))for(var r=this.listeners_[e].slice(),i=0;i<r.length;i++)r[i].callback.apply(r[i].context,t)},e.prototype.on=function(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)},e.prototype.off=function(e,t,n){this.validateEventType_(e);for(var r=this.listeners_[e]||[],i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)},e.prototype.validateEventType_=function(e){assert(this.allowedEvents_.find(function(t){return t===e}),"Unknown event: "+e)},e}(),VisibilityMonitor=function(e){function t(){var t,n,r=e.call(this,["visible"])||this;return"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(n="visibilitychange",t="hidden"):void 0!==document.mozHidden?(n="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(n="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(n="webkitvisibilitychange",t="webkitHidden")),r.visible_=!0,n&&document.addEventListener(n,function(){var e=!document[t];e!==r.visible_&&(r.visible_=e,r.trigger("visible",e))},!1),r}return __extends(t,e),t.getInstance=function(){return new t},t.prototype.getInitialEvent=function(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]},t}(EventEmitter),OnlineMonitor=function(e){function t(){var t=e.call(this,["online"])||this;return t.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||isMobileCordova()||(window.addEventListener("online",function(){t.online_||(t.online_=!0,t.trigger("online",!0))},!1),window.addEventListener("offline",function(){t.online_&&(t.online_=!1,t.trigger("online",!1))},!1)),t}return __extends(t,e),t.getInstance=function(){return new t},t.prototype.getInitialEvent=function(e){return assert("online"===e,"Unknown event type: "+e),[this.online_]},t.prototype.currentlyOnline=function(){return this.online_},t}(EventEmitter),PacketReceiver=function(){function e(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}return e.prototype.closeAfter=function(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)},e.prototype.handleResponse=function(e,t){var n=this;this.pendingResponses[e]=t;for(var r=function(){var e=i.pendingResponses[i.currentResponseNum];delete i.pendingResponses[i.currentResponseNum];for(var t=function(t){e[t]&&exceptionGuard(function(){n.onMessage_(e[t])})},r=0;r<e.length;++r)t(r);if(i.currentResponseNum===i.closeAfterResponse)return i.onClose&&(i.onClose(),i.onClose=null),"break";i.currentResponseNum++},i=this;this.pendingResponses[this.currentResponseNum];){if("break"===r())break}},e}(),FIREBASE_LONGPOLL_START_PARAM="start",FIREBASE_LONGPOLL_CLOSE_COMMAND="close",FIREBASE_LONGPOLL_COMMAND_CB_NAME="pLPCommand",FIREBASE_LONGPOLL_DATA_CB_NAME="pRTLPCB",FIREBASE_LONGPOLL_ID_PARAM="id",FIREBASE_LONGPOLL_PW_PARAM="pw",FIREBASE_LONGPOLL_SERIAL_PARAM="ser",FIREBASE_LONGPOLL_CALLBACK_ID_PARAM="cb",FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM="seg",FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET="ts",FIREBASE_LONGPOLL_DATA_PARAM="d",FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM="disconn",FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM="dframe",MAX_URL_DATA_SIZE=1870,SEG_HEADER_SIZE=30,MAX_PAYLOAD_SIZE=MAX_URL_DATA_SIZE-SEG_HEADER_SIZE,KEEPALIVE_REQUEST_INTERVAL=25e3,LP_CONNECT_TIMEOUT=3e4,BrowserPollConnection=function(){function e(e,t,n,r){this.connId=e,this.repoInfo=t,this.transportSessionId=n,this.lastSessionId=r,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=logWrapper(e),this.stats_=StatsManager.getCollection(t),this.urlFn=function(e){return t.connectionURL(LONG_POLLING,e)}}return e.prototype.open=function(e,t){var n=this;this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new PacketReceiver(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(function(){n.log_("Timed out trying to connect."),n.onClosed_(),n.connectTimeoutTimer_=null},Math.floor(LP_CONNECT_TIMEOUT)),executeWhenDOMReady(function(){if(!n.isClosed_){n.scriptTagHolder=new FirebaseIFrameScriptHolder(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=e[0],i=e[1],o=e[2];if(n.incrementIncomingBytes_(e),n.scriptTagHolder)if(n.connectTimeoutTimer_&&(clearTimeout(n.connectTimeoutTimer_),n.connectTimeoutTimer_=null),n.everConnected_=!0,r==FIREBASE_LONGPOLL_START_PARAM)n.id=i,n.password=o;else{if(r!==FIREBASE_LONGPOLL_CLOSE_COMMAND)throw new Error("Unrecognized command received: "+r);i?(n.scriptTagHolder.sendNewPolls=!1,n.myPacketOrderer.closeAfter(i,function(){n.onClosed_()})):n.onClosed_()}},function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=e[0],i=e[1];n.incrementIncomingBytes_(e),n.myPacketOrderer.handleResponse(r,i)},function(){n.onClosed_()},n.urlFn);var e={};e[FIREBASE_LONGPOLL_START_PARAM]="t",e[FIREBASE_LONGPOLL_SERIAL_PARAM]=Math.floor(1e8*Math.random()),n.scriptTagHolder.uniqueCallbackIdentifier&&(e[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM]=n.scriptTagHolder.uniqueCallbackIdentifier),e[VERSION_PARAM]=PROTOCOL_VERSION,n.transportSessionId&&(e[TRANSPORT_SESSION_PARAM]=n.transportSessionId),n.lastSessionId&&(e[LAST_SESSION_PARAM]=n.lastSessionId),!isNodeSdk()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf(FORGE_DOMAIN)&&(e[REFERER_PARAM]=FORGE_REF);var t=n.urlFn(e);n.log_("Connecting via long-poll to "+t),n.scriptTagHolder.addTag(t,function(){})}})},e.prototype.start=function(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)},e.forceAllow=function(){e.forceAllow_=!0},e.forceDisallow=function(){e.forceDisallow_=!0},e.isAvailable=function(){return e.forceAllow_||!e.forceDisallow_&&"undefined"!=typeof document&&null!=document.createElement&&!isChromeExtensionContentScript()&&!isWindowsStoreApp()&&!isNodeSdk()},e.prototype.markConnectionHealthy=function(){},e.prototype.shutdown_=function(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)},e.prototype.onClosed_=function(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))},e.prototype.close=function(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())},e.prototype.send=function(e){var t=stringify(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);for(var n=base64Encode(t),r=splitStringBySize(n,MAX_PAYLOAD_SIZE),i=0;i<r.length;i++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[i]),this.curSegmentNum++},e.prototype.addDisconnectPingFrame=function(e,t){if(!isNodeSdk()){this.myDisconnFrame=document.createElement("iframe");var n={};n[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM]="t",n[FIREBASE_LONGPOLL_ID_PARAM]=e,n[FIREBASE_LONGPOLL_PW_PARAM]=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}},e.prototype.incrementIncomingBytes_=function(e){var t=stringify(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)},e}(),FirebaseIFrameScriptHolder=function(){function e(t,n,r,i){if(this.onDisconnect=r,this.urlFn=i,this.outstandingRequests=new CountedSet,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,isNodeSdk())this.commandCB=t,this.onMessageCB=n;else{this.uniqueCallbackIdentifier=LUIDGenerator(),window[FIREBASE_LONGPOLL_COMMAND_CB_NAME+this.uniqueCallbackIdentifier]=t,window[FIREBASE_LONGPOLL_DATA_CB_NAME+this.uniqueCallbackIdentifier]=n,this.myIFrame=e.createIFrame_();var o="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length))o='<script>document.domain="'+document.domain+'";<\/script>';var a="<html><body>"+o+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(a),this.myIFrame.doc.close()}catch(e){log("frame writing exception"),e.stack&&log(e.stack),log(e)}}}return e.createIFrame_=function(){var e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||log("No IE domain setting required")}catch(n){var t=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+t+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e},e.prototype.close=function(){var t=this;if(this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(function(){null!==t.myIFrame&&(document.body.removeChild(t.myIFrame),t.myIFrame=null)},Math.floor(0))),isNodeSdk()&&this.myID){var n={};n[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM]="t",n[FIREBASE_LONGPOLL_ID_PARAM]=this.myID,n[FIREBASE_LONGPOLL_PW_PARAM]=this.myPW;var r=this.urlFn(n);e.nodeRestRequest(r)}var i=this.onDisconnect;i&&(this.onDisconnect=null,i())},e.prototype.startLongPoll=function(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););},e.prototype.newRequest_=function(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.count()<(this.pendingSegs.length>0?2:1)){this.currentSerial++;var e={};e[FIREBASE_LONGPOLL_ID_PARAM]=this.myID,e[FIREBASE_LONGPOLL_PW_PARAM]=this.myPW,e[FIREBASE_LONGPOLL_SERIAL_PARAM]=this.currentSerial;for(var t=this.urlFn(e),n="",r=0;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+SEG_HEADER_SIZE+n.length<=MAX_URL_DATA_SIZE))break;var i=this.pendingSegs.shift();n=n+"&"+FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM+r+"="+i.seg+"&"+FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET+r+"="+i.ts+"&"+FIREBASE_LONGPOLL_DATA_PARAM+r+"="+i.d,r++}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1},e.prototype.enqueueSegment=function(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()},e.prototype.addLongPollTag_=function(e,t){var n=this;this.outstandingRequests.add(t,1);var r=function(){n.outstandingRequests.remove(t),n.newRequest_()},i=setTimeout(r,Math.floor(KEEPALIVE_REQUEST_INTERVAL));this.addTag(e,function(){clearTimeout(i),r()})},e.prototype.addTag=function(e,t){var n=this;isNodeSdk()?this.doNodeLongPoll(e,t):setTimeout(function(){try{if(!n.sendNewPolls)return;var r=n.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.onload=r.onreadystatechange=function(){var e=r.readyState;e&&"loaded"!==e&&"complete"!==e||(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),t())},r.onerror=function(){log("Long-poll script failed to load: "+e),n.sendNewPolls=!1,n.close()},n.myIFrame.doc.body.appendChild(r)}catch(e){}},Math.floor(1))},e}(),WEBSOCKET_MAX_FRAME_SIZE=16384,WEBSOCKET_KEEPALIVE_INTERVAL=45e3,WebSocketImpl=null;"undefined"!=typeof MozWebSocket?WebSocketImpl=MozWebSocket:"undefined"!=typeof WebSocket&&(WebSocketImpl=WebSocket);var WebSocketConnection=function(){function e(t,n,r,i){this.connId=t,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=logWrapper(this.connId),this.stats_=StatsManager.getCollection(n),this.connURL=e.connectionURL_(n,r,i)}return e.connectionURL_=function(e,t,n){var r={};return r[VERSION_PARAM]=PROTOCOL_VERSION,!isNodeSdk()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf(FORGE_DOMAIN)&&(r[REFERER_PARAM]=FORGE_REF),t&&(r[TRANSPORT_SESSION_PARAM]=t),n&&(r[LAST_SESSION_PARAM]=n),e.connectionURL(WEBSOCKET,r)},e.prototype.open=function(e,t){var n=this;this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,PersistentStorage.set("previous_websocket_failure",!0);try{if(isNodeSdk()){var r=CONSTANTS.NODE_ADMIN?"AdminNode":"Node",i={headers:{"User-Agent":"Firebase/"+PROTOCOL_VERSION+"/"+firebase.SDK_VERSION+"/"+process.platform+"/"+r}},o=process.env,a=0==this.connURL.indexOf("wss://")?o.HTTPS_PROXY||o.https_proxy:o.HTTP_PROXY||o.http_proxy;a&&(i.proxy={origin:a}),this.mySock=new WebSocketImpl(this.connURL,[],i)}else this.mySock=new WebSocketImpl(this.connURL)}catch(e){this.log_("Error instantiating WebSocket.");var s=e.message||e.data;return s&&this.log_(s),void this.onClosed_()}this.mySock.onopen=function(){n.log_("Websocket connected."),n.everConnected_=!0},this.mySock.onclose=function(){n.log_("Websocket connection was disconnected."),n.mySock=null,n.onClosed_()},this.mySock.onmessage=function(e){n.handleIncomingFrame(e)},this.mySock.onerror=function(e){n.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&n.log_(t),n.onClosed_()}},e.prototype.start=function(){},e.forceDisallow=function(){e.forceDisallow_=!0},e.isAvailable=function(){var t=!1;if("undefined"!=typeof navigator&&navigator.userAgent){var n=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);n&&n.length>1&&parseFloat(n[1])<4.4&&(t=!0)}return!t&&null!==WebSocketImpl&&!e.forceDisallow_},e.previouslyFailed=function(){return PersistentStorage.isInMemoryStorage||!0===PersistentStorage.get("previous_websocket_failure")},e.prototype.markConnectionHealthy=function(){PersistentStorage.remove("previous_websocket_failure")},e.prototype.appendFrame_=function(e){if(this.frames.push(e),this.frames.length==this.totalFrames){var t=this.frames.join("");this.frames=null;var n=jsonEval(t);this.onMessage(n)}},e.prototype.handleNewFrameCount_=function(e){this.totalFrames=e,this.frames=[]},e.prototype.extractFrameCount_=function(e){if(assert(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e},e.prototype.handleIncomingFrame=function(e){if(null!==this.mySock){var t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{var n=this.extractFrameCount_(t);null!==n&&this.appendFrame_(n)}}},e.prototype.send=function(e){this.resetKeepAlive();var t=stringify(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=splitStringBySize(t,WEBSOCKET_MAX_FRAME_SIZE);n.length>1&&this.sendString_(String(n.length));for(var r=0;r<n.length;r++)this.sendString_(n[r])},e.prototype.shutdown_=function(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)},e.prototype.onClosed_=function(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))},e.prototype.close=function(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())},e.prototype.resetKeepAlive=function(){var e=this;clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(function(){e.mySock&&e.sendString_("0"),e.resetKeepAlive()},Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL))},e.prototype.sendString_=function(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}},e.responsesRequiredToBeHealthy=2,e.healthyTimeout=3e4,e}(),TransportManager=function(){function e(e){this.initTransports_(e)}return Object.defineProperty(e,"ALL_TRANSPORTS",{get:function(){return[BrowserPollConnection,WebSocketConnection]},enumerable:!0,configurable:!0}),e.prototype.initTransports_=function(t){var n=WebSocketConnection&&WebSocketConnection.isAvailable(),r=n&&!WebSocketConnection.previouslyFailed();if(t.webSocketOnly&&(n||warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[WebSocketConnection];else{var i=this.transports_=[];each(e.ALL_TRANSPORTS,function(e,t){t&&t.isAvailable()&&i.push(t)})}},e.prototype.initialTransport=function(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")},e.prototype.upgradeTransport=function(){return this.transports_.length>1?this.transports_[1]:null},e}(),UPGRADE_TIMEOUT=6e4,DELAY_BEFORE_SENDING_EXTRA_REQUESTS=5e3,BYTES_SENT_HEALTHY_OVERRIDE=10240,BYTES_RECEIVED_HEALTHY_OVERRIDE=102400,MESSAGE_TYPE="t",MESSAGE_DATA="d",CONTROL_SHUTDOWN="s",CONTROL_RESET="r",CONTROL_ERROR="e",CONTROL_PONG="o",SWITCH_ACK="a",END_TRANSMISSION="n",PING="p",SERVER_HELLO="h",Connection=function(){function e(e,t,n,r,i,o,a){this.id=e,this.repoInfo_=t,this.onMessage_=n,this.onReady_=r,this.onDisconnect_=i,this.onKill_=o,this.lastSessionId=a,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=logWrapper("c:"+this.id+":"),this.transportManager_=new TransportManager(t),this.log_("Connection created"),this.start_()}return e.prototype.start_=function(){var e=this,t=this.transportManager_.initialTransport();this.conn_=new t(this.nextTransportId_(),this.repoInfo_,void 0,this.lastSessionId),this.primaryResponsesRequired_=t.responsesRequiredToBeHealthy||0;var n=this.connReceiver_(this.conn_),r=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(function(){e.conn_&&e.conn_.open(n,r)},Math.floor(0));var i=t.healthyTimeout||0;i>0&&(this.healthyTimeout_=setTimeoutNonBlocking(function(){e.healthyTimeout_=null,e.isHealthy_||(e.conn_&&e.conn_.bytesReceived>BYTES_RECEIVED_HEALTHY_OVERRIDE?(e.log_("Connection exceeded healthy timeout but has received "+e.conn_.bytesReceived+" bytes. Marking connection healthy."),e.isHealthy_=!0,e.conn_.markConnectionHealthy()):e.conn_&&e.conn_.bytesSent>BYTES_SENT_HEALTHY_OVERRIDE?e.log_("Connection exceeded healthy timeout but has sent "+e.conn_.bytesSent+" bytes. Leaving connection alive."):(e.log_("Closing unhealthy connection after timeout."),e.close()))},Math.floor(i)))},e.prototype.nextTransportId_=function(){return"c:"+this.id+":"+this.connectionCount++},e.prototype.disconnReceiver_=function(e){var t=this;return function(n){e===t.conn_?t.onConnectionLost_(n):e===t.secondaryConn_?(t.log_("Secondary connection lost."),t.onSecondaryConnectionLost_()):t.log_("closing an old connection")}},e.prototype.connReceiver_=function(e){var t=this;return function(n){2!=t.state_&&(e===t.rx_?t.onPrimaryMessageReceived_(n):e===t.secondaryConn_?t.onSecondaryMessageReceived_(n):t.log_("message on old connection"))}},e.prototype.sendRequest=function(e){var t={t:"d",d:e};this.sendData_(t)},e.prototype.tryCleanupConnection=function(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)},e.prototype.onSecondaryControl_=function(e){if(MESSAGE_TYPE in e){var t=e[MESSAGE_TYPE];t===SWITCH_ACK?this.upgradeIfSecondaryHealthy_():t===CONTROL_RESET?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):t===CONTROL_PONG&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}},e.prototype.onSecondaryMessageReceived_=function(e){var t=requireKey("t",e),n=requireKey("d",e);if("c"==t)this.onSecondaryControl_(n);else{if("d"!=t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}},e.prototype.upgradeIfSecondaryHealthy_=function(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:PING,d:{}}}))},e.prototype.proceedWithUpgrade_=function(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:SWITCH_ACK,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:END_TRANSMISSION,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()},e.prototype.onPrimaryMessageReceived_=function(e){var t=requireKey("t",e),n=requireKey("d",e);"c"==t?this.onControl_(n):"d"==t&&this.onDataMessage_(n)},e.prototype.onDataMessage_=function(e){this.onPrimaryResponse_(),this.onMessage_(e)},e.prototype.onPrimaryResponse_=function(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))},e.prototype.onControl_=function(e){var t=requireKey(MESSAGE_TYPE,e);if(MESSAGE_DATA in e){var n=e[MESSAGE_DATA];if(t===SERVER_HELLO)this.onHandshake_(n);else if(t===END_TRANSMISSION){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(var r=0;r<this.pendingDataMessages.length;++r)this.onDataMessage_(this.pendingDataMessages[r]);this.pendingDataMessages=[],this.tryCleanupConnection()}else t===CONTROL_SHUTDOWN?this.onConnectionShutdown_(n):t===CONTROL_RESET?this.onReset_(n):t===CONTROL_ERROR?error$1("Server Error: "+n):t===CONTROL_PONG?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):error$1("Unknown control packet command: "+t)}},e.prototype.onHandshake_=function(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.updateHost(r),0==this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),PROTOCOL_VERSION!==n&&warn("Protocol version mismatch detected"),this.tryStartUpgrade_())},e.prototype.tryStartUpgrade_=function(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)},e.prototype.startUpgrade_=function(e){var t=this;this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var n=this.connReceiver_(this.secondaryConn_),r=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(n,r),setTimeoutNonBlocking(function(){t.secondaryConn_&&(t.log_("Timed out trying to upgrade."),t.secondaryConn_.close())},Math.floor(UPGRADE_TIMEOUT))},e.prototype.onReset_=function(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.updateHost(e),1===this.state_?this.close():(this.closeConnections_(),this.start_())},e.prototype.onConnectionEstablished_=function(e,t){var n=this;this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):setTimeoutNonBlocking(function(){n.sendPingOnPrimaryIfNecessary_()},Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS))},e.prototype.sendPingOnPrimaryIfNecessary_=function(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:PING,d:{}}}))},e.prototype.onSecondaryConnectionLost_=function(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()},e.prototype.onConnectionLost_=function(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(PersistentStorage.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()},e.prototype.onConnectionShutdown_=function(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()},e.prototype.sendData_=function(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)},e.prototype.close=function(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))},e.prototype.closeConnections_=function(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)},e}(),ServerActions=function(){function e(){}return e.prototype.put=function(e,t,n,r){},e.prototype.merge=function(e,t,n,r){},e.prototype.refreshAuthToken=function(e){},e.prototype.onDisconnectPut=function(e,t,n){},e.prototype.onDisconnectMerge=function(e,t,n){},e.prototype.onDisconnectCancel=function(e,t){},e.prototype.reportStats=function(e){},e}(),RECONNECT_MIN_DELAY=1e3,RECONNECT_MAX_DELAY_DEFAULT=3e5,RECONNECT_MAX_DELAY_FOR_ADMINS=3e4,RECONNECT_DELAY_MULTIPLIER=1.3,RECONNECT_DELAY_RESET_TIMEOUT=3e4,SERVER_KILL_INTERRUPT_REASON="server_kill",INVALID_AUTH_TOKEN_THRESHOLD=3,PersistentConnection=function(e){function t(n,r,i,o,a,s){var u=e.call(this)||this;if(u.repoInfo_=n,u.onDataUpdate_=r,u.onConnectStatus_=i,u.onServerInfoUpdate_=o,u.authTokenProvider_=a,u.authOverride_=s,u.id=t.nextPersistentConnectionId_++,u.log_=logWrapper("p:"+u.id+":"),u.interruptReasons_={},u.listens_={},u.outstandingPuts_=[],u.outstandingPutCount_=0,u.onDisconnectRequestQueue_=[],u.connected_=!1,u.reconnectDelay_=RECONNECT_MIN_DELAY,u.maxReconnectDelay_=RECONNECT_MAX_DELAY_DEFAULT,u.securityDebugCallback_=null,u.lastSessionId=null,u.establishConnectionTimer_=null,u.visible_=!1,u.requestCBHash_={},u.requestNumber_=0,u.realtime_=null,u.authToken_=null,u.forceTokenRefresh_=!1,u.invalidAuthTokenCount_=0,u.firstConnection_=!0,u.lastConnectionAttemptTime_=null,u.lastConnectionEstablishedTime_=null,s&&!isNodeSdk())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");return u.scheduleConnect_(0),VisibilityMonitor.getInstance().on("visible",u.onVisible_,u),-1===n.host.indexOf("fblocal")&&OnlineMonitor.getInstance().on("online",u.onOnline_,u),u}return __extends(t,e),t.prototype.sendRequest=function(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(stringify(i)),assert(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)},t.prototype.listen=function(e,t,n,r){var i=e.queryIdentifier(),o=e.path.toString();this.log_("Listen called for "+o+" "+i),this.listens_[o]=this.listens_[o]||{},assert(e.getQueryParams().isDefault()||!e.getQueryParams().loadsAllData(),"listen() called for non-default but complete query"),assert(!this.listens_[o][i],"listen() called twice for same path/queryId.");var a={onComplete:r,hashFn:t,query:e,tag:n};this.listens_[o][i]=a,this.connected_&&this.sendListen_(a)},t.prototype.sendListen_=function(e){var n=this,r=e.query,i=r.path.toString(),o=r.queryIdentifier();this.log_("Listen on "+i+" for "+o);var a={p:i};e.tag&&(a.q=r.queryObject(),a.t=e.tag),a.h=e.hashFn(),this.sendRequest("q",a,function(a){var s=a.d,u=a.s;t.warnOnListenWarnings_(s,r),(n.listens_[i]&&n.listens_[i][o])===e&&(n.log_("listen response",a),"ok"!==u&&n.removeListen_(i,o),e.onComplete&&e.onComplete(u,s))})},t.warnOnListenWarnings_=function(e,t){if(e&&"object"==typeof e&&contains(e,"w")){var n=safeGet(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){var r='".indexOn": "'+t.getQueryParams().getIndex().toString()+'"',i=t.path.toString();warn("Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding "+r+" at "+i+" to your security rules for better performance.")}}},t.prototype.refreshAuthToken=function(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},function(){}),this.reduceReconnectDelayIfAdminCredential_(e)},t.prototype.reduceReconnectDelayIfAdminCredential_=function(e){(e&&40===e.length||isAdmin(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=RECONNECT_MAX_DELAY_FOR_ADMINS)},t.prototype.tryAuth=function(){var e=this;if(this.connected_&&this.authToken_){var t=this.authToken_,n=isValidFormat(t)?"auth":"gauth",r={cred:t};null===this.authOverride_?r.noauth=!0:"object"==typeof this.authOverride_&&(r.authvar=this.authOverride_),this.sendRequest(n,r,function(n){var r=n.s,i=n.d||"error";e.authToken_===t&&("ok"===r?e.invalidAuthTokenCount_=0:e.onAuthRevoked_(r,i))})}},t.prototype.unlisten=function(e,t){var n=e.path.toString(),r=e.queryIdentifier();this.log_("Unlisten called for "+n+" "+r),assert(e.getQueryParams().isDefault()||!e.getQueryParams().loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e.queryObject(),t)},t.prototype.sendUnlisten_=function(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);var i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)},t.prototype.onDisconnectPut=function(e,t,n){this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})},t.prototype.onDisconnectMerge=function(e,t,n){this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})},t.prototype.onDisconnectCancel=function(e,t){this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})},t.prototype.sendOnDisconnect_=function(e,t,n,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,function(e){r&&setTimeout(function(){r(e.s,e.d)},Math.floor(0))})},t.prototype.put=function(e,t,n,r){this.putInternal("p",e,t,n,r)},t.prototype.merge=function(e,t,n,r){this.putInternal("m",e,t,n,r)},t.prototype.putInternal=function(e,t,n,r,i){var o={p:t,d:n};void 0!==i&&(o.h=i),this.outstandingPuts_.push({action:e,request:o,onComplete:r}),this.outstandingPutCount_++;var a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+t)},t.prototype.sendPut_=function(e){var t=this,n=this.outstandingPuts_[e].action,r=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(n,r,function(r){t.log_(n+" response",r),delete t.outstandingPuts_[e],t.outstandingPutCount_--,0===t.outstandingPutCount_&&(t.outstandingPuts_=[]),i&&i(r.s,r.d)})},t.prototype.reportStats=function(e){var t=this;if(this.connected_){var n={c:e};this.log_("reportStats",n),this.sendRequest("s",n,function(e){if("ok"!==e.s){var n=e.d;t.log_("reportStats","Error sending stats: "+n)}})}},t.prototype.onDataMessage_=function(e){if("r"in e){this.log_("from server: "+stringify(e));var t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}},t.prototype.onDataPush_=function(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):error$1("Unrecognized action received from server: "+stringify(e)+"\nAre you using the latest client?")},t.prototype.onReady_=function(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)},t.prototype.scheduleConnect_=function(e){var t=this;assert(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(function(){t.establishConnectionTimer_=null,t.establishConnection_()},Math.floor(e))},t.prototype.onVisible_=function(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=RECONNECT_MIN_DELAY,this.realtime_||this.scheduleConnect_(0)),this.visible_=e},t.prototype.onOnline_=function(e){e?(this.log_("Browser went online."),this.reconnectDelay_=RECONNECT_MIN_DELAY,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())},t.prototype.onRealtimeDisconnect_=function(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>RECONNECT_DELAY_RESET_TIMEOUT&&(this.reconnectDelay_=RECONNECT_MIN_DELAY),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();var e=(new Date).getTime()-this.lastConnectionAttemptTime_,t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*RECONNECT_DELAY_MULTIPLIER)}this.onConnectStatus_(!1)},t.prototype.establishConnection_=function(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var e=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+t.nextConnectionId_++,o=this,a=this.lastSessionId,s=!1,u=null,c=function(){u?u.close():(s=!0,r())};this.realtime_={close:c,sendRequest:function(e){assert(u,"sendRequest call when we're not connected not allowed."),u.sendRequest(e)}};var h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1,this.authTokenProvider_.getToken(h).then(function(t){s?log("getToken() completed but was canceled"):(log("getToken() completed. Creating connection."),o.authToken_=t&&t.accessToken,u=new Connection(i,o.repoInfo_,e,n,r,function(e){warn(e+" ("+o.repoInfo_.toString()+")"),o.interrupt(SERVER_KILL_INTERRUPT_REASON)},a))}).then(null,function(e){o.log_("Failed to get token: "+e),s||(CONSTANTS.NODE_ADMIN&&warn(e),c())})}},t.prototype.interrupt=function(e){log("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())},t.prototype.resume=function(e){log("Resuming connection for reason: "+e),delete this.interruptReasons_[e],isEmpty(this.interruptReasons_)&&(this.reconnectDelay_=RECONNECT_MIN_DELAY,this.realtime_||this.scheduleConnect_(0))},t.prototype.handleTimestamp_=function(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})},t.prototype.cancelSentTransactions_=function(){for(var e=0;e<this.outstandingPuts_.length;e++){var t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])},t.prototype.onListenRevoked_=function(e,t){var n;n=t?t.map(function(e){return ObjectToUniqueKey(e)}).join("$"):"default";var r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")},t.prototype.removeListen_=function(e,t){var n,r=new Path(e).toString();return void 0!==this.listens_[r]?(n=this.listens_[r][t],delete this.listens_[r][t],0===getCount(this.listens_[r])&&delete this.listens_[r]):n=void 0,n},t.prototype.onAuthRevoked_=function(e,t){log("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=INVALID_AUTH_TOKEN_THRESHOLD&&(this.reconnectDelay_=RECONNECT_MAX_DELAY_FOR_ADMINS,this.authTokenProvider_.notifyForInvalidToken()))},t.prototype.onSecurityDebugPacket_=function(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))},t.prototype.restoreState_=function(){var e=this;this.tryAuth(),forEach(this.listens_,function(t,n){forEach(n,function(t,n){e.sendListen_(n)})});for(var t=0;t<this.outstandingPuts_.length;t++)this.outstandingPuts_[t]&&this.sendPut_(t);for(;this.onDisconnectRequestQueue_.length;){var n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}},t.prototype.sendConnectStats_=function(){var e={},t="js";CONSTANTS.NODE_ADMIN?t="admin_node":CONSTANTS.NODE_CLIENT&&(t="node"),e["sdk."+t+"."+firebase.SDK_VERSION.replace(/\./g,"-")]=1,isMobileCordova()?e["framework.cordova"]=1:isReactNative()&&(e["framework.reactnative"]=1),this.reportStats(e)},t.prototype.shouldReconnect_=function(){var e=OnlineMonitor.getInstance().currentlyOnline();return isEmpty(this.interruptReasons_)&&e},t.nextPersistentConnectionId_=0,t.nextConnectionId_=0,t}(ServerActions),ReadonlyRestClient=function(e){function t(t,n,r){var i=e.call(this)||this;return i.repoInfo_=t,i.onDataUpdate_=n,i.authTokenProvider_=r,i.log_=logWrapper("p:rest:"),i.listens_={},i}return __extends(t,e),t.prototype.reportStats=function(e){throw new Error("Method not implemented.")},t.getListenId_=function(e,t){return void 0!==t?"tag$"+t:(assert(e.getQueryParams().isDefault(),"should have a tag if it's not a default query."),e.path.toString())},t.prototype.listen=function(e,n,r,i){var o=this,a=e.path.toString();this.log_("Listen called for "+a+" "+e.queryIdentifier());var s=t.getListenId_(e,r),u={};this.listens_[s]=u;var c=e.getQueryParams().toRestQueryStringParameters();this.restRequest_(a+".json",c,function(e,t){var n=t;(404===e&&(n=null,e=null),null===e&&o.onDataUpdate_(a,n,!1,r),safeGet(o.listens_,s)===u)&&i(e?401==e?"permission_denied":"rest_error:"+e:"ok",null)})},t.prototype.unlisten=function(e,n){var r=t.getListenId_(e,n);delete this.listens_[r]},t.prototype.refreshAuthToken=function(e){},t.prototype.restRequest_=function(e,t,n){var r=this;void 0===t&&(t={}),t.format="export",this.authTokenProvider_.getToken(!1).then(function(i){var o=i&&i.accessToken;o&&(t.auth=o);var a=(r.repoInfo_.secure?"https://":"http://")+r.repoInfo_.host+e+"?"+querystring(t);r.log_("Sending REST request for "+a);var s=new XMLHttpRequest;s.onreadystatechange=function(){if(n&&4===s.readyState){r.log_("REST Response for "+a+" received. status:",s.status,"response:",s.responseText);var e=null;if(s.status>=200&&s.status<300){try{e=jsonEval(s.responseText)}catch(e){warn("Failed to parse JSON response for "+a+": "+s.responseText)}n(null,e)}else 401!==s.status&&404!==s.status&&warn("Got unsuccessful REST response for "+a+" Status: "+s.status),n(s.status);n=null}},s.open("GET",a,!0),s.send()})},t}(ServerActions),INTERRUPT_REASON="repo_interrupt",Repo=function(){function e(e,t,n){var r=this;this.repoInfo_=e,this.app=n,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new EventQueue,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=new SparseSnapshotTree,this.persistentConnection_=null;var i=new AuthTokenProvider(n);if(this.stats_=StatsManager.getCollection(e),t||beingCrawled())this.server_=new ReadonlyRestClient(this.repoInfo_,this.onDataUpdate_.bind(this),i),setTimeout(this.onConnectStatus_.bind(this,!0),0);else{var o=n.options.databaseAuthVariableOverride;if(void 0!==o&&null!==o){if("object"!=typeof o)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{stringify(o)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}this.persistentConnection_=new PersistentConnection(this.repoInfo_,this.onDataUpdate_.bind(this),this.onConnectStatus_.bind(this),this.onServerInfoUpdate_.bind(this),i,o),this.server_=this.persistentConnection_}i.addTokenChangeListener(function(e){r.server_.refreshAuthToken(e)}),this.statsReporter_=StatsManager.getOrCreateReporter(e,function(){return new StatsReporter(r.stats_,r.server_)}),this.transactions_init_(),this.infoData_=new SnapshotHolder,this.infoSyncTree_=new SyncTree({startListening:function(e,t,n,i){var o=[],a=r.infoData_.getNode(e.path);return a.isEmpty()||(o=r.infoSyncTree_.applyServerOverwrite(e.path,a),setTimeout(function(){i("ok")},0)),o},stopListening:function(){}}),this.updateInfo_("connected",!1),this.serverSyncTree_=new SyncTree({startListening:function(e,t,n,i){return r.server_.listen(e,n,t,function(t,n){var o=i(t,n);r.eventQueue_.raiseEventsForChangedPath(e.path,o)}),[]},stopListening:function(e,t){r.server_.unlisten(e,t)}})}return e.prototype.toString=function(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host},e.prototype.name=function(){return this.repoInfo_.namespace},e.prototype.serverTime=function(){var e=this.infoData_.getNode(new Path(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+e},e.prototype.generateServerValues=function(){return generateWithValues({timestamp:this.serverTime()})},e.prototype.onDataUpdate_=function(e,t,n,r){this.dataUpdateCount++;var i=new Path(e);t=this.interceptServerDataCallback_?this.interceptServerDataCallback_(e,t):t;var o=[];if(r)if(n){var a=map(t,function(e){return nodeFromJSON$1(e)});o=this.serverSyncTree_.applyTaggedQueryMerge(i,a,r)}else{var s=nodeFromJSON$1(t);o=this.serverSyncTree_.applyTaggedQueryOverwrite(i,s,r)}else if(n){var u=map(t,function(e){return nodeFromJSON$1(e)});o=this.serverSyncTree_.applyServerMerge(i,u)}else{var c=nodeFromJSON$1(t);o=this.serverSyncTree_.applyServerOverwrite(i,c)}var h=i;o.length>0&&(h=this.rerunTransactions_(i)),this.eventQueue_.raiseEventsForChangedPath(h,o)},e.prototype.interceptServerData_=function(e){this.interceptServerDataCallback_=e},e.prototype.onConnectStatus_=function(e){this.updateInfo_("connected",e),!1===e&&this.runOnDisconnectEvents_()},e.prototype.onServerInfoUpdate_=function(e){var t=this;each(e,function(e,n){t.updateInfo_(n,e)})},e.prototype.updateInfo_=function(e,t){var n=new Path("/.info/"+e),r=nodeFromJSON$1(t);this.infoData_.updateSnapshot(n,r);var i=this.infoSyncTree_.applyServerOverwrite(n,r);this.eventQueue_.raiseEventsForChangedPath(n,i)},e.prototype.getNextWriteId_=function(){return this.nextWriteId_++},e.prototype.setWithPriority=function(e,t,n,r){var i=this;this.log_("set",{path:e.toString(),value:t,priority:n});var o=this.generateServerValues(),a=nodeFromJSON$1(t,n),s=resolveDeferredValueSnapshot(a,o),u=this.getNextWriteId_(),c=this.serverSyncTree_.applyUserOverwrite(e,s,u,!0);this.eventQueue_.queueEvents(c),this.server_.put(e.toString(),a.val(!0),function(t,n){var o="ok"===t;o||warn("set at "+e+" failed: "+t);var a=i.serverSyncTree_.ackUserWrite(u,!o);i.eventQueue_.raiseEventsForChangedPath(e,a),i.callOnCompleteCallback(r,t,n)});var h=this.abortTransactions_(e);this.rerunTransactions_(h),this.eventQueue_.raiseEventsForChangedPath(h,[])},e.prototype.update=function(e,t,n){var r=this;this.log_("update",{path:e.toString(),value:t});var i=!0,o=this.generateServerValues(),a={};if(forEach(t,function(e,t){i=!1;var n=nodeFromJSON$1(t);a[e]=resolveDeferredValueSnapshot(n,o)}),i)log("update() called with empty data. Don't do anything."),this.callOnCompleteCallback(n,"ok");else{var s=this.getNextWriteId_(),u=this.serverSyncTree_.applyUserMerge(e,a,s);this.eventQueue_.queueEvents(u),this.server_.merge(e.toString(),t,function(t,i){var o="ok"===t;o||warn("update at "+e+" failed: "+t);var a=r.serverSyncTree_.ackUserWrite(s,!o),u=a.length>0?r.rerunTransactions_(e):e;r.eventQueue_.raiseEventsForChangedPath(u,a),r.callOnCompleteCallback(n,t,i)}),forEach(t,function(t){var n=r.abortTransactions_(e.child(t));r.rerunTransactions_(n)}),this.eventQueue_.raiseEventsForChangedPath(e,[])}},e.prototype.runOnDisconnectEvents_=function(){var e=this;this.log_("onDisconnectEvents");var t=this.generateServerValues(),n=[];resolveDeferredValueTree(this.onDisconnect_,t).forEachTree(Path.Empty,function(t,r){n=n.concat(e.serverSyncTree_.applyServerOverwrite(t,r));var i=e.abortTransactions_(t);e.rerunTransactions_(i)}),this.onDisconnect_=new SparseSnapshotTree,this.eventQueue_.raiseEventsForChangedPath(Path.Empty,n)},e.prototype.onDisconnectCancel=function(e,t){var n=this;this.server_.onDisconnectCancel(e.toString(),function(r,i){"ok"===r&&n.onDisconnect_.forget(e),n.callOnCompleteCallback(t,r,i)})},e.prototype.onDisconnectSet=function(e,t,n){var r=this,i=nodeFromJSON$1(t);this.server_.onDisconnectPut(e.toString(),i.val(!0),function(t,o){"ok"===t&&r.onDisconnect_.remember(e,i),r.callOnCompleteCallback(n,t,o)})},e.prototype.onDisconnectSetWithPriority=function(e,t,n,r){var i=this,o=nodeFromJSON$1(t,n);this.server_.onDisconnectPut(e.toString(),o.val(!0),function(t,n){"ok"===t&&i.onDisconnect_.remember(e,o),i.callOnCompleteCallback(r,t,n)})},e.prototype.onDisconnectUpdate=function(e,t,n){var r=this;if(isEmpty(t))return log("onDisconnect().update() called with empty data. Don't do anything."),void this.callOnCompleteCallback(n,"ok");this.server_.onDisconnectMerge(e.toString(),t,function(i,o){"ok"===i&&forEach(t,function(t,n){var i=nodeFromJSON$1(n);r.onDisconnect_.remember(e.child(t),i)}),r.callOnCompleteCallback(n,i,o)})},e.prototype.addEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.infoSyncTree_.addEventRegistration(e,t):this.serverSyncTree_.addEventRegistration(e,t),this.eventQueue_.raiseEventsAtPath(e.path,n)},e.prototype.removeEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.infoSyncTree_.removeEventRegistration(e,t):this.serverSyncTree_.removeEventRegistration(e,t),this.eventQueue_.raiseEventsAtPath(e.path,n)},e.prototype.interrupt=function(){this.persistentConnection_&&this.persistentConnection_.interrupt(INTERRUPT_REASON)},e.prototype.resume=function(){this.persistentConnection_&&this.persistentConnection_.resume(INTERRUPT_REASON)},e.prototype.stats=function(e){if(void 0===e&&(e=!1),"undefined"!=typeof console){var t;e?(this.statsListener_||(this.statsListener_=new StatsListener(this.stats_)),t=this.statsListener_.get()):t=this.stats_.get();var n=Object.keys(t).reduce(function(e,t){return Math.max(t.length,e)},0);forEach(t,function(e,t){for(var r=e.length;r<n+2;r++)e+=" ";console.log(e+t)})}},e.prototype.statsIncrementCounter=function(e){this.stats_.incrementCounter(e),this.statsReporter_.includeStat(e)},e.prototype.log_=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n="";this.persistentConnection_&&(n=this.persistentConnection_.id+":"),log.apply(void 0,[n].concat(e))},e.prototype.callOnCompleteCallback=function(e,t,n){e&&exceptionGuard(function(){if("ok"==t)e(null);else{var r=(t||"error").toUpperCase(),i=r;n&&(i+=": "+n);var o=new Error(i);o.code=r,e(o)}})},Object.defineProperty(e.prototype,"database",{get:function(){return this.__database||(this.__database=new Database(this))},enumerable:!0,configurable:!0}),e}(),RangedFilter=function(){function e(t){this.indexedFilter_=new IndexedFilter(t.getIndex()),this.index_=t.getIndex(),this.startPost_=e.getStartPost_(t),this.endPost_=e.getEndPost_(t)}return e.prototype.getStartPost=function(){return this.startPost_},e.prototype.getEndPost=function(){return this.endPost_},e.prototype.matches=function(e){return this.index_.compare(this.getStartPost(),e)<=0&&this.index_.compare(e,this.getEndPost())<=0},e.prototype.updateChild=function(e,t,n,r,i,o){return this.matches(new NamedNode(t,n))||(n=ChildrenNode.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,o)},e.prototype.updateFullNode=function(e,t,n){t.isLeafNode()&&(t=ChildrenNode.EMPTY_NODE);var r=t.withIndex(this.index_);r=r.updatePriority(ChildrenNode.EMPTY_NODE);var i=this;return t.forEachChild(PRIORITY_INDEX,function(e,t){i.matches(new NamedNode(e,t))||(r=r.updateImmediateChild(e,ChildrenNode.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)},e.prototype.updatePriority=function(e,t){return e},e.prototype.filtersNodes=function(){return!0},e.prototype.getIndexedFilter=function(){return this.indexedFilter_},e.prototype.getIndex=function(){return this.index_},e.getStartPost_=function(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()},e.getEndPost_=function(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()},e}(),LimitedFilter=function(){function e(e){this.rangedFilter_=new RangedFilter(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft()}return e.prototype.updateChild=function(e,t,n,r,i,o){return this.rangedFilter_.matches(new NamedNode(t,n))||(n=ChildrenNode.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,o):this.fullLimitUpdateChild_(e,t,n,i,o)},e.prototype.updateFullNode=function(e,t,n){var r;if(t.isLeafNode()||t.isEmpty())r=ChildrenNode.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){r=ChildrenNode.EMPTY_NODE.withIndex(this.index_);var i=void 0;i=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);for(var o=0;i.hasNext()&&o<this.limit_;){var a=i.getNext();if(!(this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),a)<=0:this.index_.compare(a,this.rangedFilter_.getEndPost())<=0))break;r=r.updateImmediateChild(a.name,a.node),o++}}else{r=(r=t.withIndex(this.index_)).updatePriority(ChildrenNode.EMPTY_NODE);var s=void 0,u=void 0,c=void 0;i=void 0;if(this.reverse_){i=r.getReverseIterator(this.index_),s=this.rangedFilter_.getEndPost(),u=this.rangedFilter_.getStartPost();var h=this.index_.getCompare();c=function(e,t){return h(t,e)}}else i=r.getIterator(this.index_),s=this.rangedFilter_.getStartPost(),u=this.rangedFilter_.getEndPost(),c=this.index_.getCompare();o=0;for(var l=!1;i.hasNext();){a=i.getNext();!l&&c(s,a)<=0&&(l=!0),l&&o<this.limit_&&c(a,u)<=0?o++:r=r.updateImmediateChild(a.name,ChildrenNode.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)},e.prototype.updatePriority=function(e,t){return e},e.prototype.filtersNodes=function(){return!0},e.prototype.getIndexedFilter=function(){return this.rangedFilter_.getIndexedFilter()},e.prototype.getIndex=function(){return this.index_},e.prototype.fullLimitUpdateChild_=function(e,t,n,r,i){var o;if(this.reverse_){var a=this.index_.getCompare();o=function(e,t){return a(t,e)}}else o=this.index_.getCompare();var s=e;assert(s.numChildren()==this.limit_,"");var u=new NamedNode(t,n),c=this.reverse_?s.getFirstChild(this.index_):s.getLastChild(this.index_),h=this.rangedFilter_.matches(u);if(s.hasChild(t)){for(var l=s.getImmediateChild(t),d=r.getChildAfterChild(this.index_,c,this.reverse_);null!=d&&(d.name==t||s.hasChild(d.name));)d=r.getChildAfterChild(this.index_,d,this.reverse_);var f=null==d?1:o(d,u);if(h&&!n.isEmpty()&&f>=0)return null!=i&&i.trackChildChange(Change.childChangedChange(t,n,l)),s.updateImmediateChild(t,n);null!=i&&i.trackChildChange(Change.childRemovedChange(t,l));var p=s.updateImmediateChild(t,ChildrenNode.EMPTY_NODE);return null!=d&&this.rangedFilter_.matches(d)?(null!=i&&i.trackChildChange(Change.childAddedChange(d.name,d.node)),p.updateImmediateChild(d.name,d.node)):p}return n.isEmpty()?e:h&&o(c,u)>=0?(null!=i&&(i.trackChildChange(Change.childRemovedChange(c.name,c.node)),i.trackChildChange(Change.childAddedChange(t,n))),s.updateImmediateChild(t,n).updateImmediateChild(c.name,ChildrenNode.EMPTY_NODE)):e},e}(),QueryParams=function(){function e(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=PRIORITY_INDEX}return e.prototype.hasStart=function(){return this.startSet_},e.prototype.isViewFromLeft=function(){return""===this.viewFrom_?this.startSet_:this.viewFrom_===e.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT},e.prototype.getIndexStartValue=function(){return assert(this.startSet_,"Only valid if start has been set"),this.indexStartValue_},e.prototype.getIndexStartName=function(){return assert(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:MIN_NAME},e.prototype.hasEnd=function(){return this.endSet_},e.prototype.getIndexEndValue=function(){return assert(this.endSet_,"Only valid if end has been set"),this.indexEndValue_},e.prototype.getIndexEndName=function(){return assert(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:MAX_NAME},e.prototype.hasLimit=function(){return this.limitSet_},e.prototype.hasAnchoredLimit=function(){return this.limitSet_&&""!==this.viewFrom_},e.prototype.getLimit=function(){return assert(this.limitSet_,"Only valid if limit has been set"),this.limit_},e.prototype.getIndex=function(){return this.index_},e.prototype.copy_=function(){var t=new e;return t.limitSet_=this.limitSet_,t.limit_=this.limit_,t.startSet_=this.startSet_,t.indexStartValue_=this.indexStartValue_,t.startNameSet_=this.startNameSet_,t.indexStartName_=this.indexStartName_,t.endSet_=this.endSet_,t.indexEndValue_=this.indexEndValue_,t.endNameSet_=this.endNameSet_,t.indexEndName_=this.indexEndName_,t.index_=this.index_,t.viewFrom_=this.viewFrom_,t},e.prototype.limit=function(e){var t=this.copy_();return t.limitSet_=!0,t.limit_=e,t.viewFrom_="",t},e.prototype.limitToFirst=function(t){var n=this.copy_();return n.limitSet_=!0,n.limit_=t,n.viewFrom_=e.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT,n},e.prototype.limitToLast=function(t){var n=this.copy_();return n.limitSet_=!0,n.limit_=t,n.viewFrom_=e.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT,n},e.prototype.startAt=function(e,t){var n=this.copy_();return n.startSet_=!0,void 0===e&&(e=null),n.indexStartValue_=e,null!=t?(n.startNameSet_=!0,n.indexStartName_=t):(n.startNameSet_=!1,n.indexStartName_=""),n},e.prototype.endAt=function(e,t){var n=this.copy_();return n.endSet_=!0,void 0===e&&(e=null),n.indexEndValue_=e,void 0!==t?(n.endNameSet_=!0,n.indexEndName_=t):(n.endNameSet_=!1,n.indexEndName_=""),n},e.prototype.orderBy=function(e){var t=this.copy_();return t.index_=e,t},e.prototype.getQueryObject=function(){var t=e.WIRE_PROTOCOL_CONSTANTS_,n={};if(this.startSet_&&(n[t.INDEX_START_VALUE]=this.indexStartValue_,this.startNameSet_&&(n[t.INDEX_START_NAME]=this.indexStartName_)),this.endSet_&&(n[t.INDEX_END_VALUE]=this.indexEndValue_,this.endNameSet_&&(n[t.INDEX_END_NAME]=this.indexEndName_)),this.limitSet_){n[t.LIMIT]=this.limit_;var r=this.viewFrom_;""===r&&(r=this.isViewFromLeft()?t.VIEW_FROM_LEFT:t.VIEW_FROM_RIGHT),n[t.VIEW_FROM]=r}return this.index_!==PRIORITY_INDEX&&(n[t.INDEX]=this.index_.toString()),n},e.prototype.loadsAllData=function(){return!(this.startSet_||this.endSet_||this.limitSet_)},e.prototype.isDefault=function(){return this.loadsAllData()&&this.index_==PRIORITY_INDEX},e.prototype.getNodeFilter=function(){return this.loadsAllData()?new IndexedFilter(this.getIndex()):this.hasLimit()?new LimitedFilter(this):new RangedFilter(this)},e.prototype.toRestQueryStringParameters=function(){var t,n=e.REST_QUERY_CONSTANTS_,r={};return this.isDefault()?r:(this.index_===PRIORITY_INDEX?t=n.PRIORITY_INDEX:this.index_===VALUE_INDEX?t=n.VALUE_INDEX:this.index_===KEY_INDEX?t=n.KEY_INDEX:(assert(this.index_ instanceof PathIndex,"Unrecognized index type!"),t=this.index_.toString()),r[n.ORDER_BY]=stringify(t),this.startSet_&&(r[n.START_AT]=stringify(this.indexStartValue_),this.startNameSet_&&(r[n.START_AT]+=","+stringify(this.indexStartName_))),this.endSet_&&(r[n.END_AT]=stringify(this.indexEndValue_),this.endNameSet_&&(r[n.END_AT]+=","+stringify(this.indexEndName_))),this.limitSet_&&(this.isViewFromLeft()?r[n.LIMIT_TO_FIRST]=this.limit_:r[n.LIMIT_TO_LAST]=this.limit_),r)},e.WIRE_PROTOCOL_CONSTANTS_={INDEX_START_VALUE:"sp",INDEX_START_NAME:"sn",INDEX_END_VALUE:"ep",INDEX_END_NAME:"en",LIMIT:"l",VIEW_FROM:"vf",VIEW_FROM_LEFT:"l",VIEW_FROM_RIGHT:"r",INDEX:"i"},e.REST_QUERY_CONSTANTS_={ORDER_BY:"orderBy",PRIORITY_INDEX:"$priority",VALUE_INDEX:"$value",KEY_INDEX:"$key",START_AT:"startAt",END_AT:"endAt",LIMIT_TO_FIRST:"limitToFirst",LIMIT_TO_LAST:"limitToLast"},e.DEFAULT=new e,e}(),Reference=function(e){function t(t,n){if(!(t instanceof Repo))throw new Error("new Reference() no longer supported - use app.database().");return e.call(this,t,n,QueryParams.DEFAULT,!1)||this}return __extends(t,e),t.prototype.getKey=function(){return validateArgCount("Reference.key",0,0,arguments.length),this.path.isEmpty()?null:this.path.getBack()},t.prototype.child=function(e){return validateArgCount("Reference.child",1,1,arguments.length),"number"==typeof e?e=String(e):e instanceof Path||(null===this.path.getFront()?validateRootPathString("Reference.child",1,e,!1):validatePathString("Reference.child",1,e,!1)),new t(this.repo,this.path.child(e))},t.prototype.getParent=function(){validateArgCount("Reference.parent",0,0,arguments.length);var e=this.path.parent();return null===e?null:new t(this.repo,e)},t.prototype.getRoot=function(){validateArgCount("Reference.root",0,0,arguments.length);for(var e=this;null!==e.getParent();)e=e.getParent();return e},t.prototype.databaseProp=function(){return this.repo.database},t.prototype.set=function(e,t){validateArgCount("Reference.set",1,2,arguments.length),validateWritablePath("Reference.set",this.path),validateFirebaseDataArg("Reference.set",1,e,this.path,!1),validateCallback("Reference.set",2,t,!0);var n=new Deferred;return this.repo.setWithPriority(this.path,e,null,n.wrapCallback(t)),n.promise},t.prototype.update=function(e,t){if(validateArgCount("Reference.update",1,2,arguments.length),validateWritablePath("Reference.update",this.path),Array.isArray(e)){for(var n={},r=0;r<e.length;++r)n[""+r]=e[r];e=n,warn("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}validateFirebaseMergeDataArg("Reference.update",1,e,this.path,!1),validateCallback("Reference.update",2,t,!0);var i=new Deferred;return this.repo.update(this.path,e,i.wrapCallback(t)),i.promise},t.prototype.setWithPriority=function(e,t,n){if(validateArgCount("Reference.setWithPriority",2,3,arguments.length),validateWritablePath("Reference.setWithPriority",this.path),validateFirebaseDataArg("Reference.setWithPriority",1,e,this.path,!1),validatePriority("Reference.setWithPriority",2,t,!1),validateCallback("Reference.setWithPriority",3,n,!0),".length"===this.getKey()||".keys"===this.getKey())throw"Reference.setWithPriority failed: "+this.getKey()+" is a read-only object.";var r=new Deferred;return this.repo.setWithPriority(this.path,e,t,r.wrapCallback(n)),r.promise},t.prototype.remove=function(e){return validateArgCount("Reference.remove",0,1,arguments.length),validateWritablePath("Reference.remove",this.path),validateCallback("Reference.remove",1,e,!0),this.set(null,e)},t.prototype.transaction=function(e,t,n){if(validateArgCount("Reference.transaction",1,3,arguments.length),validateWritablePath("Reference.transaction",this.path),validateCallback("Reference.transaction",1,e,!1),validateCallback("Reference.transaction",2,t,!0),validateBoolean("Reference.transaction",3,n,!0),".length"===this.getKey()||".keys"===this.getKey())throw"Reference.transaction failed: "+this.getKey()+" is a read-only object.";void 0===n&&(n=!0);var r=new Deferred;"function"==typeof t&&r.promise.catch(function(){});return this.repo.startTransaction(this.path,e,function(e,n,i){e?r.reject(e):r.resolve(new TransactionResult(n,i)),"function"==typeof t&&t(e,n,i)},n),r.promise},t.prototype.setPriority=function(e,t){validateArgCount("Reference.setPriority",1,2,arguments.length),validateWritablePath("Reference.setPriority",this.path),validatePriority("Reference.setPriority",1,e,!1),validateCallback("Reference.setPriority",2,t,!0);var n=new Deferred;return this.repo.setWithPriority(this.path.child(".priority"),e,null,n.wrapCallback(t)),n.promise},t.prototype.push=function(e,t){validateArgCount("Reference.push",0,2,arguments.length),validateWritablePath("Reference.push",this.path),validateFirebaseDataArg("Reference.push",1,e,this.path,!0),validateCallback("Reference.push",2,t,!0);var n,r=this.repo.serverTime(),i=nextPushId(r),o=this.child(i),a=this.child(i);return n=null!=e?o.set(e,t).then(function(){return a}):Promise.resolve(a),o.then=n.then.bind(n),o.catch=n.then.bind(n,void 0),"function"==typeof t&&n.catch(function(){}),o},t.prototype.onDisconnect=function(){return validateWritablePath("Reference.onDisconnect",this.path),new OnDisconnect(this.repo,this.path)},Object.defineProperty(t.prototype,"database",{get:function(){return this.databaseProp()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"key",{get:function(){return this.getKey()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return this.getParent()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){return this.getRoot()},enumerable:!0,configurable:!0}),t}(Query);Query.__referenceConstructor=Reference,SyncPoint.__referenceConstructor=Reference;var TreeNode=function(){return function(){this.children={},this.childCount=0,this.value=null}}(),Tree=function(){function e(e,t,n){void 0===e&&(e=""),void 0===t&&(t=null),void 0===n&&(n=new TreeNode),this.name_=e,this.parent_=t,this.node_=n}return e.prototype.subTree=function(t){for(var n,r=t instanceof Path?t:new Path(t),i=this;null!==(n=r.getFront());){i=new e(n,i,safeGet(i.node_.children,n)||new TreeNode),r=r.popFront()}return i},e.prototype.getValue=function(){return this.node_.value},e.prototype.setValue=function(e){assert(void 0!==e,"Cannot set value to undefined"),this.node_.value=e,this.updateParents_()},e.prototype.clear=function(){this.node_.value=null,this.node_.children={},this.node_.childCount=0,this.updateParents_()},e.prototype.hasChildren=function(){return this.node_.childCount>0},e.prototype.isEmpty=function(){return null===this.getValue()&&!this.hasChildren()},e.prototype.forEachChild=function(t){var n=this;forEach(this.node_.children,function(r,i){t(new e(r,n,i))})},e.prototype.forEachDescendant=function(e,t,n){t&&!n&&e(this),this.forEachChild(function(t){t.forEachDescendant(e,!0,n)}),t&&n&&e(this)},e.prototype.forEachAncestor=function(e,t){for(var n=t?this:this.parent();null!==n;){if(e(n))return!0;n=n.parent()}return!1},e.prototype.forEachImmediateDescendantWithValue=function(e){this.forEachChild(function(t){null!==t.getValue()?e(t):t.forEachImmediateDescendantWithValue(e)})},e.prototype.path=function(){return new Path(null===this.parent_?this.name_:this.parent_.path()+"/"+this.name_)},e.prototype.name=function(){return this.name_},e.prototype.parent=function(){return this.parent_},e.prototype.updateParents_=function(){null!==this.parent_&&this.parent_.updateChild_(this.name_,this)},e.prototype.updateChild_=function(e,t){var n=t.isEmpty(),r=contains(this.node_.children,e);n&&r?(delete this.node_.children[e],this.node_.childCount--,this.updateParents_()):n||r||(this.node_.children[e]=t.node_,this.node_.childCount++,this.updateParents_())},e}(),TransactionStatus;!function(e){e[e.RUN=0]="RUN",e[e.SENT=1]="SENT",e[e.COMPLETED=2]="COMPLETED",e[e.SENT_NEEDS_ABORT=3]="SENT_NEEDS_ABORT",e[e.NEEDS_ABORT=4]="NEEDS_ABORT"}(TransactionStatus||(TransactionStatus={})),Repo.MAX_TRANSACTION_RETRIES_=25,Repo.prototype.transactions_init_=function(){this.transactionQueueTree_=new Tree},Repo.prototype.startTransaction=function(e,t,n,r){this.log_("transaction on "+e);var i=function(){},o=new Reference(this,e);o.on("value",i);var a={path:e,update:t,onComplete:n,status:null,order:LUIDGenerator(),applyLocally:r,retryCount:0,unwatcher:function(){o.off("value",i)},abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},s=this.getLatestState_(e);a.currentInputSnapshot=s;var u=a.update(s.val());if(void 0===u){if(a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete){var c=new DataSnapshot(a.currentInputSnapshot,new Reference(this,a.path),PRIORITY_INDEX);a.onComplete(null,!1,c)}}else{validateFirebaseData("transaction failed: Data returned ",u,a.path),a.status=TransactionStatus.RUN;var h=this.transactionQueueTree_.subTree(e),l=h.getValue()||[];l.push(a),h.setValue(l);var d=void 0;if("object"==typeof u&&null!==u&&contains(u,".priority"))d=safeGet(u,".priority"),assert(isValidPriority(d),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else d=(this.serverSyncTree_.calcCompleteEventCache(e)||ChildrenNode.EMPTY_NODE).getPriority().val();d=d;var f=this.generateServerValues(),p=nodeFromJSON$1(u,d),m=resolveDeferredValueSnapshot(p,f);a.currentOutputSnapshotRaw=p,a.currentOutputSnapshotResolved=m,a.currentWriteId=this.getNextWriteId_();var y=this.serverSyncTree_.applyUserOverwrite(e,m,a.currentWriteId,a.applyLocally);this.eventQueue_.raiseEventsForChangedPath(e,y),this.sendReadyTransactions_()}},Repo.prototype.getLatestState_=function(e,t){return this.serverSyncTree_.calcCompleteEventCache(e,t)||ChildrenNode.EMPTY_NODE},Repo.prototype.sendReadyTransactions_=function(e){var t=this;if(void 0===e&&(e=this.transactionQueueTree_),e||this.pruneCompletedTransactionsBelowNode_(e),null!==e.getValue()){var n=this.buildTransactionQueue_(e);assert(n.length>0,"Sending zero length transaction queue"),n.every(function(e){return e.status===TransactionStatus.RUN})&&this.sendTransactionQueue_(e.path(),n)}else e.hasChildren()&&e.forEachChild(function(e){t.sendReadyTransactions_(e)})},Repo.prototype.sendTransactionQueue_=function(e,t){for(var n=this,r=t.map(function(e){return e.currentWriteId}),i=this.getLatestState_(e,r),o=i,a=i.hash(),s=0;s<t.length;s++){var u=t[s];assert(u.status===TransactionStatus.RUN,"tryToSendTransactionQueue_: items in queue should all be run."),u.status=TransactionStatus.SENT,u.retryCount++;var c=Path.relativePath(e,u.path);o=o.updateChild(c,u.currentOutputSnapshotRaw)}var h=o.val(!0),l=e;this.server_.put(l.toString(),h,function(r){n.log_("transaction put response",{path:l.toString(),status:r});var i=[];if("ok"===r){for(var o=[],a=0;a<t.length;a++){if(t[a].status=TransactionStatus.COMPLETED,i=i.concat(n.serverSyncTree_.ackUserWrite(t[a].currentWriteId)),t[a].onComplete){var s=t[a].currentOutputSnapshotResolved,u=new Reference(n,t[a].path),c=new DataSnapshot(s,u,PRIORITY_INDEX);o.push(t[a].onComplete.bind(null,null,!0,c))}t[a].unwatcher()}n.pruneCompletedTransactionsBelowNode_(n.transactionQueueTree_.subTree(e)),n.sendReadyTransactions_(),n.eventQueue_.raiseEventsForChangedPath(e,i);for(a=0;a<o.length;a++)exceptionGuard(o[a])}else{if("datastale"===r)for(a=0;a<t.length;a++)t[a].status===TransactionStatus.SENT_NEEDS_ABORT?t[a].status=TransactionStatus.NEEDS_ABORT:t[a].status=TransactionStatus.RUN;else{warn("transaction at "+l.toString()+" failed: "+r);for(a=0;a<t.length;a++)t[a].status=TransactionStatus.NEEDS_ABORT,t[a].abortReason=r}n.rerunTransactions_(e)}},a)},Repo.prototype.rerunTransactions_=function(e){var t=this.getAncestorTransactionNode_(e),n=t.path(),r=this.buildTransactionQueue_(t);return this.rerunTransactionQueue_(r,n),n},Repo.prototype.rerunTransactionQueue_=function(e,t){if(0!==e.length){for(var n,r=[],i=[],o=e.filter(function(e){return e.status===TransactionStatus.RUN}).map(function(e){return e.currentWriteId}),a=0;a<e.length;a++){var s=e[a],u=Path.relativePath(t,s.path),c=!1,h=void 0;if(assert(null!==u,"rerunTransactionsUnderNode_: relativePath should not be null."),s.status===TransactionStatus.NEEDS_ABORT)c=!0,h=s.abortReason,i=i.concat(this.serverSyncTree_.ackUserWrite(s.currentWriteId,!0));else if(s.status===TransactionStatus.RUN)if(s.retryCount>=Repo.MAX_TRANSACTION_RETRIES_)c=!0,h="maxretry",i=i.concat(this.serverSyncTree_.ackUserWrite(s.currentWriteId,!0));else{var l=this.getLatestState_(s.path,o);s.currentInputSnapshot=l;var d=e[a].update(l.val());if(void 0!==d){validateFirebaseData("transaction failed: Data returned ",d,s.path);var f=nodeFromJSON$1(d);"object"==typeof d&&null!=d&&contains(d,".priority")||(f=f.updatePriority(l.getPriority()));var p=s.currentWriteId,m=this.generateServerValues(),y=resolveDeferredValueSnapshot(f,m);s.currentOutputSnapshotRaw=f,s.currentOutputSnapshotResolved=y,s.currentWriteId=this.getNextWriteId_(),o.splice(o.indexOf(p),1),i=(i=i.concat(this.serverSyncTree_.applyUserOverwrite(s.path,y,s.currentWriteId,s.applyLocally))).concat(this.serverSyncTree_.ackUserWrite(p,!0))}else c=!0,h="nodata",i=i.concat(this.serverSyncTree_.ackUserWrite(s.currentWriteId,!0))}if(this.eventQueue_.raiseEventsForChangedPath(t,i),i=[],c&&(e[a].status=TransactionStatus.COMPLETED,n=e[a].unwatcher,setTimeout(n,Math.floor(0)),e[a].onComplete))if("nodata"===h){var g=new Reference(this,e[a].path),v=e[a].currentInputSnapshot,_=new DataSnapshot(v,g,PRIORITY_INDEX);r.push(e[a].onComplete.bind(null,null,!1,_))}else r.push(e[a].onComplete.bind(null,new Error(h),!1,null))}this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);for(a=0;a<r.length;a++)exceptionGuard(r[a]);this.sendReadyTransactions_()}},Repo.prototype.getAncestorTransactionNode_=function(e){for(var t,n=this.transactionQueueTree_;null!==(t=e.getFront())&&null===n.getValue();)n=n.subTree(t),e=e.popFront();return n},Repo.prototype.buildTransactionQueue_=function(e){var t=[];return this.aggregateTransactionQueuesForNode_(e,t),t.sort(function(e,t){return e.order-t.order}),t},Repo.prototype.aggregateTransactionQueuesForNode_=function(e,t){var n=this,r=e.getValue();if(null!==r)for(var i=0;i<r.length;i++)t.push(r[i]);e.forEachChild(function(e){n.aggregateTransactionQueuesForNode_(e,t)})},Repo.prototype.pruneCompletedTransactionsBelowNode_=function(e){var t=this,n=e.getValue();if(n){for(var r=0,i=0;i<n.length;i++)n[i].status!==TransactionStatus.COMPLETED&&(n[r]=n[i],r++);n.length=r,e.setValue(n.length>0?n:null)}e.forEachChild(function(e){t.pruneCompletedTransactionsBelowNode_(e)})},Repo.prototype.abortTransactions_=function(e){var t=this,n=this.getAncestorTransactionNode_(e).path(),r=this.transactionQueueTree_.subTree(e);return r.forEachAncestor(function(e){t.abortTransactionsOnNode_(e)}),this.abortTransactionsOnNode_(r),r.forEachDescendant(function(e){t.abortTransactionsOnNode_(e)}),n},Repo.prototype.abortTransactionsOnNode_=function(e){var t=e.getValue();if(null!==t){for(var n=[],r=[],i=-1,o=0;o<t.length;o++)if(t[o].status===TransactionStatus.SENT_NEEDS_ABORT);else if(t[o].status===TransactionStatus.SENT)assert(i===o-1,"All SENT items should be at beginning of queue."),i=o,t[o].status=TransactionStatus.SENT_NEEDS_ABORT,t[o].abortReason="set";else if(assert(t[o].status===TransactionStatus.RUN,"Unexpected transaction status in abort"),t[o].unwatcher(),r=r.concat(this.serverSyncTree_.ackUserWrite(t[o].currentWriteId,!0)),t[o].onComplete){n.push(t[o].onComplete.bind(null,new Error("set"),!1,null))}-1===i?e.setValue(null):t.length=i+1,this.eventQueue_.raiseEventsForChangedPath(e.path(),r);for(o=0;o<n.length;o++)exceptionGuard(n[o])}};var DATABASE_URL_OPTION="databaseURL",_staticInstance,RepoManager=function(){function e(){this.repos_={},this.useRestClient_=!1}return e.getInstance=function(){return _staticInstance||(_staticInstance=new e),_staticInstance},e.prototype.interrupt=function(){for(var e in this.repos_)for(var t in this.repos_[e])this.repos_[e][t].interrupt()},e.prototype.resume=function(){for(var e in this.repos_)for(var t in this.repos_[e])this.repos_[e][t].resume()},e.prototype.databaseFromApp=function(e,t){var n=t||e.options[DATABASE_URL_OPTION];void 0===n&&fatal("Can't determine Firebase Database URL. Be sure to include "+DATABASE_URL_OPTION+" option when calling firebase.initializeApp().");var r=parseRepoInfo(n),i=r.repoInfo;return validateUrl("Invalid Firebase Database URL",1,r),r.path.isEmpty()||fatal("Database URL must point to the root of a Firebase Database (not including a child path)."),this.createRepo(i,e).database},e.prototype.deleteRepo=function(e){var t=safeGet(this.repos_,e.app.name);t&&safeGet(t,e.repoInfo_.toURLString())===e||fatal("Database "+e.app.name+"("+e.repoInfo_+") has already been deleted."),e.interrupt(),delete t[e.repoInfo_.toURLString()]},e.prototype.createRepo=function(e,t){var n=safeGet(this.repos_,t.name);n||(n={},this.repos_[t.name]=n);var r=safeGet(n,e.toURLString());return r&&fatal("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new Repo(e,this.useRestClient_,t),n[e.toURLString()]=r,r},e.prototype.forceRestClient=function(e){this.useRestClient_=e},e}(),Database=function(){function e(e){this.repo_=e,e instanceof Repo||fatal("Don't call new Database() directly - please use firebase.database()."),this.root_=new Reference(e,Path.Empty),this.INTERNAL=new DatabaseInternals(this)}return Object.defineProperty(e.prototype,"app",{get:function(){return this.repo_.app},enumerable:!0,configurable:!0}),e.prototype.ref=function(e){return this.checkDeleted_("ref"),validateArgCount("database.ref",0,1,arguments.length),e instanceof Reference?this.refFromURL(e.toString()):void 0!==e?this.root_.child(e):this.root_},e.prototype.refFromURL=function(e){var t="database.refFromURL";this.checkDeleted_(t),validateArgCount(t,1,1,arguments.length);var n=parseRepoInfo(e);validateUrl(t,1,n);var r=n.repoInfo;return r.host!==this.repo_.repoInfo_.host&&fatal(t+": Host name does not match the current database: (found "+r.host+" but expected "+this.repo_.repoInfo_.host+")"),this.ref(n.path.toString())},e.prototype.checkDeleted_=function(e){null===this.repo_&&fatal("Cannot call "+e+" on a deleted database.")},e.prototype.goOffline=function(){validateArgCount("database.goOffline",0,0,arguments.length),this.checkDeleted_("goOffline"),this.repo_.interrupt()},e.prototype.goOnline=function(){validateArgCount("database.goOnline",0,0,arguments.length),this.checkDeleted_("goOnline"),this.repo_.resume()},e.ServerValue={TIMESTAMP:{".sv":"timestamp"}},e}(),DatabaseInternals=function(){function e(e){this.database=e}return e.prototype.delete=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.database.checkDeleted_("delete"),RepoManager.getInstance().deleteRepo(this.database.repo_),this.database.repo_=null,this.database.root_=null,this.database.INTERNAL=null,this.database=null,[2]})})},e}(),forceLongPolling=function(){WebSocketConnection.forceDisallow(),BrowserPollConnection.forceAllow()},forceWebSockets=function(){BrowserPollConnection.forceDisallow()},isWebSocketsAvailable=function(){return WebSocketConnection.isAvailable()},setSecurityDebugCallback=function(e,t){e.repo.persistentConnection_.securityDebugCallback_=t},stats=function(e,t){e.repo.stats(t)},statsIncrementCounter=function(e,t){e.repo.statsIncrementCounter(t)},dataUpdateCount=function(e){return e.repo.dataUpdateCount},interceptServerData=function(e,t){return e.repo.interceptServerData_(t)},INTERNAL=Object.freeze({forceLongPolling:forceLongPolling,forceWebSockets:forceWebSockets,isWebSocketsAvailable:isWebSocketsAvailable,setSecurityDebugCallback:setSecurityDebugCallback,stats:stats,statsIncrementCounter:statsIncrementCounter,dataUpdateCount:dataUpdateCount,interceptServerData:interceptServerData}),DataConnection=PersistentConnection;PersistentConnection.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},PersistentConnection.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};var RealTimeConnection=Connection,hijackHash=function(e){var t=PersistentConnection.prototype.put;return PersistentConnection.prototype.put=function(n,r,i,o){void 0!==o&&(o=e()),t.call(this,n,r,i,o)},function(){PersistentConnection.prototype.put=t}},ConnectionTarget=RepoInfo,queryIdentifier=function(e){return e.queryIdentifier()},listens=function(e){return e.repo.persistentConnection_.listens_},forceRestClient=function(e){RepoManager.getInstance().forceRestClient(e)},TEST_ACCESS=Object.freeze({DataConnection:DataConnection,RealTimeConnection:RealTimeConnection,hijackHash:hijackHash,ConnectionTarget:ConnectionTarget,queryIdentifier:queryIdentifier,listens:listens,forceRestClient:forceRestClient}),ServerValue=Database.ServerValue;function registerDatabase(e){var t=e.INTERNAL.registerService("database",function(e,t,n){return RepoManager.getInstance().databaseFromApp(e,n)},{Reference:Reference,Query:Query,Database:Database,enableLogging:enableLogging,INTERNAL:INTERNAL,ServerValue:ServerValue,TEST_ACCESS:TEST_ACCESS},null,!0);isNodeSdk()&&(module.exports=t)}registerDatabase(firebase);var commonjsGlobal="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},e,goog=goog||{},h=commonjsGlobal;function l(e){return"string"==typeof e}function m(e,t){e=e.split("."),t=t||h;for(var n=0;n<e.length;n++)if(null==(t=t[e[n]]))return null;return t}function aa(){}function ba(e){var t=typeof e;if("object"==t){if(!e)return"null";if(e instanceof Array)return"array";if(e instanceof Object)return t;var n=Object.prototype.toString.call(e);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof e.length&&void 0!==e.splice&&void 0!==e.propertyIsEnumerable&&!e.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==e.call&&void 0!==e.propertyIsEnumerable&&!e.propertyIsEnumerable("call"))return"function"}else if("function"==t&&void 0===e.call)return"object";return t}function n(e){return"array"==ba(e)}function ca(e){var t=ba(e);return"array"==t||"object"==t&&"number"==typeof e.length}function q(e){return"function"==ba(e)}function r(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var t="closure_uid_"+(1e9*Math.random()>>>0),da=0;function ea(e,t,n){return e.call.apply(e.bind,arguments)}function fa(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function u(e,t,n){return(u=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?ea:fa).apply(null,arguments)}function v(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}var w=Date.now||function(){return+new Date};function x(e,t){function n(){}n.prototype=t.prototype,e.L=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.sh=function(e,n,r){for(var i=Array(arguments.length-2),o=2;o<arguments.length;o++)i[o-2]=arguments[o];return t.prototype[n].apply(e,i)}}function y(e){if(Error.captureStackTrace)Error.captureStackTrace(this,y);else{var t=Error().stack;t&&(this.stack=t)}e&&(this.message=String(e))}function ha(e,t){for(var n="",r=(e=e.split("%s")).length-1,i=0;i<r;i++)n+=e[i]+(i<t.length?t[i]:"%s");y.call(this,n+e[r])}function ia(e,t){throw new ha("Failure"+(e?": "+e:""),Array.prototype.slice.call(arguments,1))}function z(){0!=ja&&(ka[this[t]||(this[t]=++da)]=this),this.Ka=this.Ka,this.Qa=this.Qa}x(y,Error),y.prototype.name="CustomError",x(ha,y),ha.prototype.name="AssertionError";var ja=0,ka={};z.prototype.Ka=!1,z.prototype.cb=function(){if(!this.Ka&&(this.Ka=!0,this.F(),0!=ja)){var e=this[t]||(this[t]=++da);if(0!=ja&&this.Qa&&0<this.Qa.length)throw Error(this+" did not empty its onDisposeCallbacks queue. This probably means it overrode dispose() or disposeInternal() without calling the superclass' method.");delete ka[e]}},z.prototype.F=function(){if(this.Qa)for(;this.Qa.length;)this.Qa.shift()()};var la=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if(l(e))return l(t)&&1==t.length?e.indexOf(t,0):-1;for(var n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1},ma=Array.prototype.lastIndexOf?function(e,t){return Array.prototype.lastIndexOf.call(e,t,e.length-1)}:function(e,t){var n=e.length-1;if(0>n&&(n=Math.max(0,e.length+n)),l(e))return l(t)&&1==t.length?e.lastIndexOf(t,n):-1;for(;0<=n;n--)if(n in e&&e[n]===t)return n;return-1},na=Array.prototype.forEach?function(e,t,n){Array.prototype.forEach.call(e,t,n)}:function(e,t,n){for(var r=e.length,i=l(e)?e.split(""):e,o=0;o<r;o++)o in i&&t.call(n,i[o],o,e)},oa=Array.prototype.some?function(e,t){return Array.prototype.some.call(e,t,void 0)}:function(e,t){for(var n=e.length,r=l(e)?e.split(""):e,i=0;i<n;i++)if(i in r&&t.call(void 0,r[i],i,e))return!0;return!1};function pa(e){e:{for(var t=qa,n=e.length,r=l(e)?e.split(""):e,i=0;i<n;i++)if(i in r&&t.call(void 0,r[i],i,e)){t=i;break e}t=-1}return 0>t?null:l(e)?e.charAt(t):e[t]}function ra(e){if(!n(e))for(var t=e.length-1;0<=t;t--)delete e[t];e.length=0}function sa(e,t){var n;return(n=0<=(t=la(e,t)))&&Array.prototype.splice.call(e,t,1),n}function ta(e){return Array.prototype.concat.apply([],arguments)}function ua(e){var t=e.length;if(0<t){for(var n=Array(t),r=0;r<t;r++)n[r]=e[r];return n}return[]}function va(e){return/^[\s\xa0]*$/.test(e)}var wa=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]},A;function xa(e,t){return e<t?-1:e>t?1:0}e:{var ya=h.navigator;if(ya){var za=ya.userAgent;if(za){A=za;break e}}A=""}function B(e){return-1!=A.indexOf(e)}function Aa(e,t,n){for(var r in e)t.call(n,e[r],r,e)}function Ba(e){var t,n=[],r=0;for(t in e)n[r++]=e[t];return n}function Ca(e){var t,n=[],r=0;for(t in e)n[r++]=t;return n}function Da(e){var t,n={};for(t in e)n[t]=e[t];return n}var Ea="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Fa(e,t){for(var n,r,i=1;i<arguments.length;i++){for(n in r=arguments[i])e[n]=r[n];for(var o=0;o<Ea.length;o++)n=Ea[o],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function Ga(e){return Ga[" "](e),e}function Ha(e,t){var n=Ia;return Object.prototype.hasOwnProperty.call(n,e)?n[e]:n[e]=t(e)}Ga[" "]=aa;var Ja=B("Opera"),C=B("Trident")||B("MSIE"),Ka=B("Edge"),La=Ka||C,Ma=B("Gecko")&&!(-1!=A.toLowerCase().indexOf("webkit")&&!B("Edge"))&&!(B("Trident")||B("MSIE"))&&!B("Edge"),Na=-1!=A.toLowerCase().indexOf("webkit")&&!B("Edge"),Pa,a;function Oa(){var e=h.document;return e?e.documentMode:void 0}e:{var Qa="",Ra=(a=A,Ma?/rv:([^\);]+)(\)|;)/.exec(a):Ka?/Edge\/([\d\.]+)/.exec(a):C?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a):Na?/WebKit\/(\S+)/.exec(a):Ja?/(?:Version)[ \/]?(\S+)/.exec(a):void 0);if(Ra&&(Qa=Ra?Ra[1]:""),C){var Sa=Oa();if(null!=Sa&&Sa>parseFloat(Qa)){Pa=String(Sa);break e}}Pa=Qa}var Ia={},Ua;function Ta(e){return Ha(e,function(){for(var t=0,n=wa(String(Pa)).split("."),r=wa(String(e)).split("."),i=Math.max(n.length,r.length),o=0;0==t&&o<i;o++){var a=n[o]||"",s=r[o]||"";do{if(a=/(\d*)(\D*)(.*)/.exec(a)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],0==a[0].length&&0==s[0].length)break;t=xa(0==a[1].length?0:parseInt(a[1],10),0==s[1].length?0:parseInt(s[1],10))||xa(0==a[2].length,0==s[2].length)||xa(a[2],s[2]),a=a[3],s=s[3]}while(0==t)}return 0<=t})}var Va=h.document;Ua=Va&&C?Oa()||("CSS1Compat"==Va.compatMode?parseInt(Pa,10):5):void 0;var Wa=Object.freeze||function(e){return e},Xa=!C||9<=Number(Ua),Ya=C&&!Ta("9"),Za=function(){if(!h.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{h.addEventListener("test",aa,t),h.removeEventListener("test",aa,t)}catch(e){}return e}();function D(e,t){this.type=e,this.currentTarget=this.target=t,this.defaultPrevented=this.Ea=!1,this.Ee=!0}function E(e,t){D.call(this,e?e.type:""),this.relatedTarget=this.currentTarget=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=this.offsetY=this.offsetX=0,this.key="",this.charCode=this.keyCode=0,this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.gb=null,e&&this.Of(e,t)}D.prototype.stopPropagation=function(){this.Ea=!0},D.prototype.preventDefault=function(){this.defaultPrevented=!0,this.Ee=!1},x(E,D);var $a=Wa({2:"touch",3:"pen",4:"mouse"});E.prototype.Of=function(e,t){var n=this.type=e.type,r=e.changedTouches?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.currentTarget=t,t=e.relatedTarget){if(Ma){e:{try{Ga(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,null===r?(this.offsetX=Na||void 0!==e.offsetX?e.offsetX:e.layerX,this.offsetY=Na||void 0!==e.offsetY?e.offsetY:e.layerY,this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0):(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0),this.button=e.button,this.keyCode=e.keyCode||0,this.key=e.key||"",this.charCode=e.charCode||("keypress"==n?e.keyCode:0),this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType=l(e.pointerType)?e.pointerType:$a[e.pointerType]||"",this.state=e.state,this.gb=e,e.defaultPrevented&&this.preventDefault()},E.prototype.stopPropagation=function(){E.L.stopPropagation.call(this),this.gb.stopPropagation?this.gb.stopPropagation():this.gb.cancelBubble=!0},E.prototype.preventDefault=function(){E.L.preventDefault.call(this);var e=this.gb;if(e.preventDefault)e.preventDefault();else if(e.returnValue=!1,Ya)try{(e.ctrlKey||112<=e.keyCode&&123>=e.keyCode)&&(e.keyCode=-1)}catch(e){}};var ab="closure_listenable_"+(1e6*Math.random()|0);function F(e){return!(!e||!e[ab])}var bb=0;function cb(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.Pb=i,this.key=++bb,this.Sa=this.Fb=!1}function db(e){this.src=e,this.J={},this.yb=0}function eb(e,t,n,r){for(var i=0;i<e.length;++i){var o=e[i];if(!o.Sa&&o.listener==t&&o.capture==!!n&&o.Pb==r)return i}return-1}cb.prototype.Wb=function(){this.Sa=!0,this.Pb=this.src=this.proxy=this.listener=null},e=db.prototype,e.add=function(e,t,n,r,i){var o=e.toString();(e=this.J[o])||(e=this.J[o]=[],this.yb++);var a=eb(e,t,r,i);return-1<a?(t=e[a],n||(t.Fb=!1)):((t=new cb(t,this.src,o,!!r,i)).Fb=n,e.push(t)),t},e.remove=function(e,t,n,r){if(!((e=e.toString())in this.J))return!1;var i=this.J[e];return-1<(t=eb(i,t,n,r))&&(i[t].Wb(),Array.prototype.splice.call(i,t,1),0==i.length&&(delete this.J[e],this.yb--),!0)},e.Be=function(e){var t=e.type;t in this.J&&sa(this.J[t],e)&&(e.Wb(),0==this.J[t].length&&(delete this.J[t],this.yb--))},e.qb=function(e){var t;for(t in e=e&&e.toString(),this.J)if(!e||t==e){for(var n=this.J[t],r=0;r<n.length;r++)n[r].Wb();delete this.J[t],this.yb--}},e.kb=function(e,t,n,r){var i=-1;return(e=this.J[e.toString()])&&(i=eb(e,t,n,r)),-1<i?e[i]:null};var fb="closure_lm_"+(1e6*Math.random()|0),gb={};function ib(e,t,i,o,a){if(o&&o.once)return jb(e,t,i,o,a);if(n(t)){for(var s=0;s<t.length;s++)ib(e,t[s],i,o,a);return null}return i=kb(i),F(e)?e.ob(t,i,r(o)?!!o.capture:!!o,a):lb(e,t,i,!1,o,a)}function lb(e,t,n,i,o,a){if(!t)throw Error("Invalid event type");var s=r(o)?!!o.capture:!!o,u=G(e);if(u||(e[fb]=u=new db(e)),(n=u.add(t,n,i,s,a)).proxy)return n;if(i=mb(),n.proxy=i,i.src=e,i.listener=n,e.addEventListener)Za||(o=s),void 0===o&&(o=!1),e.addEventListener(t.toString(),i,o);else if(e.attachEvent)e.attachEvent(nb(t.toString()),i);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(i)}return n}function mb(){var e=ob,t=Xa?function(n){return e.call(t.src,t.listener,n)}:function(n){if(!(n=e.call(t.src,t.listener,n)))return n};return t}function jb(e,t,i,o,a){if(n(t)){for(var s=0;s<t.length;s++)jb(e,t[s],i,o,a);return null}return i=kb(i),F(e)?e.Qc(t,i,r(o)?!!o.capture:!!o,a):lb(e,t,i,!0,o,a)}function pb(e,t,i,o,a){if(n(t))for(var s=0;s<t.length;s++)pb(e,t[s],i,o,a);else o=r(o)?!!o.capture:!!o,i=kb(i),F(e)?e.hd(t,i,o,a):e&&(e=G(e))&&(t=e.kb(t,i,o,a))&&qb(t)}function qb(e){if("number"!=typeof e&&e&&!e.Sa){var t=e.src;if(F(t))t.Pe(e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(nb(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=G(t))?(n.Be(e),0==n.yb&&(n.src=null,t[fb]=null)):e.Wb()}}}function nb(e){return e in gb?gb[e]:gb[e]="on"+e}function rb(e,t,n,r){var i=!0;if((e=G(e))&&(t=e.J[t.toString()]))for(t=t.concat(),e=0;e<t.length;e++){var o=t[e];o&&o.capture==n&&!o.Sa&&(o=sb(o,r),i=i&&!1!==o)}return i}function sb(e,t){var n=e.listener,r=e.Pb||e.src;return e.Fb&&qb(e),n.call(r,t)}function ob(e,t){if(e.Sa)return!0;if(!Xa){var n=t||m("window.event");t=new E(n,this);var r=!0;if(!(0>n.keyCode||void 0!=n.returnValue)){e:{var i=!1;if(0==n.keyCode)try{n.keyCode=-1;break e}catch(e){i=!0}(i||void 0==n.returnValue)&&(n.returnValue=!0)}for(n=[],i=t.currentTarget;i;i=i.parentNode)n.push(i);for(e=e.type,i=n.length-1;!t.Ea&&0<=i;i--){t.currentTarget=n[i];var o=rb(n[i],e,!0,t);r=r&&o}for(i=0;!t.Ea&&i<n.length;i++)t.currentTarget=n[i],o=rb(n[i],e,!1,t),r=r&&o}return r}return sb(e,new E(t,this))}function G(e){return(e=e[fb])instanceof db?e:null}var tb="__closure_events_fn_"+(1e9*Math.random()>>>0);function kb(e){return q(e)?e:(e[tb]||(e[tb]=function(t){return e.handleEvent(t)}),e[tb])}function H(){z.call(this),this.ka=new db(this),this.Te=this,this.Wc=null}function ub(e){return!/^\s*$/.test(e)&&/^[\],:{}\s\u2028\u2029]*$/.test(e.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,""))}function vb(a){if(a=String(a),ub(a))try{return eval("("+a+")")}catch(e){}throw Error("Invalid JSON string: "+a)}function I(){this.Ta=void 0}x(H,z),H.prototype[ab]=!0,e=H.prototype,e.addEventListener=function(e,t,n,r){ib(this,e,t,n,r)},e.removeEventListener=function(e,t,n,r){pb(this,e,t,n,r)},e.dispatchEvent=function(e){var t,n=this.Wc;if(n)for(t=[];n;n=n.Wc)t.push(n);n=this.Te;var r=e.type||e;if(l(e))e=new D(e,n);else if(e instanceof D)e.target=e.target||n;else{var i=e;Fa(e=new D(r,n),i)}if(i=!0,t)for(var o=t.length-1;!e.Ea&&0<=o;o--){var a=e.currentTarget=t[o];i=a.Mb(r,!0,e)&&i}if(e.Ea||(i=(a=e.currentTarget=n).Mb(r,!0,e)&&i,e.Ea||(i=a.Mb(r,!1,e)&&i)),t)for(o=0;!e.Ea&&o<t.length;o++)i=(a=e.currentTarget=t[o]).Mb(r,!1,e)&&i;return i},e.F=function(){H.L.F.call(this),this.tg(),this.Wc=null},e.ob=function(e,t,n,r){return this.ka.add(String(e),t,!1,n,r)},e.Qc=function(e,t,n,r){return this.ka.add(String(e),t,!0,n,r)},e.hd=function(e,t,n,r){this.ka.remove(String(e),t,n,r)},e.Pe=function(e){this.ka.Be(e)},e.tg=function(){this.ka&&this.ka.qb(void 0)},e.Mb=function(e,t,n){if(!(e=this.ka.J[String(e)]))return!0;e=e.concat();for(var r=!0,i=0;i<e.length;++i){var o=e[i];if(o&&!o.Sa&&o.capture==t){var a=o.listener,s=o.Pb||o.src;o.Fb&&this.Pe(o),r=!1!==a.call(s,n)&&r}}return r&&0!=n.Ee},e.kb=function(e,t,n,r){return this.ka.kb(String(e),t,n,r)},I.prototype.ec=function(e){var t=[];return this.bd(e,t),t.join("")},I.prototype.bd=function(e,t){if(null==e)t.push("null");else{if("object"==typeof e){if(n(e))return void this.Dg(e,t);if(!(e instanceof String||e instanceof Number||e instanceof Boolean))return void this.Fg(e,t);e=e.valueOf()}switch(typeof e){case"string":this.Ge(e,t);break;case"number":this.Eg(e,t);break;case"boolean":t.push(String(e));break;case"function":t.push("null");break;default:throw Error("Unknown type: "+typeof e)}}};var wb={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\u000b"},xb=/\uffff/.test("")?/[\\"\x00-\x1f\x7f-\uffff]/g:/[\\"\x00-\x1f\x7f-\xff]/g;function yb(e,t){this.Wf=100,this.jf=e,this.xg=t,this.$b=0,this.Qb=null}function J(){this.nc=this.Wa=null}I.prototype.Ge=function(e,t){t.push('"',e.replace(xb,function(e){var t=wb[e];return t||(t="\\u"+(65536|e.charCodeAt(0)).toString(16).substr(1),wb[e]=t),t}),'"')},I.prototype.Eg=function(e,t){t.push(isFinite(e)&&!isNaN(e)?String(e):"null")},I.prototype.Dg=function(e,t){var n=e.length;t.push("[");for(var r="",i=0;i<n;i++)t.push(r),r=e[i],this.bd(this.Ta?this.Ta.call(e,String(i),r):r,t),r=",";t.push("]")},I.prototype.Fg=function(e,t){t.push("{");var n,r="";for(n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var i=e[n];"function"!=typeof i&&(t.push(r),this.Ge(n,t),t.push(":"),this.bd(this.Ta?this.Ta.call(e,n,i):i,t),r=",")}t.push("}")},yb.prototype.get=function(){if(0<this.$b){this.$b--;var e=this.Qb;this.Qb=e.next,e.next=null}else e=this.jf();return e},yb.prototype.put=function(e){this.xg(e),this.$b<this.Wf&&(this.$b++,e.next=this.Qb,this.Qb=e)};var Ab=new yb(function(){return new zb},function(e){e.reset()}),Cb,Eb;function zb(){this.next=this.scope=this.Ic=null}function Bb(e){h.setTimeout(function(){throw e},0)}function Db(){var e=h.MessageChannel;if(void 0===e&&"undefined"!=typeof window&&window.postMessage&&window.addEventListener&&!B("Presto")&&(e=function(){var e=document.createElement("IFRAME");e.style.display="none",e.src="",document.documentElement.appendChild(e);var t=e.contentWindow;(e=t.document).open(),e.write(""),e.close();var n="callImmediate"+Math.random(),r="file:"==t.location.protocol?"*":t.location.protocol+"//"+t.location.host;e=u(function(e){"*"!=r&&e.origin!=r||e.data!=n||this.port1.onmessage()},this),t.addEventListener("message",e,!1),this.port1={},this.port2={postMessage:function(){t.postMessage(n,r)}}}),void 0!==e&&!B("Trident")&&!B("MSIE")){var t=new e,n={},r=n;return t.port1.onmessage=function(){if(void 0!==n.next){var e=(n=n.next).ud;n.ud=null,e()}},function(e){r.next={ud:e},r=r.next,t.port2.postMessage(0)}}return"undefined"!=typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(e){var t=document.createElement("SCRIPT");t.onreadystatechange=function(){t.onreadystatechange=null,t.parentNode.removeChild(t),t=null,e(),e=null},document.documentElement.appendChild(t)}:function(e){h.setTimeout(e,0)}}function Fb(){if(h.Promise&&h.Promise.resolve){var e=h.Promise.resolve(void 0);Eb=function(){e.then(Gb)}}else Eb=function(){var e=Gb;!q(h.setImmediate)||h.Window&&h.Window.prototype&&!B("Edge")&&h.Window.prototype.setImmediate==h.setImmediate?(Cb||(Cb=Db()),Cb(e)):h.setImmediate(e)}}J.prototype.add=function(e,t){var n=this.Ef();n.set(e,t),this.nc?this.nc.next=n:this.Wa=n,this.nc=n},J.prototype.remove=function(){var e=null;return this.Wa&&(e=this.Wa,this.Wa=this.Wa.next,this.Wa||(this.nc=null),e.next=null),e},J.prototype.zg=function(e){Ab.put(e)},J.prototype.Ef=function(){return Ab.get()},zb.prototype.set=function(e,t){this.Ic=e,this.scope=t,this.next=null},zb.prototype.reset=function(){this.next=this.scope=this.Ic=null};var Hb=!1,Ib=new J;function Gb(){for(var e;e=Ib.remove();){try{e.Ic.call(e.scope)}catch(e){Bb(e)}Ib.zg(e)}Hb=!1}function Jb(e,t){H.call(this),this.Na=e||1,this.xb=t||h,this.qd=u(this.Xg,this),this.le=w()}function Kb(e,t,n){if(q(e))n&&(e=u(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=u(e.handleEvent,e)}return 2147483647<Number(t)?-1:h.setTimeout(e,t||0)}function Lb(e,t,n){z.call(this),this.Yf=null!=n?u(e,n):e,this.Na=t,this.af=u(this.jg,this),this.sc=[]}function Mb(e){z.call(this),this.i=e,this.o={}}x(Jb,H),e=Jb.prototype,e.enabled=!1,e.B=null,e.setInterval=function(e){this.Na=e,this.B&&this.enabled?(this.stop(),this.start()):this.B&&this.stop()},e.Xg=function(){if(this.enabled){var e=w()-this.le;0<e&&e<.8*this.Na?this.B=this.xb.setTimeout(this.qd,this.Na-e):(this.B&&(this.xb.clearTimeout(this.B),this.B=null),this.kf(),this.enabled&&(this.stop(),this.start()))}},e.kf=function(){this.dispatchEvent("tick")},e.start=function(){this.enabled=!0,this.B||(this.B=this.xb.setTimeout(this.qd,this.Na),this.le=w())},e.stop=function(){this.enabled=!1,this.B&&(this.xb.clearTimeout(this.B),this.B=null)},e.F=function(){Jb.L.F.call(this),this.stop(),delete this.xb},x(Lb,z),e=Lb.prototype,e.Ua=!1,e.pb=0,e.B=null,e.rf=function(e){this.sc=arguments,this.B||this.pb?this.Ua=!0:this.Ec()},e.stop=function(){this.B&&(h.clearTimeout(this.B),this.B=null,this.Ua=!1,this.sc=[])},e.pause=function(){this.pb++},e.resume=function(){this.pb--,this.pb||!this.Ua||this.B||(this.Ua=!1,this.Ec())},e.F=function(){Lb.L.F.call(this),this.stop()},e.jg=function(){this.B=null,this.Ua&&!this.pb&&(this.Ua=!1,this.Ec())},e.Ec=function(){this.B=Kb(this.af,this.Na),this.Yf.apply(null,this.sc)},x(Mb,z);var Nb=[];function K(e,t,n){this.reset(e,t,n,void 0,void 0)}function Pb(e){this.se=e,this.be=this.wc=this.nb=this.ac=null}function L(e,t){this.name=e,this.value=t}e=Mb.prototype,e.ob=function(e,t,n,r){return this.Xf(e,t,n,r)},e.Xf=function(e,t,r,i){n(t)||(t&&(Nb[0]=t.toString()),t=Nb);for(var o=0;o<t.length;o++){var a=ib(e,t[o],r||this.handleEvent,i||!1,this.i||this);if(!a)break;this.o[a.key]=a}return this},e.Qc=function(e,t,n,r){return this.me(e,t,n,r)},e.me=function(e,t,r,i,o){if(n(t))for(var a=0;a<t.length;a++)this.me(e,t[a],r,i,o);else{if(!(e=jb(e,t,r||this.handleEvent,i,o||this.i||this)))return this;this.o[e.key]=e}return this},e.hd=function(e,t,i,o,a){if(n(t))for(var s=0;s<t.length;s++)this.hd(e,t[s],i,o,a);else i=i||this.handleEvent,o=r(o)?!!o.capture:!!o,a=a||this.i||this,i=kb(i),o=!!o,(t=F(e)?e.kb(t,i,o,a):e&&(e=G(e))?e.kb(t,i,o,a):null)&&(qb(t),delete this.o[t.key])},e.qb=function(){Aa(this.o,function(e,t){this.o.hasOwnProperty(t)&&qb(e)},this),this.o={}},e.F=function(){Mb.L.F.call(this),this.qb()},e.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},K.prototype.Pd=null,K.prototype.reset=function(e,t,n,r,i){this.nb=e,delete this.Pd},K.prototype.Hg=function(e){this.Pd=e},K.prototype.Ke=function(e){this.nb=e},L.prototype.toString=function(){return this.name};var Qb=new L("SEVERE",1e3),Rb=new L("WARNING",900),Sb=new L("INFO",800),Tb=new L("CONFIG",700),Ub=new L("FINE",500);e=Pb.prototype,e.getName=function(){return this.se},e.getParent=function(){return this.ac},e.tf=function(){return this.wc||(this.wc={}),this.wc},e.Ke=function(e){this.nb=e},e.Td=function(){return this.nb?this.nb:this.ac?this.ac.Td():(ia("Root logger has no level set."),null)},e.Tf=function(e){return e.value>=this.Td().value},e.log=function(e,t,n){this.Tf(e)&&(q(t)&&(t=t()),this.lf(this.yf(e,t,n)))},e.yf=function(e,t,n){return e=new K(e,String(t),this.se),n&&e.Hg(n),e},e.ca=function(e,t){this.log(Qb,e,t)},e.T=function(e,t){this.log(Rb,e,t)},e.info=function(e,t){this.log(Sb,e,t)},e.qf=function(e){this.log(Ub,e,void 0)},e.lf=function(e){for(var t=this;t;)t.$e(e),t=t.getParent()},e.$e=function(e){if(this.be)for(var t,n=0;t=this.be[n];n++)t(e)},e.Lg=function(e){this.ac=e},e.Ue=function(e,t){this.tf()[e]=t};var Wb={},Xb=null;function Yb(e){var t;if(Xb||(Xb=new Pb(""),Wb[""]=Xb,Xb.Ke(Tb)),!(t=Wb[e])){t=new Pb(e);var n=e.lastIndexOf("."),r=e.substr(n+1);(n=Yb(e.substr(0,n))).Ue(r,t),t.Lg(n),Wb[e]=t}return t}function Zb(e,t){e&&e.info(t,void 0)}function M(e,t){e&&e.qf(t)}function $b(){this.s=Yb("goog.labs.net.webChannel.WebChannelDebug"),this.Yc=!0}e=$b.prototype,e.Ld=function(){this.Yc=!1},e.Zg=function(e,t,n,r,i){var o=this;this.info(function(){return"XMLHTTP REQ ("+n+") [attempt "+r+"]: "+e+"\n"+t+"\n"+o.ag(i)})},e.$g=function(e,t,n,r,i,o){this.info(function(){return"XMLHTTP RESP ("+n+") [ attempt "+r+"]: "+e+"\n"+t+"\n"+i+" "+o})},e.Xa=function(e,t,n){var r=this;this.info(function(){return"XMLHTTP TEXT ("+e+"): "+r.rg(t)+(n?" "+n:"")})},e.Yg=function(e){this.info(function(){return"TIMEOUT: "+e})},e.debug=function(e){M(this.s,e)},e.eb=function(e,t){var n=this.s;n&&n.ca(t||"Exception",e)},e.info=function(e){Zb(this.s,e)},e.T=function(e){var t=this.s;t&&t.T(e,void 0)},e.ca=function(e){var t=this.s;t&&t.ca(e,void 0)},e.rg=function(e){if(!this.Yc)return e;if(!e)return null;try{var t=JSON.parse(e);if(t)for(var r=0;r<t.length;r++)n(t[r])&&this.$f(t[r]);return(new I).ec(t)}catch(t){return this.debug("Exception parsing expected JS array - probably was not JS"),e}},e.$f=function(e){if(!(2>e.length||(e=e[1],!n(e)||1>e.length))){var t=e[0];if("noop"!=t&&"stop"!=t&&"close"!=t)for(t=1;t<e.length;t++)e[t]=""}},e.ag=function(e){if(!this.Yc)return e;if(!e)return null;var t="";e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].split("=");if(1<r.length){var i=r[0];r=r[1];var o=i.split("_");t=2<=o.length&&"type"==o[1]?t+(i+"=")+r+"&":t+(i+"=redacted&")}}return t};var N=new H;function ac(e){D.call(this,"serverreachability",e)}function O(e){N.dispatchEvent(new ac(N,e))}function bc(e,t){D.call(this,"statevent",e),this.stat=t}function P(e){N.dispatchEvent(new bc(N,e))}function cc(e,t,n){D.call(this,"timingevent",e),this.size=t,this.rtt=n}function dc(e,t,n){N.dispatchEvent(new cc(N,e,t,n))}function Q(e,t){if(!q(e))throw Error("Fn must not be null and must be a function");return h.setTimeout(function(){e()},t)}x(ac,D),x(bc,D),x(cc,D);var ec={NO_ERROR:0,ah:1,ih:2,hh:3,eh:4,gh:5,jh:6,Re:7,TIMEOUT:8,mh:9},fc={dh:"complete",qh:"success",Se:"error",Re:"abort",oh:"ready",ph:"readystatechange",TIMEOUT:"timeout",kh:"incrementaldata",nh:"progress",fh:"downloadprogress",rh:"uploadprogress"};function gc(){}function hc(){}gc.prototype.sd=null,gc.prototype.Yd=function(){return this.sd||(this.sd=this.Qf())};var ic={OPEN:"a",bh:"b",Se:"c",lh:"d"},lc;function jc(){D.call(this,"d")}function kc(){D.call(this,"c")}function mc(){}function R(e,t,n,r,i){this.b=e,this.a=t,this.ra=n,this.R=r,this.Zc=i||1,this.Hc=new Mb(this),this.Va=nc,e=La?125:void 0,this.Xc=new Jb(e),this.A=null,this.S=!1,this.Da=this.pa=this.ua=this.kc=this.rb=this.ld=this.Ga=null,this.ba=[],this.h=null,this.Cb=0,this.I=this.Fa=null,this.w=-1,this.$a=!1,this.Ra=0,this.bc=null,this.mb=this.Hd=this.Ac=!1}x(jc,D),x(kc,D),x(mc,gc),mc.prototype.Gd=function(){var e=this.Zd();return e?new ActiveXObject(e):new XMLHttpRequest},mc.prototype.Qf=function(){var e={};return this.Zd()&&(e[0]=!0,e[1]=!0),e},mc.prototype.Zd=function(){if(!this.ee&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],t=0;t<e.length;t++){var n=e[t];try{return new ActiveXObject(n),this.ee=n}catch(e){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed")}return this.ee},lc=new mc;var nc=45e3;function oc(e,t){switch(e){case 0:return"Non-200 return code ("+t+")";case 1:return"XMLHTTP failure (no data)";case 2:return"HttpConnection timeout";default:return"Unknown error"}}var pc={},qc={};function rc(e){if(e.H&&"function"==typeof e.H)return e.H();if(l(e))return e.split("");if(ca(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}return Ba(e)}function sc(e,t,n){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,n);else if(ca(e)||l(e))na(e,t,n);else{if(e.W&&"function"==typeof e.W)var r=e.W();else if(e.H&&"function"==typeof e.H)r=void 0;else if(ca(e)||l(e)){r=[];for(var i=e.length,o=0;o<i;o++)r.push(o)}else r=Ca(e);o=(i=rc(e)).length;for(var a=0;a<o;a++)t.call(n,i[a],r&&r[a],e)}}function S(e,t){this.D={},this.o=[],this.j=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else e&&this.addAll(e)}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e=R.prototype,e.ga=function(e){this.A=e},e.setTimeout=function(e){this.Va=e},e.Le=function(e){this.Ra=e},e.Mg=function(e){this.ba=e},e.la=function(){return this.ba},e.nd=function(e,t){this.kc=1,this.ua=e.clone().Vb(),this.Da=t,this.Ac=!0,this.Fe(null)},e.md=function(e,t,n){this.kc=1,this.ua=e.clone().Vb(),this.Da=null,this.Ac=t,this.Fe(n)},e.Fe=function(e){this.rb=w(),this.fb(),this.pa=this.ua.clone(),this.pa.fc("t",this.Zc),this.Cb=0,this.h=this.b.Kb(this.b.hc()?e:null),0<this.Ra&&(this.bc=new Lb(u(this.Qe,this,this.h),this.Ra)),this.Hc.ob(this.h,"readystatechange",this.qg),e=this.A?Da(this.A):{},this.Da?(this.Fa||(this.Fa="POST"),e["Content-Type"]="application/x-www-form-urlencoded",this.h.send(this.pa,this.Fa,this.Da,e)):(this.Fa="GET",this.h.send(this.pa,this.Fa,null,e)),O(1),this.a.Zg(this.Fa,this.pa,this.R,this.Zc,this.Da)},e.qg=function(e){e=e.target;var t=this.bc;t&&3==e.ma()?(this.a.debug("Throttling readystatechange."),t.rf()):this.Qe(e)},e.Qe=function(e){try{e==this.h?this.lg():this.a.T("Called back with an unexpected xmlhttp")}catch(e){if(this.a.debug("Failed call to OnXmlHttpReadyStateChanged_"),this.h&&this.h.ya()){var t=this;this.a.eb(e,function(){return"ResponseText: "+t.h.ya()})}else this.a.eb(e,"No response text")}},e.lg=function(){var e=this.h.ma(),t=this.h.Xd(),n=this.h.za();if(!(3>e||3==e&&!La&&!this.h.ya())){this.$a||4!=e||7==t||O(8==t||0>=n?3:2),this.Gb();var r=this.h.za();if(this.w=r,!(t=this.h.ya())){var i=this;this.a.debug(function(){return"No response text for uri "+i.pa+" status "+r})}if(this.S=200==r,this.a.$g(this.Fa,this.pa,this.R,this.Zc,e,r),this.S){if(this.Og()){if(!(n=this.wf()))return this.S=!1,this.I=3,P(12),this.a.T("XMLHTTP Missing X_HTTP_INITIAL_RESPONSE ("+this.R+")"),this.Ia(),void this.Lb();this.a.Xa(this.R,n,"Initial handshake response via X-HTTP-Initial-Response"),this.mb=!0,this.$c(n)}this.Ac?(this.Id(e,t),La&&this.S&&3==e&&this.Tg()):(this.a.Xa(this.R,t,null),this.$c(t)),4==e&&this.Ia(),this.S&&!this.$a&&(4==e?this.b.Vc(this):(this.S=!1,this.fb()))}else 400==r&&0<t.indexOf("Unknown SID")?(this.I=3,P(12),this.a.T("XMLHTTP Unknown SID ("+this.R+")")):(this.I=0,P(13),this.a.T("XMLHTTP Bad status "+r+" ("+this.R+")")),this.Ia(),this.Lb()}},e.Og=function(){return this.Hd&&!this.mb},e.wf=function(){if(this.h){var e=this.h.lb("X-HTTP-Initial-Response");if(e&&!va(e))return e}return null},e.Gg=function(){this.Hd=!0},e.Id=function(e,t){for(var n=!0;!this.$a&&this.Cb<t.length;){var r=this.zf(t);if(r==qc){4==e&&(this.I=4,P(14),n=!1),this.a.Xa(this.R,null,"[Incomplete Response]");break}if(r==pc){this.I=4,P(15),this.a.Xa(this.R,t,"[Invalid Chunk]"),n=!1;break}this.a.Xa(this.R,r,null),this.$c(r)}4==e&&0==t.length&&(this.I=1,P(16),n=!1),this.S=this.S&&n,n||(this.a.Xa(this.R,t,"[Invalid Chunked Response]"),this.Ia(),this.Lb())},e.og=function(){if(this.h){var e=this.h.ma(),t=this.h.ya();this.Cb<t.length&&(this.Gb(),this.Id(e,t),this.S&&4!=e&&this.fb())}},e.Tg=function(){this.Hc.ob(this.Xc,"tick",this.og),this.Xc.start()},e.zf=function(e){var t=this.Cb,n=e.indexOf("\n",t);return-1==n?qc:(t=Number(e.substring(t,n)),isNaN(t)?pc:(n+=1)+t>e.length?qc:(e=e.substr(n,t),this.Cb=n+t,e))},e.Bg=function(e){this.kc=2,this.ua=e.clone().Vb(),e=!1,h.navigator&&h.navigator.sendBeacon&&(e=h.navigator.sendBeacon(this.ua.toString(),"")),!e&&h.Image&&((new Image).src=this.ua,e=!0),e||(this.h=this.b.Kb(null),this.h.send(this.ua)),this.rb=w(),this.fb()},e.cancel=function(){this.$a=!0,this.Ia()},e.wg=function(e){e&&this.setTimeout(e),this.Ga&&(this.Gb(),this.fb())},e.fb=function(){this.ld=w()+this.Va,this.Oe(this.Va)},e.Oe=function(e){if(null!=this.Ga)throw Error("WatchDog timer not null");this.Ga=Q(u(this.kg,this),e)},e.Gb=function(){this.Ga&&(h.clearTimeout(this.Ga),this.Ga=null)},e.kg=function(){this.Ga=null;var e=w();0<=e-this.ld?this.Hf():(this.a.T("WatchDog timer called too early"),this.Oe(this.ld-e))},e.Hf=function(){this.S&&this.a.ca("Received watchdog timeout even though request loaded successfully"),this.a.Yg(this.pa),2!=this.kc&&(O(3),P(17)),this.Ia(),this.I=2,this.Lb()},e.Lb=function(){this.b.ge()||this.$a||this.b.Vc(this)},e.Ia=function(){this.Gb();var e=this.bc;e&&"function"==typeof e.cb&&e.cb(),this.bc=null,this.Xc.stop(),this.Hc.qb(),this.h&&(e=this.h,this.h=null,e.abort(),e.cb())},e.Jc=function(){return this.I},e.$c=function(e){try{this.b.xe(this,e),O(4)}catch(e){this.a.eb(e,"Error in httprequest callback")}},e=S.prototype,e.C=function(){return this.j},e.H=function(){this.yc();for(var e=[],t=0;t<this.o.length;t++)e.push(this.D[this.o[t]]);return e},e.W=function(){return this.yc(),this.o.concat()},e.va=function(e){return T(this.D,e)},e.X=function(){return 0==this.j},e.clear=function(){this.D={},this.j=this.o.length=0},e.remove=function(e){return!!T(this.D,e)&&(delete this.D[e],this.j--,this.o.length>2*this.j&&this.yc(),!0)},e.yc=function(){if(this.j!=this.o.length){for(var e=0,t=0;e<this.o.length;){var n=this.o[e];T(this.D,n)&&(this.o[t++]=n),e++}this.o.length=t}if(this.j!=this.o.length){var r={};for(t=e=0;e<this.o.length;)T(r,n=this.o[e])||(this.o[t++]=n,r[n]=1),e++;this.o.length=t}},e.get=function(e,t){return T(this.D,e)?this.D[e]:t},e.set=function(e,t){T(this.D,e)||(this.j++,this.o.push(e)),this.D[e]=t},e.addAll=function(e){if(e instanceof S)for(var t=e.W(),n=0;n<t.length;n++)this.set(t[n],e.get(t[n]));else for(t in e)this.set(t,e[t])},e.forEach=function(e,t){for(var n=this.W(),r=0;r<n.length;r++){var i=n[r],o=this.get(i);e.call(t,o,i,this)}},e.clone=function(){return new S(this)};var tc=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function uc(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var o=e[n].substring(0,r);i=e[n].substring(r+1)}else o=e[n];t(o,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}function U(e,t){var n;this.xa=this.Ab=this.qa="",this.Ca=null,this.jb=this.K="",this.O=this.Uf=!1,e instanceof U?(this.O=void 0!==t?t:e.O,this.ub(e.qa),this.fd(e.Ab),this.sb(e.xa),this.tb(e.Ca),this.gc(e.K),this.ed(e.P.clone()),this.cd(e.jb)):e&&(n=String(e).match(tc))?(this.O=!!t,this.ub(n[1]||"",!0),this.fd(n[2]||"",!0),this.sb(n[3]||"",!0),this.tb(n[4]),this.gc(n[5]||"",!0),this.ed(n[6]||"",!0),this.cd(n[7]||"",!0)):(this.O=!!t,this.P=new vc(null,this.O))}function Ec(e){return e instanceof U?e.clone():new U(e,void 0)}function Fc(e,t,n,r){var i=new U(null,void 0);return e&&i.ub(e),t&&i.sb(t),n&&i.tb(n),r&&i.gc(r),i}function Cc(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function wc(e,t,n){return l(e)?(e=encodeURI(e).replace(t,Gc),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function Gc(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}e=U.prototype,e.toString=function(){var e=[],t=this.qa;t&&e.push(wc(t,yc,!0),":");var n=this.xa;return(n||"file"==t)&&(e.push("//"),(t=this.Ab)&&e.push(wc(t,yc,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.Ca)&&e.push(":",String(n))),(n=this.K)&&(this.Kc()&&"/"!=n.charAt(0)&&e.push("/"),e.push(wc(n,"/"==n.charAt(0)?zc:Ac,!0))),(n=this.Ud())&&e.push("?",n),(n=this.jb)&&e.push("#",wc(n,Bc)),e.join("")},e.resolve=function(e){var t=this.clone(),n=e.Lf();n?t.ub(e.qa):n=e.Mf(),n?t.fd(e.Ab):n=e.Kc(),n?t.sb(e.xa):n=e.Jf();var r=e.K;if(n)t.tb(e.Ca);else if(n=e.de()){if("/"!=r.charAt(0))if(this.Kc()&&!this.de())r="/"+r;else{var i=t.K.lastIndexOf("/");-1!=i&&(r=t.K.substr(0,i+1)+r)}if(".."==(i=r)||"."==i)r="";else if(-1!=i.indexOf("./")||-1!=i.indexOf("/.")){r=0==i.lastIndexOf("/",0),i=i.split("/");for(var o=[],a=0;a<i.length;){var s=i[a++];"."==s?r&&a==i.length&&o.push(""):".."==s?((1<o.length||1==o.length&&""!=o[0])&&o.pop(),r&&a==i.length&&o.push("")):(o.push(s),r=!0)}r=o.join("/")}else r=i}return n?t.gc(r):n=e.Kf(),n?t.ed(e.P.clone()):n=e.If(),n&&t.cd(e.jb),t},e.clone=function(){return new U(this)},e.ub=function(e,t){this.U(),(this.qa=t?Cc(e,!0):e)&&(this.qa=this.qa.replace(/:$/,""))},e.Lf=function(){return!!this.qa},e.fd=function(e,t){this.U(),this.Ab=t?Cc(e):e},e.Mf=function(){return!!this.Ab},e.sb=function(e,t){this.U(),this.xa=t?Cc(e,!0):e},e.Kc=function(){return!!this.xa},e.tb=function(e){if(this.U(),e){if(e=Number(e),isNaN(e)||0>e)throw Error("Bad port number "+e);this.Ca=e}else this.Ca=null},e.Jf=function(){return null!=this.Ca},e.gc=function(e,t){this.U(),this.K=t?Cc(e,!0):e},e.de=function(){return!!this.K},e.Kf=function(){return""!==this.P.toString()},e.ed=function(e,t){this.U(),e instanceof vc?(this.P=e,this.P.dd(this.O)):(t||(e=wc(e,Dc)),this.P=new vc(e,this.O))},e.Ud=function(){return this.P.toString()},e.getQuery=function(){return this.Ud()},e.l=function(e,t){this.U(),this.P.set(e,t)},e.fc=function(e,t){this.U(),n(t)||(t=[String(t)]),this.P.Me(e,t)},e.cd=function(e,t){this.U(),this.jb=t?Cc(e):e},e.If=function(){return!!this.jb},e.Vb=function(){return this.U(),this.l("zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^w()).toString(36)),this},e.removeParameter=function(e){return this.U(),this.P.remove(e),this},e.U=function(){if(this.Uf)throw Error("Tried to modify a read-only Uri")},e.dd=function(e){this.O=e,this.P&&this.P.dd(e)};var yc=/[#\/\?@]/g,Ac=/[#\?:]/g,zc=/[#\?]/g,Dc=/[#\?@]/g,Bc=/#/g;function vc(e,t){this.j=this.m=null,this.ja=e||null,this.O=!!t}function Jc(){}function Kc(){}function Lc(e,t){this.b=e,this.a=t,this.f=this.A=null,this.cc=!1,this.K=null,this.w=-1,this.Dd=this.na=null}function Mc(){this.rd=this.ce=null}function Nc(e){this.D=new S,e&&this.addAll(e)}function Oc(e){var n=typeof e;return"object"==n&&e||"function"==n?"o"+(e[t]||(e[t]=++da)):n.substr(0,1)+e}function Pc(e,t){this.Rc=e,this.map=t,this.context=null}function Qc(e){this.pe=e||Rc,h.PerformanceNavigationTiming?e=0<(e=h.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):e=!!(h.xc&&h.xc.ne&&h.xc.ne()&&h.xc.ne().th),this.Yb=e?this.pe:1,this.v=null,1<this.Yb&&(this.v=new Nc),this.f=null,this.ba=[]}e=vc.prototype,e.$=function(){if(!this.m&&(this.m=new S,this.j=0,this.ja)){var e=this;uc(this.ja,function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)})}},e.C=function(){return this.$(),this.j},e.add=function(e,t){this.$(),this.Oa(),e=this.Ma(e);var n=this.m.get(e);return n||this.m.set(e,n=[]),n.push(t),this.j+=1,this},e.remove=function(e){return this.$(),e=this.Ma(e),!!this.m.va(e)&&(this.Oa(),this.j-=this.m.get(e).length,this.m.remove(e))},e.clear=function(){this.Oa(),this.m=null,this.j=0},e.X=function(){return this.$(),0==this.j},e.va=function(e){return this.$(),e=this.Ma(e),this.m.va(e)},e.forEach=function(e,t){this.$(),this.m.forEach(function(n,r){na(n,function(n){e.call(t,n,r,this)},this)},this)},e.W=function(){this.$();for(var e=this.m.H(),t=this.m.W(),n=[],r=0;r<t.length;r++)for(var i=e[r],o=0;o<i.length;o++)n.push(t[r]);return n},e.H=function(e){this.$();var t=[];if(l(e))this.va(e)&&(t=ta(t,this.m.get(this.Ma(e))));else{e=this.m.H();for(var n=0;n<e.length;n++)t=ta(t,e[n])}return t},e.set=function(e,t){return this.$(),this.Oa(),e=this.Ma(e),this.va(e)&&(this.j-=this.m.get(e).length),this.m.set(e,[t]),this.j+=1,this},e.get=function(e,t){return e&&0<(e=this.H(e)).length?String(e[0]):t},e.Me=function(e,t){this.remove(e),0<t.length&&(this.Oa(),this.m.set(this.Ma(e),ua(t)),this.j+=t.length)},e.toString=function(){if(this.ja)return this.ja;if(!this.m)return"";for(var e=[],t=this.m.W(),n=0;n<t.length;n++){var r=t[n],i=encodeURIComponent(String(r));r=this.H(r);for(var o=0;o<r.length;o++){var a=i;""!==r[o]&&(a+="="+encodeURIComponent(String(r[o]))),e.push(a)}}return this.ja=e.join("&")},e.Oa=function(){this.ja=null},e.clone=function(){var e=new vc;return e.ja=this.ja,this.m&&(e.m=this.m.clone(),e.j=this.j),e},e.Ma=function(e){return e=String(e),this.O&&(e=e.toLowerCase()),e},e.dd=function(e){e&&!this.O&&(this.$(),this.Oa(),this.m.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(this.remove(t),this.Me(n,e))},this)),this.O=e},e.extend=function(e){for(var t=0;t<arguments.length;t++)sc(arguments[t],function(e,t){this.add(t,e)},this)},x(Kc,Jc),e=Lc.prototype,e.g=null,e.ga=function(e){this.A=e},e.connect=function(e){this.K=e,e=this.b.Vd(this.K),P(3);var t=this.b.Jb.ce;null!=t?(this.na=this.b.ab(t[0]),this.g=1,this.Ad()):(e.fc("MODE","init"),!this.b.ta&&this.b.aa&&e.fc("X-HTTP-Session-Id",this.b.aa),this.f=new R(this,this.a,void 0,void 0,void 0),this.f.ga(this.A),this.f.md(e,!1,null),this.g=0)},e.Ad=function(){this.a.debug("TestConnection: starting stage 2");var e=this.b.Jb.rd;if(null!=e)this.a.debug(function(){return"Buffered"}),P(4),e?(P(10),this.b.vb(this,!1)):(P(11),this.b.vb(this,!0));else{this.f=new R(this,this.a,void 0,void 0,void 0),this.f.ga(this.A);var t=this.b.Sd(this.na,this.K);P(4),t.fc("TYPE","xmlhttp");var n=this.b.aa,r=this.b.Mc;n&&r&&t.l(n,r),this.f.md(t,!1,this.na)}},e.Kb=function(e){return this.b.Kb(e)},e.abort=function(){this.f&&(this.f.cancel(),this.f=null),this.w=-1},e.ge=function(){return!1},e.xe=function(e,t){if(this.w=e.w,0==this.g)if(this.a.debug("TestConnection: Got data for stage 1"),this.rc(e),t){try{var n=this.b.mc.Bc(t)}catch(e){return this.a.eb(e),void this.b.gd(this)}this.na=this.b.ab(n[0])}else this.a.debug("TestConnection: Null responseText"),this.b.gd(this);else 1==this.g&&(this.cc?P(6):"11111"==t?(P(5),this.cc=!0,this.cf()&&(this.w=200,this.f.cancel(),this.a.debug("Test connection succeeded; using streaming connection"),P(11),this.b.vb(this,!0))):(P(7),this.cc=!1))},e.Vc=function(){this.w=this.f.w,this.f.S?0==this.g?(this.g=1,this.a.debug("TestConnection: request complete for initial check"),this.Ad()):1==this.g&&(this.a.debug("TestConnection: request complete for stage 2"),this.cc?(this.a.debug("Test connection succeeded; using streaming connection"),P(11),this.b.vb(this,!0)):(this.a.debug("Test connection failed; not using streaming"),P(10),this.b.vb(this,!1))):(this.a.debug("TestConnection: request failed, in state "+this.g),0==this.g?P(8):1==this.g&&P(9),this.b.gd(this))},e.rc=function(e){if(!this.b.ta&&(e=e.h)){var t=e.lb("X-Client-Wire-Protocol");this.Dd=t||null,this.b.aa&&((e=e.lb("X-HTTP-Session-Id"))?this.b.Je(e):this.a.T("Missing X_HTTP_SESSION_ID in the handshake response"))}},e.hc=function(){return this.b.hc()},e.Ba=function(){return this.b.Ba()},e.cf=function(){return!C||10<=Number(Ua)},e=Nc.prototype,e.C=function(){return this.D.C()},e.add=function(e){this.D.set(Oc(e),e)},e.addAll=function(e){for(var t=(e=rc(e)).length,n=0;n<t;n++)this.add(e[n])},e.qb=function(e){for(var t=(e=rc(e)).length,n=0;n<t;n++)this.remove(e[n])},e.remove=function(e){return this.D.remove(Oc(e))},e.clear=function(){this.D.clear()},e.X=function(){return this.D.X()},e.contains=function(e){return this.D.va(Oc(e))},e.H=function(){return this.D.H()},e.clone=function(){return new Nc(this)};var Rc=10;function Sc(){this.Ag=this.Ta=void 0}function Tc(){this.ng=new Sc}function Uc(e,t){var n=new $b;n.debug("TestLoadImage: loading "+e);var r=new Image;r.onload=v(Vc,n,r,"TestLoadImage: loaded",!0,t),r.onerror=v(Vc,n,r,"TestLoadImage: error",!1,t),r.onabort=v(Vc,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=v(Vc,n,r,"TestLoadImage: timeout",!1,t),h.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}function Vc(e,t,n,r,i){try{e.debug(n),t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(t){e.eb(t)}}function V(e){H.call(this),this.headers=new S,this.Ya=e||null,this.ha=!1,this.oc=this.c=null,this.je=this.Ub="",this.Pa=0,this.I="",this.Aa=this.Nc=this.Rb=this.Gc=!1,this.wb=0,this.jc=null,this.De=Wc,this.lc=this.pg=this.Bb=!1}e=Qc.prototype,e.od=function(e){this.v||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(this.Yb=this.pe,this.v=new Nc,this.f&&(this.qc(this.f),this.f=null))},e.he=function(){return!!this.f||!!this.v&&this.v.C()>=this.Yb},e.Bf=function(){return this.f?1:this.v?this.v.C():0},e.Lc=function(e){return this.f?this.f==e:!!this.v&&this.v.contains(e)},e.qc=function(e){this.v?this.v.add(e):this.f=e},e.Ce=function(e){this.f&&this.f==e?this.f=null:this.v&&this.v.contains(e)&&this.v.remove(e)},e.cancel=function(){this.ba=this.la(),this.f?(this.f.cancel(),this.f=null):this.v&&!this.v.X()&&(na(this.v.H(),function(e){e.cancel()}),this.v.clear())},e.la=function(){if(null!=this.f)return this.ba.concat(this.f.la());if(null!=this.v&&!this.v.X()){var e=this.ba;return na(this.v.H(),function(t){e=e.concat(t.la())}),e}return ua(this.ba)},e.Ve=function(e){this.ba=this.ba.concat(e)},e.df=function(){this.ba.length=0},Sc.prototype.stringify=function(e){return h.JSON.stringify(e,this.Ta)},Sc.prototype.parse=function(e){return h.JSON.parse(e,this.Ag)},Tc.prototype.mf=function(e,t,n){var i=n||"";try{sc(e,function(e,n){var o=e;r(e)&&(o=(new I).ec(e)),t.push(i+n+"="+encodeURIComponent(o))})}catch(e){throw t.push(i+"type="+encodeURIComponent("_badmap")),e}},Tc.prototype.nf=function(e,t,n){for(var r=-1;;){var i=["count="+t];-1==r?0<t?(r=e[0].Rc,i.push("ofs="+r)):r=0:i.push("ofs="+r);for(var o=!0,a=0;a<t;a++){var s=e[a].Rc,u=e[a].map;if(0>(s-=r))r=Math.max(0,e[a].Rc-100),o=!1;else try{this.mf(u,i,"req"+s+"_")}catch(e){n&&n(u)}}if(o)return i.join("&")}},Tc.prototype.Bc=function(e){return this.ng.parse(e)},x(V,H);var Wc="";V.prototype.s=Yb("goog.net.XhrIo");var Xc=/^https?$/i,Yc=["POST","PUT"];function Zc(e){return C&&Ta(9)&&"number"==typeof e.timeout&&void 0!==e.ontimeout}function qa(e){return"content-type"==e.toLowerCase()}function $c(e,t){return{type:t,lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total}}function ad(e){var t="";return Aa(e,function(e,n){t+=n,t+=":",t+=e,t+="\r\n"}),t}function bd(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}if(r)return e;if(n=ad(n),l(e)){if(t=encodeURIComponent(String(t)),t+=n=null!=n?"="+encodeURIComponent(String(n)):""){if(0>(n=e.indexOf("#"))&&(n=e.length),0>(r=e.indexOf("?"))||r>n){r=n;var i=""}else i=e.substring(r+1,n);n=(e=[e.substr(0,r),i,e.substr(n)])[1],e[1]=t?n?n+"&"+t:t:n,e=e[0]+(e[1]?"?"+e[1]:"")+e[2]}return e}return e.l(t,n),e}function cd(e){this.Ed=22,this.He=0,this.M=[],this.a=new $b,this.Jb=new Mc,this.na=this.pd=this.ib=this.K=this.u=this.Mc=this.aa=this.hb=this.N=this.Sb=this.A=null,this.Xe=!0,this.eg=this.Zb=0,this.pf=!!m("internalChannelParams.failFast",e),this.jd=this.Ja=this.wa=this.ia=this.ea=this.i=null,this.We=!0,this.w=this.ke=this.Tb=-1,this.tc=this.Ha=this.La=0,this.Ze=m("internalChannelParams.baseRetryDelayMs",e)||5e3,this.yg=m("internalChannelParams.retryDelaySeedMs",e)||1e4,this.sf=m("internalChannelParams.forwardChannelMaxRetries",e)||2,this.Rd=m("internalChannelParams.forwardChannelRequestTimeoutMs",e)||2e4,this.Ya=e&&e.uh||void 0,this.Eb=void 0,this.Ra=0,this.ic=e&&e.supportsCrossDomainXhr||!1,this.ra="",this.G=new Qc(e&&e.concurrentRequestLimit),this.mc=new Tc,this.ta=!e||void 0===e.backgroundChannelTest||e.backgroundChannelTest,(this.Qd=e&&e.fastHandshake||!1)&&!this.ta&&(this.a.T("Force backgroundChannelTest when fastHandshake is enabled."),this.ta=!0),e&&e.Ld&&this.a.Ld()}function dd(){}function ed(e){for(var t=arguments[0],n=1;n<arguments.length;n++){var r,i=arguments[n];if(0==i.lastIndexOf("/",0))t=i;else(r=""==t)||(r=0<=(r=t.length-1)&&t.indexOf("/",r)==r),t=r?t+i:t+"/"+i}return t}function fd(){if(C&&!(10<=Number(Ua)))throw Error("Environmental error: no available transport.")}function W(e,t){H.call(this),this.b=new cd(t),this.zb=e,this.Wg=t&&t.testUrl?t.testUrl:ed(this.zb,"test"),this.s=Yb("goog.labs.net.webChannel.WebChannelBaseTransport"),this.Tc=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.b.ga(e),e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.Cd&&(e?e["X-WebChannel-Client-Profile"]=t.Cd:e={"X-WebChannel-Client-Profile":t.Cd}),this.b.Kg(e),(e=t&&t.httpHeadersOverwriteParam)&&!va(e)&&this.b.Ig(e),this.Ug=t&&t.supportsCrossDomainXhr||!1,this.Cg=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!va(t)&&(this.b.Jg(t),null!==(e=this.Tc)&&t in e&&(t in(e=this.Tc)&&delete e[t],(e=this.s)&&e.T("Ignore httpSessionIdParam also specified with messageUrlParams: "+t,void 0))),this.yd=new X(this)}function gd(e){jc.call(this);var t=e.__sm__;if(t){e:{for(var n in t){e=n;break e}e=void 0}(this.qe=e)&&(e=this.qe,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function hd(e){kc.call(this),this.status=1,this.errorCode=e}function X(e){this.b=e}e=V.prototype,e.Ne=function(e){this.Bb=e},e.send=function(e,t,n,r){if(this.c)throw Error("[goog.net.XhrIo] Object is active with another request="+this.Ub+"; newUri="+e);t=t?t.toUpperCase():"GET",this.Ub=e,this.I="",this.Pa=0,this.je=t,this.Gc=!1,this.ha=!0,this.c=this.hf(),this.oc=this.Ya?this.Ya.Yd():lc.Yd(),this.c.onreadystatechange=u(this.we,this),this.pg&&"onprogress"in this.c&&(this.c.onprogress=u(function(e){this.ue(e,!0)},this),this.c.upload&&(this.c.upload.onprogress=u(this.ue,this)));try{M(this.s,this.da("Opening Xhr")),this.Nc=!0,this.c.open(t,String(e),!0),this.Nc=!1}catch(e){return M(this.s,this.da("Error opening Xhr: "+e.message)),void this.Od(e)}e=n||"";var i=this.headers.clone();r&&sc(r,function(e,t){i.set(t,e)}),r=pa(i.W()),n=h.FormData&&e instanceof h.FormData,!(0<=la(Yc,t))||r||n||i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach(function(e,t){this.c.setRequestHeader(t,e)},this),this.De&&(this.c.responseType=this.De),"withCredentials"in this.c&&this.c.withCredentials!==this.Bb&&(this.c.withCredentials=this.Bb);try{this.Bd(),0<this.wb&&(this.lc=Zc(this.c),M(this.s,this.da("Will abort after "+this.wb+"ms if incomplete, xhr2 "+this.lc)),this.lc?(this.c.timeout=this.wb,this.c.ontimeout=u(this.Va,this)):this.jc=Kb(this.Va,this.wb,this)),M(this.s,this.da("Sending request")),this.Rb=!0,this.c.send(e),this.Rb=!1}catch(e){M(this.s,this.da("Send error: "+e.message)),this.Od(e)}},e.hf=function(){return this.Ya?this.Ya.Gd():lc.Gd()},e.Va=function(){void 0!==goog&&this.c&&(this.I="Timed out after "+this.wb+"ms, aborting",this.Pa=8,M(this.s,this.da(this.I)),this.dispatchEvent("timeout"),this.abort(8))},e.Od=function(e){this.ha=!1,this.c&&(this.Aa=!0,this.c.abort(),this.Aa=!1),this.I=e,this.Pa=5,this.Md(),this.Hb()},e.Md=function(){this.Gc||(this.Gc=!0,this.dispatchEvent("complete"),this.dispatchEvent("error"))},e.abort=function(e){this.c&&this.ha&&(M(this.s,this.da("Aborting")),this.ha=!1,this.Aa=!0,this.c.abort(),this.Aa=!1,this.Pa=e||7,this.dispatchEvent("complete"),this.dispatchEvent("abort"),this.Hb())},e.F=function(){this.c&&(this.ha&&(this.ha=!1,this.Aa=!0,this.c.abort(),this.Aa=!1),this.Hb(!0)),V.L.F.call(this)},e.we=function(){this.Ka||(this.Nc||this.Rb||this.Aa?this.ve():this.ig())},e.ig=function(){this.ve()},e.ve=function(){if(this.ha&&void 0!==goog)if(this.oc[1]&&4==this.ma()&&2==this.za())M(this.s,this.da("Local request error detected and ignored"));else if(this.Rb&&4==this.ma())Kb(this.we,0,this);else if(this.dispatchEvent("readystatechange"),this.Oc()){M(this.s,this.da("Request complete")),this.ha=!1;try{this.Vf()?(this.dispatchEvent("complete"),this.dispatchEvent("success")):(this.Pa=6,this.I=this.ae()+" ["+this.za()+"]",this.Md())}finally{this.Hb()}}},e.ue=function(e,t){this.dispatchEvent($c(e,"progress")),this.dispatchEvent($c(e,t?"downloadprogress":"uploadprogress"))},e.Hb=function(e){if(this.c){this.Bd();var t=this.c,n=this.oc[0]?aa:null;this.oc=this.c=null,e||this.dispatchEvent("ready");try{t.onreadystatechange=n}catch(t){(e=this.s)&&e.ca("Problem encountered resetting onreadystatechange: "+t.message,void 0)}}},e.Bd=function(){this.c&&this.lc&&(this.c.ontimeout=null),this.jc&&(h.clearTimeout(this.jc),this.jc=null)},e.Ba=function(){return!!this.c},e.Oc=function(){return 4==this.ma()},e.Vf=function(){var e=this.za();e:switch(e){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}return t||0===e&&!this.Sf()},e.Sf=function(){var e=String(this.Ub).match(tc)[1]||null;return!e&&h.self&&h.self.location&&(e=(e=h.self.location.protocol).substr(0,e.length-1)),Xc.test(e?e.toLowerCase():"")},e.ma=function(){return this.c?this.c.readyState:0},e.za=function(){try{return 2<this.ma()?this.c.status:-1}catch(e){return-1}},e.ae=function(){try{return 2<this.ma()?this.c.statusText:""}catch(e){return M(this.s,"Can not get status: "+e.message),""}},e.ya=function(){try{return this.c?this.c.responseText:""}catch(e){return M(this.s,"Can not get responseText: "+e.message),""}},e.Cf=function(e){if(this.c){var t=this.c.responseText;e&&0==t.indexOf(e)&&(t=t.substring(e.length));e:{if(e=t,h.JSON)try{var n=h.JSON.parse(e);break e}catch(e){}n=vb(e)}return n}},e.getResponseHeader=function(e){if(this.c&&this.Oc())return null===(e=this.c.getResponseHeader(e))?void 0:e},e.getAllResponseHeaders=function(){return this.c&&this.Oc()&&this.c.getAllResponseHeaders()||""},e.lb=function(e){return this.c?this.c.getResponseHeader(e):null},e.Xd=function(){return this.Pa},e.Jc=function(){return l(this.I)?this.I:String(this.I)},e.da=function(e){return e+" ["+this.je+" "+this.Ub+" "+this.za()+"]"},e=cd.prototype,e.vc=8,e.g=1,e.connect=function(e,t,n,r,i){this.a.debug("connect()"),P(0),this.K=t,this.hb=n||{},r&&void 0!==i&&(this.hb.OSID=r,this.hb.OAID=i),this.ta&&(this.a.debug("connect() bypassed channel-test."),this.Jb.ce=[],this.Jb.rd=!1),this.ff(e)},e.disconnect=function(){if(this.a.debug("disconnect()"),this.td(),3==this.g){var e=this.Zb++,t=this.ib.clone();t.l("SID",this.ra),t.l("RID",e),t.l("TYPE","terminate"),this.Za(t),new R(this,this.a,this.ra,e,void 0).Bg(t)}this.te()},e.ff=function(e){this.a.debug("connectTest_()"),this.Ja=new Lc(this,this.a),null===this.N&&this.Ja.ga(this.A);var t=e;this.N&&this.A&&(t=bd(e,this.N,this.A)),this.Ja.connect(t)},e.ef=function(){this.a.debug("connectChannel_()"),this.ib=this.Vd(this.K),this.Fc()},e.td=function(){this.Ja&&(this.Ja.abort(),this.Ja=null),this.u&&(this.u.cancel(),this.u=null),this.ia&&(h.clearTimeout(this.ia),this.ia=null),this.Ib(),this.G.cancel(),this.ea&&(h.clearTimeout(this.ea),this.ea=null)},e.ga=function(e){this.A=e},e.Kg=function(e){this.Sb=e},e.Ig=function(e){this.N=e},e.Jg=function(e){this.aa=e},e.Je=function(e){this.Mc=e},e.Le=function(e){this.Ra=e},e.Ng=function(){this.ic=!0},e.Ie=function(e){this.i=e},e.Rf=function(){return!this.jd},e.ad=function(e){1e3==this.M.length&&this.a.ca(function(){return"Already have 1000 queued maps upon queueing "+(new I).ec(e)}),this.M.push(new Pc(this.eg++,e)),3==this.g&&this.Fc()},e.uf=function(){return this.pf?0:this.sf},e.ge=function(){return 0==this.g},e.getState=function(){return this.g},e.Fc=function(){this.G.he()||this.ea||(this.ea=Q(u(this.ze,this),0),this.La=0)},e.bg=function(e){return this.G.Bf()>=this.G.Yb-(this.ea?1:0)?(this.a.ca("Unexpected retry request is scheduled."),!1):this.ea?(this.a.debug("Use the retry request that is already scheduled."),this.M=e.la().concat(this.M),!0):!(1==this.g||2==this.g||this.La>=this.uf())&&(this.a.debug("Going to retry POST"),this.ea=Q(u(this.ze,this,e),this.$d(this.La)),this.La++,!0)},e.ze=function(e){this.ea=null,this.Sg(e)},e.Sg=function(e){this.a.debug("startForwardChannel_"),1==this.g?e?this.a.ca("Not supposed to retry the open"):(this.mg(),this.g=2):3==this.g&&(e?this.oe(e):0==this.M.length?this.a.debug("startForwardChannel_ returned: nothing to send"):this.G.he()?this.a.ca("startForwardChannel_ returned: connection already in progress"):(this.oe(),this.a.debug("startForwardChannel_ finished, sent request")))},e.mg=function(){this.a.debug("open_()"),this.Zb=Math.floor(1e5*Math.random());var e=this.Zb++,t=new R(this,this.a,"",e,void 0),n=this.A;this.Sb&&(n?Fa(n=Da(n),this.Sb):n=this.Sb),null===this.N&&t.ga(n);var r=this.Kd(t),i=this.ib.clone();i.l("RID",e),0<this.Ed&&i.l("CVER",this.Ed),this.ta&&this.aa&&i.l("X-HTTP-Session-Id",this.aa),this.Za(i),this.N&&n&&bd(i,this.N,n),this.G.qc(t),this.Qd?(i.l("$req",r),i.l("SID","null"),t.Gg(),t.nd(i,null)):t.nd(i,r)},e.oe=function(e){var t=e?e.R:this.Zb++,n=this.ib.clone();n.l("SID",this.ra),n.l("RID",t),n.l("AID",this.Tb),this.Za(n),this.N&&this.A&&bd(n,this.N,this.A),t=new R(this,this.a,this.ra,t,this.La+1),null===this.N&&t.ga(this.A),e&&this.vg(e),e=this.Kd(t),t.setTimeout(Math.round(.5*this.Rd)+Math.round(.5*this.Rd*Math.random())),this.G.qc(t),t.nd(n,e)},e.Za=function(e){this.i&&sc({},function(t,n){e.l(n,t)})},e.Kd=function(e){var t=Math.min(this.M.length,1e3),n=this.i?u(this.i.Ye,this.i,this):null;return n=this.mc.nf(this.M,t,n),e.Mg(this.M.splice(0,t)),n},e.vg=function(e){this.M=e.la().concat(this.M)},e.Nd=function(){if(!this.u&&!this.ia){this.tc=1;var e=this.ye;Eb||Fb(),Hb||(Eb(),Hb=!0),Ib.add(e,this),this.Ha=0}},e.Sc=function(){return this.u||this.ia?(this.a.ca("Request already in progress"),!1):!(3<=this.Ha)&&(this.a.debug("Going to retry GET"),this.tc++,this.ia=Q(u(this.ye,this),this.$d(this.Ha)),this.Ha++,!0)},e.ye=function(){this.ia=null,this.Qg()},e.Qg=function(){this.a.debug("Creating new HttpRequest"),this.u=new R(this,this.a,this.ra,"rpc",this.tc),null===this.N&&this.u.ga(this.A),this.u.Le(this.Ra);var e=this.pd.clone();e.l("RID","rpc"),e.l("SID",this.ra),e.l("CI",this.jd?"0":"1"),e.l("AID",this.Tb),this.Za(e),e.l("TYPE","xmlhttp"),this.N&&this.A&&bd(e,this.N,this.A),this.Eb&&this.u.setTimeout(this.Eb),this.u.md(e,!0,this.na),this.a.debug("New Request created")},e.vb=function(e,t){this.a.debug("Test Connection Finished");var n=e.Dd;n&&this.G.od(n),this.jd=this.We&&t,this.w=e.w,this.ef()},e.gd=function(e){this.a.debug("Test Connection Failed"),this.w=e.w,this.sa(2)},e.xe=function(e,t){if(0!=this.g&&(this.u==e||this.G.Lc(e)))if(this.w=e.w,!e.mb&&this.G.Lc(e)&&3==this.g){try{var r=this.mc.Bc(t)}catch(e){r=null}n(r)&&3==r.length?this.Gf(r,e):(this.a.debug("Bad POST response data returned"),this.sa(11))}else(e.mb||this.u==e)&&this.Ib(),va(t)||(r=this.mc.Bc(t),this.hg(r,e))},e.Gf=function(e,t){0==e[0]?this.Ff(t):(this.ke=e[1],0<(t=this.ke-this.Tb)&&(e=e[2],this.a.debug(e+" bytes (in "+t+" arrays) are outstanding on the BackChannel"),this.Pg(e)&&!this.wa&&(this.wa=Q(u(this.fg,this),6e3))))},e.Ff=function(e){if(this.a.debug("Server claims our backchannel is missing."),this.ia)this.a.debug("But we are currently starting the request.");else{if(this.u){if(!(this.u.rb+3e3<e.rb))return;this.Ib(),this.u.cancel(),this.u=null}else this.a.T("We do not have a BackChannel established");this.Sc(),P(18)}},e.Pg=function(e){return 37500>e&&!this.Rf()&&0==this.Ha},e.ab=function(e){return this.Xe?this.i?this.i.ab(e):e:null},e.fg=function(){null!=this.wa&&(this.wa=null,this.u.cancel(),this.u=null,this.Sc(),P(19))},e.Ib=function(){null!=this.wa&&(h.clearTimeout(this.wa),this.wa=null)},e.Vc=function(e){this.a.debug("Request complete");var t=null;if(this.u==e){this.Ib(),this.u=null;var n=2}else{if(!this.G.Lc(e))return;t=e.la(),this.G.Ce(e),n=1}if(this.w=e.w,0!=this.g)if(e.S)1==n?(dc(e.Da?e.Da.length:0,w()-e.rb,this.La),this.Fc()):this.Nd();else{var r=e.Jc();if(3==r||0==r&&0<this.w)this.a.debug("Not retrying due to error type");else{var i=this;if(this.a.debug(function(){return"Maybe retrying, last error: "+oc(r,i.w)}),1==n&&this.bg(e)||2==n&&this.Sc())return;this.a.debug("Exceeded max number of retries")}switch(t&&0<t.length&&this.G.Ve(t),this.a.debug("Error: HTTP request failed"),r){case 1:this.sa(5);break;case 4:this.sa(10);break;case 3:this.sa(6);break;default:this.sa(2)}}},e.$d=function(e){var t=this.Ze+Math.floor(Math.random()*this.yg);return this.Ba()||(this.a.debug("Inactive channel"),t*=2),t*e},e.rc=function(e){if(this.ta&&(e=e.h)){var t=e.lb("X-Client-Wire-Protocol");t&&this.G.od(t),this.aa&&((e=e.lb("X-HTTP-Session-Id"))?(this.Je(e),this.ib.l(this.aa,e)):this.a.T("Missing X_HTTP_SESSION_ID in the handshake response"))}},e.hg=function(e,t){for(var n=this.i&&this.i.uc?[]:null,r=0;r<e.length;r++){var i=e[r];if(this.Tb=i[0],i=i[1],2==this.g)if("c"==i[0]){this.ra=i[1],this.na=this.ab(i[2]);var o=i[3];null!=o&&(this.vc=o,this.a.info("VER="+this.vc)),null!=(o=i[4])&&(this.He=o,this.a.info("SVER="+this.He)),null!=(i=i[5])&&"number"==typeof i&&0<i&&(this.Eb=i*=1.5,this.a.info("backChannelRequestTimeoutMs_="+i)),this.rc(t),this.g=3,this.i&&this.i.zd(),this.Rg(t)}else"stop"!=i[0]&&"close"!=i[0]||this.sa(7);else 3==this.g&&("stop"==i[0]||"close"==i[0]?(n&&0!=n.length&&(this.i.uc(this,n),n.length=0),"stop"==i[0]?this.sa(7):this.disconnect()):"noop"!=i[0]&&(n?n.push(i):this.i&&this.i.xd(i)),this.Ha=0)}n&&0!=n.length&&this.i.uc(this,n)},e.Rg=function(e){this.pd=this.Sd(this.na,this.K),e.mb?(this.a.debug("Upgrade the handshake request to a backchannel."),this.G.Ce(e),e.wg(this.Eb),this.u=e):this.Nd()},e.sa=function(e){if(this.a.info("Error code "+e),2==e){var t=null;this.i&&(t=null);var n=u(this.Vg,this);t||(t=new U("//www.google.com/images/cleardot.gif"),h.location&&"http"==h.location.protocol||t.ub("https"),t.Vb()),Uc(t.toString(),n)}else P(2);this.gg(e)},e.Vg=function(e){e?(this.a.info("Successfully pinged google.com"),P(2)):(this.a.info("Failed to ping google.com"),P(1))},e.gg=function(e){this.a.debug("HttpChannel: error - "+e),this.g=0,this.i&&this.i.wd(e),this.te(),this.td()},e.te=function(){if(this.g=0,this.w=-1,this.i){var e=this.G.la();if(0!=e.length||0!=this.M.length){var t=this;this.a.debug(function(){return"Number of undelivered maps, pending: "+e.length+", outgoing: "+t.M.length}),this.G.df(),ua(this.M),this.M.length=0}this.i.vd()}},e.Vd=function(e){return e=this.Fd(null,e),this.a.debug("GetForwardChannelUri: "+e),e},e.Sd=function(e,t){return e=this.Fd(this.hc()?e:null,t),this.a.debug("GetBackChannelUri: "+e),e},e.Fd=function(e,t){var n=Ec(t);if(""!=n.xa)e&&n.sb(e+"."+n.xa),n.tb(n.Ca);else{var r=h.location;n=Fc(r.protocol,e?e+"."+r.hostname:r.hostname,+r.port,t)}return this.hb&&Aa(this.hb,function(e,t){n.l(t,e)}),e=this.aa,t=this.Mc,e&&t&&n.l(e,t),n.l("VER",this.vc),this.Za(n),n},e.Kb=function(e){if(e&&!this.ic)throw Error("Can't create secondary domain capable XhrIo object.");return(e=new V(this.Ya)).Ne(this.ic),e},e.Ba=function(){return!!this.i&&this.i.Ba()},e.hc=function(){return this.ic},e=dd.prototype,e.uc=null,e.zd=function(){},e.xd=function(){},e.wd=function(){},e.vd=function(){},e.Ba=function(){return!0},e.Ye=function(){},e.ab=function(e){return e},fd.prototype.gf=function(e,t){return new W(e,t)},x(W,H),e=W.prototype,e.addEventListener=function(e,t,n,r){W.L.addEventListener.call(this,e,t,n,r)},e.removeEventListener=function(e,t,n,r){W.L.removeEventListener.call(this,e,t,n,r)},e.open=function(){this.b.Ie(this.yd),this.Ug&&this.b.Ng(),this.b.connect(this.Wg,this.zb,this.Tc||void 0)},e.close=function(){this.b.disconnect()},e.send=function(e){if(l(e)){var t={};t.__data__=e,this.b.ad(t)}else this.Cg?((t={}).__data__=(new I).ec(e),this.b.ad(t)):this.b.ad(e)},e.F=function(){this.b.Ie(null),delete this.yd,this.b.disconnect(),delete this.b,W.L.F.call(this)},x(gd,jc),x(hd,kc),x(X,dd),X.prototype.zd=function(){Zb(this.b.s,"WebChannel opened on "+this.b.zb),this.b.dispatchEvent("a")},X.prototype.xd=function(e){this.b.dispatchEvent(new gd(e))},X.prototype.wd=function(e){Zb(this.b.s,"WebChannel aborted on "+this.b.zb+" due to channel error: "+e),this.b.dispatchEvent(new hd(e))},X.prototype.vd=function(){Zb(this.b.s,"WebChannel closed on "+this.b.zb),this.b.dispatchEvent("b")};var id$1=v(function(e,t){function n(){}n.prototype=e.prototype;var r=new n;return e.apply(r,Array.prototype.slice.call(arguments,1)),r},fd);function jd(){this.V=[],this.Z=[]}function kd(e,t){if(z.call(this),this.re=e||0,this.Xb=t||10,this.re>this.Xb)throw Error(ld);this.fa=new jd,this.oa=new Nc,this.Cc=0,this.Pc=null,this.Db()}e=jd.prototype,e.Zf=function(){0==this.V.length&&(this.V=this.Z,this.V.reverse(),this.Z=[])},e.enqueue=function(e){this.Z.push(e)},e.bb=function(){return this.Zf(),this.V.pop()},e.C=function(){return this.V.length+this.Z.length},e.X=function(){return 0==this.V.length&&0==this.Z.length},e.clear=function(){this.V=[],this.Z=[]},e.contains=function(e){return 0<=la(this.V,e)||0<=la(this.Z,e)},e.remove=function(e){var t=this.V,n=ma(t,e);return 0<=n?(Array.prototype.splice.call(t,n,1),t=!0):t=!1,t||sa(this.Z,e)},e.H=function(){for(var e=[],t=this.V.length-1;0<=t;--t)e.push(this.V[t]);var n=this.Z.length;for(t=0;t<n;++t)e.push(this.Z[t]);return e},x(kd,z);var ld="[goog.structs.Pool] Min can not be greater than max";function md(e,t){this.ie=e,this.kd=t}function nd(e){this.Y=[],e&&this.Pf(e)}function od(){nd.call(this)}function Y(e,t){this.Jd=void 0,this.dc=new od,kd.call(this,e,t)}function Z(e,t,n,r){this.Nf=e,this.Bb=!!r,Y.call(this,t,n)}e=kd.prototype,e.Nb=function(){var e=w();if(!(null!=this.Pc&&e-this.Pc<this.Cc)){var t=this.ug();return t&&(this.Pc=e,this.oa.add(t)),t}},e.sg=function(e){return!!this.oa.remove(e)&&(this.pc(e),!0)},e.ug=function(){for(var e;0<this.Wd()&&(e=this.fa.bb(),!this.Uc(e));)this.Db();return!e&&this.C()<this.Xb&&(e=this.zc()),e},e.pc=function(e){this.oa.remove(e),this.Uc(e)&&this.C()<this.Xb?this.fa.enqueue(e):this.Dc(e)},e.Db=function(){for(var e=this.fa;this.C()<this.re;)e.enqueue(this.zc());for(;this.C()>this.Xb&&0<this.Wd();)this.Dc(e.bb())},e.zc=function(){return{}},e.Dc=function(e){if("function"==typeof e.cb)e.cb();else for(var t in e)e[t]=null},e.Uc=function(e){return"function"!=typeof e.bf||e.bf()},e.contains=function(e){return this.fa.contains(e)||this.oa.contains(e)},e.C=function(){return this.fa.C()+this.oa.C()},e.vf=function(){return this.oa.C()},e.Wd=function(){return this.fa.C()},e.X=function(){return this.fa.X()&&this.oa.X()},e.F=function(){if(kd.L.F.call(this),0<this.vf())throw Error("[goog.structs.Pool] Objects not released");delete this.oa;for(var e=this.fa;!e.X();)this.Dc(e.bb());delete this.fa},md.prototype.getKey=function(){return this.ie},md.prototype.clone=function(){return new md(this.ie,this.kd)},e=nd.prototype,e.fe=function(e,t){var n=this.Y;n.push(new md(e,t)),this.dg(n.length-1)},e.Pf=function(e){if(e instanceof nd){var t=e.W();if(e=e.H(),0>=this.C()){for(var n=this.Y,r=0;r<t.length;r++)n.push(new md(t[r],e[r]));return}}else t=Ca(e),e=Ba(e);for(r=0;r<t.length;r++)this.fe(t[r],e[r])},e.remove=function(){var e=this.Y,t=e.length,n=e[0];if(!(0>=t))return 1==t?ra(e):(e[0]=e.pop(),this.cg()),n.kd},e.cg=function(){for(var e=0,t=this.Y,n=t.length,r=t[e];e<n>>1;){var i=this.xf(e),o=this.Df(e);if(t[i=o<n&&t[o].getKey()<t[i].getKey()?o:i].getKey()>r.getKey())break;t[e]=t[i],e=i}t[e]=r},e.dg=function(e){for(var t=this.Y,n=t[e];0<e;){var r=this.Af(e);if(!(t[r].getKey()>n.getKey()))break;t[e]=t[r],e=r}t[e]=n},e.xf=function(e){return 2*e+1},e.Df=function(e){return 2*e+2},e.Af=function(e){return e-1>>1},e.H=function(){for(var e=this.Y,t=[],n=e.length,r=0;r<n;r++)t.push(e[r].kd);return t},e.W=function(){for(var e=this.Y,t=[],n=e.length,r=0;r<n;r++)t.push(e[r].getKey());return t},e.va=function(e){return oa(this.Y,function(t){return t.getKey()==e})},e.clone=function(){return new nd(this)},e.C=function(){return this.Y.length},e.X=function(){return 0==this.Y.length},e.clear=function(){ra(this.Y)},x(od,nd),od.prototype.enqueue=function(e,t){this.fe(e,t)},od.prototype.bb=function(){return this.remove()},x(Y,kd),e=Y.prototype,e.Nb=function(e,t){if(!e)return(e=Y.L.Nb.call(this))&&this.Cc&&(this.Jd=h.setTimeout(u(this.Ob,this),this.Cc)),e;this.dc.enqueue(void 0!==t?t:100,e),this.Ob()},e.Ob=function(){for(var e=this.dc;0<e.C();){var t=this.Nb();if(!t)break;e.bb().apply(this,[t])}},e.pc=function(e){Y.L.pc.call(this,e),this.Ob()},e.Db=function(){Y.L.Db.call(this),this.Ob()},e.F=function(){Y.L.F.call(this),h.clearTimeout(this.Jd),this.dc.clear(),this.dc=null},x(Z,Y),Z.prototype.zc=function(){var e=new V,t=this.Nf;return t&&t.forEach(function(t,n){e.headers.set(n,t)}),this.Bb&&e.Ne(!0),e},Z.prototype.Uc=function(e){return!e.Ka&&!e.Ba()},fd.prototype.createWebChannel=fd.prototype.gf,W.prototype.send=W.prototype.send,W.prototype.open=W.prototype.open,W.prototype.close=W.prototype.close,ec.NO_ERROR=0,ec.TIMEOUT=8,ec.HTTP_ERROR=6,fc.COMPLETE="complete",hc.EventType=ic,ic.OPEN="a",ic.CLOSE="b",ic.ERROR="c",ic.MESSAGE="d",H.prototype.listen=H.prototype.ob,Z.prototype.getObject=Z.prototype.Nb,Z.prototype.releaseObject=Z.prototype.sg,V.prototype.listenOnce=V.prototype.Qc,V.prototype.getLastError=V.prototype.Jc,V.prototype.getLastErrorCode=V.prototype.Xd,V.prototype.getStatus=V.prototype.za,V.prototype.getStatusText=V.prototype.ae,V.prototype.getResponseJson=V.prototype.Cf,V.prototype.getResponseText=V.prototype.ya,V.prototype.getResponseText=V.prototype.ya,V.prototype.send=V.prototype.send;var src={createWebChannelTransport:id$1,ErrorCode:ec,EventType:fc,WebChannel:hc,XhrIoPool:Z},src_1=src.createWebChannelTransport,src_2=src.ErrorCode,src_3=src.EventType,src_4=src.WebChannel,src_5=src.XhrIoPool,SDK_VERSION=firebase.SDK_VERSION,logClient$1=new Logger("@firebase/firestore"),LogLevel$1,LogLevel$$1;function getLogLevel(){return logClient$1.logLevel===LogLevel.DEBUG?LogLevel$1.DEBUG:logClient$1.logLevel===LogLevel.SILENT?LogLevel$1.SILENT:LogLevel$1.ERROR}function setLogLevel$1(e){switch(e){case LogLevel$1.DEBUG:logClient$1.logLevel=LogLevel.DEBUG;break;case LogLevel$1.ERROR:logClient$1.logLevel=LogLevel.ERROR;break;case LogLevel$1.SILENT:logClient$1.logLevel=LogLevel.SILENT;break;default:logClient$1.error("Firestore ("+SDK_VERSION+"): Invalid value passed to `setLogLevel`")}}function debug(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(logClient$1.logLevel<=LogLevel.DEBUG){var i=n.map(argToString);logClient$1.debug.apply(logClient$1,["Firestore ("+SDK_VERSION+") ["+e+"]: "+t].concat(i))}}function error$2(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(logClient$1.logLevel<=LogLevel.ERROR){var r=t.map(argToString);logClient$1.error.apply(logClient$1,["Firestore ("+SDK_VERSION+"): "+e].concat(r))}}function argToString(e){if("string"==typeof e)return e;var t=PlatformSupport.getPlatform();try{return t.formatJSON(e)}catch(t){return e}}function fail(e){var t="FIRESTORE ("+SDK_VERSION+") INTERNAL ASSERTION FAILED: "+e;throw error$2(t),new Error(t)}function assert$1(e,t){e||fail(t)}LogLevel$$1=LogLevel$1||(LogLevel$1={}),LogLevel$$1[LogLevel$$1.DEBUG=0]="DEBUG",LogLevel$$1[LogLevel$$1.ERROR=1]="ERROR",LogLevel$$1[LogLevel$$1.SILENT=2]="SILENT";var PlatformSupport=function(){function e(){}return e.setPlatform=function(t){e.platform&&fail("Platform already defined"),e.platform=t},e.getPlatform=function(){return e.platform||fail("Platform not set"),e.platform},e}();function emptyByteString(){return PlatformSupport.getPlatform().emptyByteString}var Code={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"},FirestoreError=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 __extends(t,e),t}(Error);function makeConstructorPrivate(e,t){function n(){var e="This constructor is private.";throw t&&(e+=" ",e+=t),new FirestoreError(Code.INVALID_ARGUMENT,e)}for(var r in n.prototype=e.prototype,e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n}function contains$2(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function defaulted(e,t){return void 0!==e?e:t}function forEachNumber(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 forEach$1(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function isEmpty$1(e){for(var t in assert$1(null!=e&&"object"==typeof e,"isEmpty() expects object parameter."),e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function shallowCopy(e){assert$1(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}function validateExactNumberOfArgs(e,t,n){if(t.length!==n)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires "+formatPlural(n,"argument")+", but was called with "+formatPlural(t.length,"argument")+".")}function validateAtLeastNumberOfArgs(e,t,n){if(t.length<n)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires at least "+formatPlural(n,"argument")+", but was called with "+formatPlural(t.length,"argument")+".")}function validateBetweenNumberOfArgs(e,t,n,r){if(t.length<n||t.length>r)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires between "+n+" and "+r+" arguments, but was called with "+formatPlural(t.length,"argument")+".")}function validateNamedArrayAtLeastNumberOfElements(e,t,n,r){if(!(t instanceof Array)||t.length<r)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires its "+n+" argument to be an array with at least "+formatPlural(r,"element")+".")}function validateArgType(e,t,n,r){validateType(e,t,ordinal(n)+" argument",r)}function validateOptionalArgType(e,t,n,r){void 0!==r&&validateArgType(e,t,n,r)}function validateNamedType(e,t,n,r){validateType(e,t,n+" option",r)}function validateNamedOptionalType(e,t,n,r){void 0!==r&&validateNamedType(e,t,n,r)}function validateArrayElements(e,t,n,r,i){if(!(r instanceof Array))throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires its "+t+" option to be an array, but it was: "+valueDescription(r));for(var o=0;o<r.length;++o)if(!i(r[o]))throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires all "+t+" elements to be "+n+", but the value at index "+o+" was: "+valueDescription(r[o]))}function validateOptionalArrayElements(e,t,n,r,i){void 0!==r&&validateArrayElements(e,t,n,r,i)}function validateNamedPropertyEquals(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(valueDescription(u))}var c=valueDescription(r);throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid value "+c+" provided to function "+e+'() for option "'+n+'". Acceptable values: '+o.join(", "))}function validateNamedOptionalPropertyEquals(e,t,n,r,i){void 0!==r&&validateNamedPropertyEquals(e,t,n,r,i)}function validateType(e,t,n,r){if(!("object"===t?isPlainObject(r):"non-empty string"===t?"string"==typeof r&&""!==r:typeof r===t)){var i=valueDescription(r);throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires its "+n+" to be of type "+t+", but it was: "+i)}}function isPlainObject(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function valueDescription(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=tryGetCustomObjectType(e);return t?"a custom "+t+" object":"an object"}return"function"==typeof e?"a function":fail("Unknown wrong type: "+typeof e)}function tryGetCustomObjectType(e){if(e.constructor){var t=/function\s+([^\s(]+)\s*\(/.exec(e.constructor.toString());if(t&&t.length>1)return t[1]}return null}function validateDefined(e,t,n){if(void 0===n)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires a valid "+ordinal(t)+" argument, but it was undefined.")}function validateOptionNames(e,t,n){forEach$1(t,function(t,r){if(n.indexOf(t)<0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Unknown option '"+t+"' passed to function "+e+"(). Available options: "+n.join(", "))})}function invalidClassError(e,t,n,r){var i=valueDescription(r);return new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() requires its "+ordinal(n)+" argument to be a "+t+", but it was: "+i)}function ordinal(e){switch(e){case 1:return"first";case 2:return"second";case 3:return"third";default:return e+"th"}}function formatPlural(e,t){return e+" "+t+(1===e?"":"s")}var AutoId=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 assert$1(20===t.length,"Invalid auto ID: "+t),t},e}();function primitiveComparator(e,t){return e<t?-1:e>t?1:0}function equals(e,t){return null!==e&&void 0!==e?!(!t||!e.isEqual(t)):e===t}function arrayEquals(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 immediateSuccessor(e){return e+"\0"}function assertUint8ArrayAvailable(){if("undefined"==typeof Uint8Array)throw new FirestoreError(Code.UNIMPLEMENTED,"Uint8Arrays are not available in this environment.")}function assertBase64Available(){if(!PlatformSupport.getPlatform().base64Available)throw new FirestoreError(Code.UNIMPLEMENTED,"Blobs are unavailable in Firestore in this environment.")}var Blob$1=function(){function e(e){assertBase64Available(),this._binaryString=e}return e.fromBase64String=function(t){validateExactNumberOfArgs("Blob.fromBase64String",arguments,1),validateArgType("Blob.fromBase64String","string",1,t),assertBase64Available();try{return new e(PlatformSupport.getPlatform().atob(t))}catch(e){throw new FirestoreError(Code.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+e)}},e.fromUint8Array=function(t){if(validateExactNumberOfArgs("Blob.fromUint8Array",arguments,1),assertUint8ArrayAvailable(),!(t instanceof Uint8Array))throw invalidClassError("Blob.fromUint8Array","Uint8Array",1,t);return new e(Array.prototype.map.call(t,function(e){return String.fromCharCode(e)}).join(""))},e.prototype.toBase64=function(){return validateExactNumberOfArgs("Blob.toBase64",arguments,0),assertBase64Available(),PlatformSupport.getPlatform().btoa(this._binaryString)},e.prototype.toUint8Array=function(){validateExactNumberOfArgs("Blob.toUint8Array",arguments,0),assertUint8ArrayAvailable();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 primitiveComparator(this._binaryString,e._binaryString)},e}(),PublicBlob=makeConstructorPrivate(Blob$1,"Use Blob.fromUint8Array() or Blob.fromBase64String() instead."),GeoPoint=function(){function e(e,t){if(validateExactNumberOfArgs("GeoPoint",arguments,2),validateArgType("GeoPoint","number",1,e),validateArgType("GeoPoint","number",2,t),!isFinite(e)||e<-90||e>90)throw new FirestoreError(Code.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new FirestoreError(Code.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 primitiveComparator(this._lat,e._lat)||primitiveComparator(this._long,e._long)},e}(),Timestamp=function(){function e(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new FirestoreError(Code.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new FirestoreError(Code.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new FirestoreError(Code.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?primitiveComparator(this.nanoseconds,e.nanoseconds):primitiveComparator(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}(),DatabaseInfo=function(){return function(e,t,n,r){this.databaseId=e,this.persistenceKey=t,this.host=n,this.ssl=r}}(),DEFAULT_DATABASE_NAME="(default)",DatabaseId=function(){function e(e,t){this.projectId=e,this.database=t||DEFAULT_DATABASE_NAME}return Object.defineProperty(e.prototype,"isDefaultDatabase",{get:function(){return this.database===DEFAULT_DATABASE_NAME},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 primitiveComparator(this.projectId,e.projectId)||primitiveComparator(this.database,e.database)},e}(),DOCUMENT_KEY_NAME="__name__",Path$1=function(){function e(e,t,n){this.init(e,t,n)}return e.prototype.init=function(e,t,n){void 0===t?t=0:t>e.length&&fail("offset "+t+" out of range "+e.length),void 0===n?n=e.length-t:n>e.length-t&&fail("length "+n+" out of range "+(e.length-t)),this.segments=e,this.offset=t,this.len=n},e.prototype.construct=function(e,t,n){var r=Object.create(Object.getPrototypeOf(this));return r.init(e,t,n),r},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)}):"string"==typeof t?n.push(t):fail("Unknown parameter type for Path.child(): "+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,assert$1(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 assert$1(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},e.prototype.firstSegment=function(){return assert$1(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},e.prototype.lastSegment=function(){return assert$1(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},e.prototype.get=function(e){return assert$1(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}(),ResourcePath=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),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 FirestoreError(Code.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}(Path$1),identifierRegExp=/^[_a-zA-Z][_a-zA-Z0-9]*$/,FieldPath=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.isValidIdentifier=function(e){return identifierRegExp.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)===DOCUMENT_KEY_NAME},t.keyField=function(){return new t([DOCUMENT_KEY_NAME])},t.fromServerFormat=function(e){for(var n=[],r="",i=0,o=function(){if(0===r.length)throw new FirestoreError(Code.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 FirestoreError(Code.INVALID_ARGUMENT,"Path has trailing escape character: "+e);var u=e[i+1];if("\\"!==u&&"."!==u&&"`"!==u)throw new FirestoreError(Code.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 FirestoreError(Code.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new t(n)},t.EMPTY_PATH=new t([]),t}(Path$1),DocumentKey=function(){function e(t){this.path=t,assert$1(e.isDocumentKey(t),"Invalid DocumentKey with an odd number of segments: "+t.toArray().join("/"))}return e.prototype.isEqual=function(e){return null!==e&&0===ResourcePath.comparator(this.path,e.path)},e.prototype.toString=function(){return this.path.toString()},e.comparator=function(e,t){return ResourcePath.comparator(e.path,t.path)},e.isDocumentKey=function(e){return e.length%2==0},e.fromSegments=function(t){return new e(new ResourcePath(t.slice()))},e.fromPathString=function(t){return new e(ResourcePath.fromString(t))},e.EMPTY=new e(new ResourcePath([])),e}(),MaybeDocument=function(){function e(e,t){this.key=e,this.version=t}return e.compareByKey=function(e,t){return DocumentKey.comparator(e.key,t.key)},e}(),Document=function(e){function t(t,n,r,i){var o=e.call(this,t,n)||this;return o.data=r,o.hasLocalMutations=!!i.hasLocalMutations,o.hasCommittedMutations=!!i.hasCommittedMutations,o}return __extends(t,e),t.prototype.field=function(e){return this.data.field(e)},t.prototype.fieldValue=function(e){var t=this.field(e);return t?t.value():void 0},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.data.isEqual(e.data)&&this.hasLocalMutations===e.hasLocalMutations&&this.hasCommittedMutations===e.hasCommittedMutations},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.compareByField=function(e,t,n){var r=t.field(e),i=n.field(e);return void 0!==r&&void 0!==i?r.compareTo(i):fail("Trying to compare documents on fields that don't exist")},t}(MaybeDocument),NoDocument=function(e){function t(t,n,r){var i=e.call(this,t,n)||this;return i.hasCommittedMutations=!(!r||!r.hasCommittedMutations),i}return __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.version.isEqual(this.version)&&e.key.isEqual(this.key)},t}(MaybeDocument),UnknownDocument=function(e){function t(t,n){return e.call(this,t,n)||this}return __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}),t.prototype.isEqual=function(e){return e instanceof t&&e.version.isEqual(this.version)&&e.key.isEqual(this.key)},t}(MaybeDocument),SortedMap$1=function(){function e(e,t){this.comparator=e,this.root=t||LLRBNode$1.EMPTY}return e.prototype.insert=function(t,n){return new e(this.comparator,this.root.insert(t,n,this.comparator).copy(null,null,LLRBNode$1.BLACK,null,null))},e.prototype.remove=function(t){return new e(this.comparator,this.root.remove(t,this.comparator).copy(null,null,LLRBNode$1.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.reverseTraversal=function(e){return this.root.reverseTraversal(e)},e.prototype.getIterator=function(){return new SortedMapIterator$1(this.root,null,this.comparator,!1)},e.prototype.getIteratorFrom=function(e){return new SortedMapIterator$1(this.root,e,this.comparator,!1)},e.prototype.getReverseIterator=function(){return new SortedMapIterator$1(this.root,null,this.comparator,!0)},e.prototype.getReverseIteratorFrom=function(e){return new SortedMapIterator$1(this.root,e,this.comparator,!0)},e}(),SortedMapIterator$1=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(){assert$1(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}(),LLRBNode$1=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 fail("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw fail("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check();if(e!==this.right.check())throw fail("Black depths differ");return e+(this.isRed()?0:1)},e.EMPTY=null,e.RED=!0,e.BLACK=!1,e}(),LLRBEmptyNode$1=function(){function e(){this.size=0}return e.prototype.copy=function(e,t,n,r,i){return this},e.prototype.insert=function(e,t,n){return new LLRBNode$1(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}(),TypeOrder,ServerTimestampBehavior;LLRBNode$1.EMPTY=new LLRBEmptyNode$1,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"}(TypeOrder||(TypeOrder={})),function(e){e[e.Default=0]="Default",e[e.Estimate=1]="Estimate",e[e.Previous=2]="Previous"}(ServerTimestampBehavior||(ServerTimestampBehavior={}));var FieldValueOptions=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(ServerTimestampBehavior.Estimate,n);case"previous":return new e(ServerTimestampBehavior.Previous,n);case"none":case void 0:return new e(ServerTimestampBehavior.Default,n);default:return fail("fromSnapshotOptions() called with invalid options.")}},e}(),FieldValue=function(){function e(){}return e.prototype.toString=function(){var e=this.value();return null===e?"null":e.toString()},e.prototype.defaultCompareTo=function(e){return assert$1(this.typeOrder!==e.typeOrder,"Default compareTo should not be used for values of same type."),primitiveComparator(this.typeOrder,e.typeOrder)},e}(),NullValue=function(e){function t(){var t=e.call(this)||this;return t.typeOrder=TypeOrder.NullValue,t.internalValue=null,t}return __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}(FieldValue),BooleanValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.BooleanValue,n}return __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?primitiveComparator(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}(FieldValue),NumberValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.NumberValue,n}return __extends(t,e),t.prototype.value=function(e){return this.internalValue},t.prototype.compareTo=function(e){return e instanceof t?numericComparator(this.internalValue,e.internalValue):this.defaultCompareTo(e)},t}(FieldValue);function numericComparator(e,t){return e<t?-1:e>t?1:e===t?0:isNaN(e)?isNaN(t)?0:-1:1}function numericEquals(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}var IntegerValue=function(e){function t(t){return e.call(this,t)||this}return __extends(t,e),t.prototype.isEqual=function(e){return e instanceof t&&numericEquals(this.internalValue,e.internalValue)},t}(NumberValue),DoubleValue=function(e){function t(t){var n=e.call(this,t)||this;return n.internalValue=t,n}return __extends(t,e),t.prototype.isEqual=function(e){return e instanceof t&&numericEquals(this.internalValue,e.internalValue)},t.NAN=new t(NaN),t.POSITIVE_INFINITY=new t(1/0),t.NEGATIVE_INFINITY=new t(-1/0),t}(NumberValue),StringValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.StringValue,n}return __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?primitiveComparator(this.internalValue,e.internalValue):this.defaultCompareTo(e)},t}(FieldValue),TimestampValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.TimestampValue,n}return __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 ServerTimestampValue?-1:this.defaultCompareTo(e)},t}(FieldValue),ServerTimestampValue=function(e){function t(t,n){var r=e.call(this)||this;return r.localWriteTime=t,r.previousValue=n,r.typeOrder=TypeOrder.TimestampValue,r}return __extends(t,e),t.prototype.value=function(e){return e&&e.serverTimestampBehavior===ServerTimestampBehavior.Estimate?new TimestampValue(this.localWriteTime).value(e):e&&e.serverTimestampBehavior===ServerTimestampBehavior.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 TimestampValue?1:this.defaultCompareTo(e)},t.prototype.toString=function(){return"<ServerTimestamp localTime="+this.localWriteTime.toString()+">"},t}(FieldValue),BlobValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.BlobValue,n}return __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}(FieldValue),RefValue=function(e){function t(t,n){var r=e.call(this)||this;return r.databaseId=t,r.key=n,r.typeOrder=TypeOrder.RefValue,r}return __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:DocumentKey.comparator(this.key,e.key)}return this.defaultCompareTo(e)},t}(FieldValue),GeoPointValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.GeoPointValue,n}return __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}(FieldValue),ObjectValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.ObjectValue,n}return __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=primitiveComparator(i.key,o.key)||i.value.compareTo(o.value);if(a)return a}return primitiveComparator(n.hasNext(),r.hasNext())}return this.defaultCompareTo(e)},t.prototype.set=function(e,n){if(assert$1(!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(assert$1(!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 void 0!==this.field(e)},t.prototype.field=function(e){assert$1(!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)||void 0}),n},t.prototype.toString=function(){return JSON.stringify(this.value())},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 SortedMap$1(primitiveComparator)),t}(FieldValue),ArrayValue=function(e){function t(t){var n=e.call(this)||this;return n.internalValue=t,n.typeOrder=TypeOrder.ArrayValue,n}return __extends(t,e),t.prototype.value=function(e){return this.internalValue.map(function(t){return t.value(e)})},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 primitiveComparator(this.internalValue.length,e.internalValue.length)}return this.defaultCompareTo(e)},t.prototype.toString=function(){return JSON.stringify(this.value())},t}(FieldValue),NumberAsAny=Number,MIN_SAFE_INTEGER=NumberAsAny.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),MAX_SAFE_INTEGER=NumberAsAny.MAX_SAFE_INTEGER||Math.pow(2,53)-1,isInteger=NumberAsAny.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function isNullOrUndefined(e){return null===e||void 0===e}function isSafeInteger(e){return isInteger(e)&&e<=MAX_SAFE_INTEGER&&e>=MIN_SAFE_INTEGER}var Query$1=function(){function e(e,t,n,r,i,o){void 0===t&&(t=[]),void 0===n&&(n=[]),void 0===r&&(r=null),void 0===i&&(i=null),void 0===o&&(o=null),this.path=e,this.explicitOrderBy=t,this.filters=n,this.limit=r,this.startAt=i,this.endAt=o,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}return 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=[KEY_ORDERING_ASC]:this.memoizedOrderBy=[new OrderBy(e),KEY_ORDERING_ASC];else{assert$1(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:Direction.ASCENDING;this.memoizedOrderBy.push(a===Direction.ASCENDING?KEY_ORDERING_ASC:KEY_ORDERING_DESC)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),e.prototype.addFilter=function(t){assert$1(null==this.getInequalityFilterField()||!(t instanceof RelationFilter)||!t.isInequality()||t.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),assert$1(!DocumentKey.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([t]);return new e(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},e.prototype.addOrderBy=function(t){assert$1(!DocumentKey.isDocumentKey(this.path),"No ordering allowed for document query"),assert$1(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([t]);return new e(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},e.prototype.withLimit=function(t){return new e(this.path,this.explicitOrderBy.slice(),this.filters.slice(),t,this.startAt,this.endAt)},e.prototype.withStartAt=function(t){return new e(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,t,this.endAt)},e.prototype.withEndAt=function(t){return new e(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,t)},e.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var e=this.path.canonicalString();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+=","}isNullOrUndefined(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},e.prototype.toString=function(){var e="Query("+this.path.canonicalString();return this.filters.length>0&&(e+=", filters: ["+this.filters.join(", ")+"]"),isNullOrUndefined(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.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 assert$1(n,"orderBy used that doesn't compare on key field"),0},e.prototype.matches=function(e){return this.matchesAncestor(e)&&this.matchesOrderBy(e)&&this.matchesFilters(e)&&this.matchesBounds(e)},e.prototype.hasLimit=function(){return!isNullOrUndefined(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 RelationFilter&&n.isInequality())return n.field}return null},e.prototype.hasArrayContainsFilter=function(){return void 0!==this.filters.find(function(e){return e instanceof RelationFilter&&e.op===RelationOp.ARRAY_CONTAINS})},e.prototype.isDocumentQuery=function(){return DocumentKey.isDocumentKey(this.path)&&0===this.filters.length},e.prototype.matchesAncestor=function(e){var t=e.key.path;return DocumentKey.isDocumentKey(this.path)?this.path.isEqual(t):this.path.isPrefixOf(t)&&this.path.length===t.length-1},e.prototype.matchesOrderBy=function(e){for(var t=0,n=this.explicitOrderBy;t<n.length;t++){var r=n[t];if(!r.field.isKeyField()&&void 0===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){assert$1(e.position.length<=this.orderBy.length,"Bound is longer than orderBy")},e}(),Filter=function(){function e(){}return e.create=function(e,t,n){if(n.isEqual(NullValue.INSTANCE)){if(t!==RelationOp.EQUAL)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new NullFilter(e)}if(n.isEqual(DoubleValue.NAN)){if(t!==RelationOp.EQUAL)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new NanFilter(e)}return new RelationFilter(e,t,n)},e}(),RelationOp=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;default:return fail("Unknown relation: "+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}(),RelationFilter=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 __extends(t,e),t.prototype.matches=function(e){if(this.field.isKeyField()){assert$1(this.value instanceof RefValue,"Comparing on key, but filter value not a RefValue"),assert$1(this.op!==RelationOp.ARRAY_CONTAINS,"array-contains queries don't make sense on document keys.");var t=this.value,n=DocumentKey.comparator(e.key,t.key);return this.matchesComparison(n)}var r=e.field(this.field);return void 0!==r&&this.matchesValue(r)},t.prototype.matchesValue=function(e){var t=this;return this.op===RelationOp.ARRAY_CONTAINS?e instanceof ArrayValue&&void 0!==e.internalValue.find(function(e){return e.isEqual(t.value)}):this.value.typeOrder===e.typeOrder&&this.matchesComparison(e.compareTo(this.value))},t.prototype.matchesComparison=function(e){switch(this.op){case RelationOp.LESS_THAN:return e<0;case RelationOp.LESS_THAN_OR_EQUAL:return e<=0;case RelationOp.EQUAL:return 0===e;case RelationOp.GREATER_THAN:return e>0;case RelationOp.GREATER_THAN_OR_EQUAL:return e>=0;default:return fail("Unknown relation op"+this.op)}},t.prototype.isInequality=function(){return this.op!==RelationOp.EQUAL&&this.op!==RelationOp.ARRAY_CONTAINS},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}(Filter),NullFilter=function(e){function t(t){var n=e.call(this)||this;return n.field=t,n}return __extends(t,e),t.prototype.matches=function(e){var t=e.field(this.field);return void 0!==t&&null===t.value()},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},t.prototype.toString=function(){return this.field.canonicalString()+" IS null"},t.prototype.isEqual=function(e){return e instanceof t&&this.field.isEqual(e.field)},t}(Filter),NanFilter=function(e){function t(t){var n=e.call(this)||this;return n.field=t,n}return __extends(t,e),t.prototype.matches=function(e){var t=e.field(this.field),n=t&&t.value();return"number"==typeof n&&isNaN(n)},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.isEqual=function(e){return e instanceof t&&this.field.isEqual(e.field)},t}(Filter),Direction=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}(),Bound=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){assert$1(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())assert$1(o instanceof RefValue,"Bound has a non-key value where the key path is being used."),n=DocumentKey.comparator(o.key,t.key);else{var a=t.field(i.field);assert$1(void 0!==a,"Field should exist since document matched the orderBy already."),n=o.compareTo(a)}if(i.dir===Direction.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];return n.isEqual(r)}return!0},e}(),OrderBy=function(){function e(e,t){this.field=e,void 0===t&&(t=Direction.ASCENDING),this.dir=t,this.isKeyOrderBy=e.isKeyField()}return e.prototype.compare=function(e,t){var n=this.isKeyOrderBy?Document.compareByKey(e,t):Document.compareByField(this.field,e,t);switch(this.dir){case Direction.ASCENDING:return n;case Direction.DESCENDING:return-1*n;default:return fail("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}(),KEY_ORDERING_ASC=new OrderBy(FieldPath.keyField(),Direction.ASCENDING),KEY_ORDERING_DESC=new OrderBy(FieldPath.keyField(),Direction.DESCENDING),SnapshotVersion=function(){function e(e){this.timestamp=e}return e.fromMicroseconds=function(t){var n=Math.floor(t/1e6);return new e(new Timestamp(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 Timestamp(0,0)),e}(),QueryPurpose;!function(e){e[e.Listen=0]="Listen",e[e.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",e[e.LimboResolution=2]="LimboResolution"}(QueryPurpose||(QueryPurpose={}));var QueryData=function(){function e(e,t,n,r,i,o){void 0===i&&(i=SnapshotVersion.MIN),void 0===o&&(o=emptyByteString()),this.query=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.resumeToken=o}return e.prototype.copy=function(t){return new e(this.query,this.targetId,this.purpose,void 0===t.sequenceNumber?this.sequenceNumber:t.sequenceNumber,void 0===t.snapshotVersion?this.snapshotVersion:t.snapshotVersion,void 0===t.resumeToken?this.resumeToken:t.resumeToken)},e.prototype.isEqual=function(e){return this.targetId===e.targetId&&this.purpose===e.purpose&&this.sequenceNumber===e.sequenceNumber&&this.snapshotVersion.isEqual(e.snapshotVersion)&&this.resumeToken===e.resumeToken&&this.query.isEqual(e.query)},e}(),FieldMask=function(){function e(e){this.fields=e}return e.prototype.covers=function(e){for(var t=0,n=this.fields;t<n.length;t++){if(n[t].isPrefixOf(e))return!0}return!1},e.prototype.isEqual=function(e){return arrayEquals(this.fields,e.fields)},e}(),FieldTransform=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}(),MutationResult=function(){return function(e,t){this.version=e,this.transformResults=t}}(),MutationType;!function(e){e[e.Set=0]="Set",e[e.Patch=1]="Patch",e[e.Transform=2]="Transform",e[e.Delete=3]="Delete"}(MutationType||(MutationType={}));var Precondition=function(){function e(e,t){this.updateTime=e,this.exists=t,assert$1(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 Document&&e.version.isEqual(this.updateTime):void 0!==this.exists?this.exists===e instanceof Document:(assert$1(this.isNone,"Precondition should be empty"),!0)},e.prototype.isEqual=function(e){return equals(this.updateTime,e.updateTime)&&this.exists===e.exists},e.NONE=new e,e}(),Mutation=function(){function e(){}return e.prototype.verifyKeyMatches=function(e){null!=e&&assert$1(e.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")},e.getPostMutationVersion=function(e){return e instanceof Document?e.version:SnapshotVersion.MIN},e}(),SetMutation=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=MutationType.Set,i}return __extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){this.verifyKeyMatches(e),assert$1(null==t.transformResults,"Transform results received by SetMutation.");var n=t.version;return new Document(this.key,n,this.value,{hasCommittedMutations:!0})},t.prototype.applyToLocalView=function(e,t,n){if(this.verifyKeyMatches(e),!this.precondition.isValidFor(e))return e;var r=Mutation.getPostMutationVersion(e);return new Document(this.key,r,this.value,{hasLocalMutations:!0})},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}(Mutation),PatchMutation=function(e){function t(t,n,r,i){var o=e.call(this)||this;return o.key=t,o.data=n,o.fieldMask=r,o.precondition=i,o.type=MutationType.Patch,o}return __extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){if(this.verifyKeyMatches(e),assert$1(null==t.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(e))return new UnknownDocument(this.key,t.version);var n=this.patchDocument(e);return new Document(this.key,t.version,n,{hasCommittedMutations:!0})},t.prototype.applyToLocalView=function(e,t,n){if(this.verifyKeyMatches(e),!this.precondition.isValidFor(e))return e;var r=Mutation.getPostMutationVersion(e),i=this.patchDocument(e);return new Document(this.key,r,i,{hasLocalMutations:!0})},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 Document?e.data:ObjectValue.EMPTY,this.patchObject(t)},t.prototype.patchObject=function(e){for(var t=0,n=this.fieldMask.fields;t<n.length;t++){var r=n[t];if(!r.isEmpty()){var i=this.data.field(r);e=void 0!==i?e.set(r,i):e.delete(r)}}return e},t}(Mutation),TransformMutation=function(e){function t(t,n){var r=e.call(this)||this;return r.key=t,r.fieldTransforms=n,r.type=MutationType.Transform,r.precondition=Precondition.exists(!0),r}return __extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){if(this.verifyKeyMatches(e),assert$1(null!=t.transformResults,"Transform results missing for TransformMutation."),!this.precondition.isValidFor(e))return new UnknownDocument(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 Document(this.key,i,o,{hasCommittedMutations:!0})},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,t),o=this.transformObject(r.data,i);return new Document(this.key,r.version,o,{hasLocalMutations:!0})},t.prototype.isEqual=function(e){return e instanceof t&&this.key.isEqual(e.key)&&arrayEquals(this.fieldTransforms,e.fieldTransforms)&&this.precondition.isEqual(e.precondition)},t.prototype.requireDocument=function(e){assert$1(e instanceof Document,"Unknown MaybeDocument type "+e);var t=e;return assert$1(t.key.isEqual(this.key),"Can only transform a document with the same key"),t},t.prototype.serverTransformResults=function(e,t){var n=[];assert$1(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 Document&&(a=e.field(i.field)||null),n.push(o.applyToRemoteDocument(a,t[r]))}return n},t.prototype.localTransformResults=function(e,t){for(var n=[],r=0,i=this.fieldTransforms;r<i.length;r++){var o=i[r],a=o.transform,s=null;t instanceof Document&&(s=t.field(o.field)||null),n.push(a.applyToLocalView(s,e))}return n},t.prototype.transformObject=function(e,t){assert$1(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}(Mutation),DeleteMutation=function(e){function t(t,n){var r=e.call(this)||this;return r.key=t,r.precondition=n,r.type=MutationType.Delete,r}return __extends(t,e),t.prototype.applyToRemoteDocument=function(e,t){return this.verifyKeyMatches(e),assert$1(null==t.transformResults,"Transform results received by DeleteMutation."),new NoDocument(this.key,t.version,{hasCommittedMutations:!0})},t.prototype.applyToLocalView=function(e,t,n){return this.verifyKeyMatches(e),this.precondition.isValidFor(e)?(e&&assert$1(e.key.isEqual(this.key),"Can only apply mutation to document with same key"),new NoDocument(this.key,SnapshotVersion.forDeletedDoc())):e},t.prototype.isEqual=function(e){return e instanceof t&&this.key.isEqual(e.key)&&this.precondition.isEqual(e.precondition)},t}(Mutation),ServerTimestampTransform=function(){function e(){}return e.prototype.applyToLocalView=function(e,t){return new ServerTimestampValue(t,e)},e.prototype.applyToRemoteDocument=function(e,t){return t},e.prototype.isEqual=function(t){return t instanceof e},e.instance=new e,e}(),ArrayUnionTransformOperation=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=coercedFieldValuesArray(e),n=function(e){t.find(function(t){return t.isEqual(e)})||t.push(e)},r=0,i=this.elements;r<i.length;r++){n(i[r])}return new ArrayValue(t)},e.prototype.isEqual=function(t){return t instanceof e&&arrayEquals(t.elements,this.elements)},e}(),ArrayRemoveTransformOperation=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=coercedFieldValuesArray(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 ArrayValue(t)},e.prototype.isEqual=function(t){return t instanceof e&&arrayEquals(t.elements,this.elements)},e}();function coercedFieldValuesArray(e){return e instanceof ArrayValue?e.internalValue.slice():[]}var ExistenceFilter=function(){function e(e){this.count=e}return e.prototype.isEqual=function(e){return e&&e.count===this.count},e}(),RpcCode;function isPermanentError(e){switch(e){case Code.OK:return fail("Treated status OK as error");case Code.CANCELLED:case Code.UNKNOWN:case Code.DEADLINE_EXCEEDED:case Code.RESOURCE_EXHAUSTED:case Code.INTERNAL:case Code.UNAVAILABLE:case Code.UNAUTHENTICATED:return!1;case Code.INVALID_ARGUMENT:case Code.NOT_FOUND:case Code.ALREADY_EXISTS:case Code.PERMISSION_DENIED:case Code.FAILED_PRECONDITION:case Code.ABORTED:case Code.OUT_OF_RANGE:case Code.UNIMPLEMENTED:case Code.DATA_LOSS:return!0;default:return fail("Unknown status code: "+e)}}function mapCodeFromRpcStatus(e){var t=RpcCode[e];if(void 0!==t)return mapCodeFromRpcCode(t)}function mapCodeFromRpcCode(e){if(void 0===e)return error$2("GRPC error has no .code"),Code.UNKNOWN;switch(e){case RpcCode.OK:return Code.OK;case RpcCode.CANCELLED:return Code.CANCELLED;case RpcCode.UNKNOWN:return Code.UNKNOWN;case RpcCode.DEADLINE_EXCEEDED:return Code.DEADLINE_EXCEEDED;case RpcCode.RESOURCE_EXHAUSTED:return Code.RESOURCE_EXHAUSTED;case RpcCode.INTERNAL:return Code.INTERNAL;case RpcCode.UNAVAILABLE:return Code.UNAVAILABLE;case RpcCode.UNAUTHENTICATED:return Code.UNAUTHENTICATED;case RpcCode.INVALID_ARGUMENT:return Code.INVALID_ARGUMENT;case RpcCode.NOT_FOUND:return Code.NOT_FOUND;case RpcCode.ALREADY_EXISTS:return Code.ALREADY_EXISTS;case RpcCode.PERMISSION_DENIED:return Code.PERMISSION_DENIED;case RpcCode.FAILED_PRECONDITION:return Code.FAILED_PRECONDITION;case RpcCode.ABORTED:return Code.ABORTED;case RpcCode.OUT_OF_RANGE:return Code.OUT_OF_RANGE;case RpcCode.UNIMPLEMENTED:return Code.UNIMPLEMENTED;case RpcCode.DATA_LOSS:return Code.DATA_LOSS;default:return fail("Unknown status code: "+e)}}function mapRpcCodeFromCode(e){if(void 0===e)return RpcCode.OK;switch(e){case Code.OK:return RpcCode.OK;case Code.CANCELLED:return RpcCode.CANCELLED;case Code.UNKNOWN:return RpcCode.UNKNOWN;case Code.DEADLINE_EXCEEDED:return RpcCode.DEADLINE_EXCEEDED;case Code.RESOURCE_EXHAUSTED:return RpcCode.RESOURCE_EXHAUSTED;case Code.INTERNAL:return RpcCode.INTERNAL;case Code.UNAVAILABLE:return RpcCode.UNAVAILABLE;case Code.UNAUTHENTICATED:return RpcCode.UNAUTHENTICATED;case Code.INVALID_ARGUMENT:return RpcCode.INVALID_ARGUMENT;case Code.NOT_FOUND:return RpcCode.NOT_FOUND;case Code.ALREADY_EXISTS:return RpcCode.ALREADY_EXISTS;case Code.PERMISSION_DENIED:return RpcCode.PERMISSION_DENIED;case Code.FAILED_PRECONDITION:return RpcCode.FAILED_PRECONDITION;case Code.ABORTED:return RpcCode.ABORTED;case Code.OUT_OF_RANGE:return RpcCode.OUT_OF_RANGE;case Code.UNIMPLEMENTED:return RpcCode.UNIMPLEMENTED;case Code.DATA_LOSS:return RpcCode.DATA_LOSS;default:return fail("Unknown status code: "+e)}}function mapCodeFromHttpStatus(e){switch(e){case 200:return Code.OK;case 400:return Code.INVALID_ARGUMENT;case 401:return Code.UNAUTHENTICATED;case 403:return Code.PERMISSION_DENIED;case 404:return Code.NOT_FOUND;case 409:return Code.ABORTED;case 416:return Code.OUT_OF_RANGE;case 429:return Code.RESOURCE_EXHAUSTED;case 499:return Code.CANCELLED;case 500:return Code.UNKNOWN;case 501:return Code.UNIMPLEMENTED;case 503:return Code.UNAVAILABLE;case 504:return Code.DEADLINE_EXCEEDED;default:return e>=200&&e<300?Code.OK:e>=400&&e<500?Code.FAILED_PRECONDITION:e>=500&&e<600?Code.INTERNAL:Code.UNKNOWN}}!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"}(RpcCode||(RpcCode={}));var SortedSet=function(){function e(e){this.comparator=e,this.data=new SortedMap$1(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.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}(),EMPTY_MAYBE_DOCUMENT_MAP=new SortedMap$1(DocumentKey.comparator);function maybeDocumentMap(){return EMPTY_MAYBE_DOCUMENT_MAP}var EMPTY_DOCUMENT_MAP=new SortedMap$1(DocumentKey.comparator);function documentMap(){return EMPTY_DOCUMENT_MAP}var EMPTY_DOCUMENT_VERSION_MAP=new SortedMap$1(DocumentKey.comparator);function documentVersionMap(){return EMPTY_DOCUMENT_VERSION_MAP}var EMPTY_DOCUMENT_KEY_SET=new SortedSet(DocumentKey.comparator);function documentKeySet(){return EMPTY_DOCUMENT_KEY_SET}var EMPTY_TARGET_ID_SET=new SortedSet(primitiveComparator);function targetIdSet(){return EMPTY_TARGET_ID_SET}var DocumentSet=function(){function e(e){this.comparator=e?function(t,n){return e(t,n)||DocumentKey.comparator(t.key,n.key)}:function(e,t){return DocumentKey.comparator(e.key,t.key)},this.keyedMap=documentMap(),this.sortedSet=new SortedMap$1(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}(),ChangeType,SyncState;!function(e){e[e.Added=0]="Added",e[e.Removed=1]="Removed",e[e.Modified=2]="Modified",e[e.Metadata=3]="Metadata"}(ChangeType||(ChangeType={})),function(e){e[e.Local=0]="Local",e[e.Synced=1]="Synced"}(SyncState||(SyncState={}));var DocumentChangeSet=function(){function e(){this.changeMap=new SortedMap$1(DocumentKey.comparator)}return e.prototype.track=function(e){var t=e.doc.key,n=this.changeMap.get(t);n?e.type!==ChangeType.Added&&n.type===ChangeType.Metadata?this.changeMap=this.changeMap.insert(t,e):e.type===ChangeType.Metadata&&n.type!==ChangeType.Removed?this.changeMap=this.changeMap.insert(t,{type:n.type,doc:e.doc}):e.type===ChangeType.Modified&&n.type===ChangeType.Modified?this.changeMap=this.changeMap.insert(t,{type:ChangeType.Modified,doc:e.doc}):e.type===ChangeType.Modified&&n.type===ChangeType.Added?this.changeMap=this.changeMap.insert(t,{type:ChangeType.Added,doc:e.doc}):e.type===ChangeType.Removed&&n.type===ChangeType.Added?this.changeMap=this.changeMap.remove(t):e.type===ChangeType.Removed&&n.type===ChangeType.Modified?this.changeMap=this.changeMap.insert(t,{type:ChangeType.Removed,doc:n.doc}):e.type===ChangeType.Added&&n.type===ChangeType.Removed?this.changeMap=this.changeMap.insert(t,{type:ChangeType.Modified,doc:e.doc}):fail("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}(),ViewSnapshot=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=[];return n.forEach(function(e){o.push({type:ChangeType.Added,doc:e})}),new e(t,n,DocumentSet.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}(),RemoteEvent=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]=TargetChange.createSynthesizedTargetChangeForCurrentChange(t,n),r);return new e(SnapshotVersion.MIN,i,targetIdSet(),maybeDocumentMap(),documentKeySet())},e}(),TargetChange=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(emptyByteString(),n,documentKeySet(),documentKeySet(),documentKeySet())},e}(),DocumentWatchChange=function(){return function(e,t,n,r){this.updatedTargetIds=e,this.removedTargetIds=t,this.key=n,this.newDoc=r}}(),ExistenceFilterChange=function(){return function(e,t){this.targetId=e,this.existenceFilter=t}}(),WatchTargetChangeState;!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"}(WatchTargetChangeState||(WatchTargetChangeState={}));var WatchTargetChange=function(){return function(e,t,n,r){void 0===n&&(n=emptyByteString()),void 0===r&&(r=null),this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}(),TargetState=function(){function e(){this.pendingResponses=0,this.documentChanges=snapshotChangesMap(),this._resumeToken=emptyByteString(),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=documentKeySet(),t=documentKeySet(),n=documentKeySet();return this.documentChanges.forEach(function(r,i){switch(i){case ChangeType.Added:e=e.add(r);break;case ChangeType.Modified:t=t.add(r);break;case ChangeType.Removed:n=n.add(r);break;default:fail("Encountered invalid change type: "+i)}}),new TargetChange(this._resumeToken,this._current,e,t,n)},e.prototype.clearPendingChanges=function(){this._hasPendingChanges=!1,this.documentChanges=snapshotChangesMap()},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}(),WatchChangeAggregator=function(){function e(e){this.metadataProvider=e,this.targetStates={},this.pendingDocumentUpdates=maybeDocumentMap(),this.pendingDocumentTargetMapping=documentTargetMap(),this.pendingTargetResets=new SortedSet(primitiveComparator)}return e.prototype.handleDocumentChange=function(e){for(var t=0,n=e.updatedTargetIds;t<n.length;t++){var r=n[t];e.newDoc instanceof Document?this.addDocumentToTarget(r,e.newDoc):e.newDoc instanceof NoDocument&&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 WatchTargetChangeState.NoChange:t.isActiveTarget(n)&&r.updateResumeToken(e.resumeToken);break;case WatchTargetChangeState.Added:r.recordTargetResponse(),r.isPending||r.clearPendingChanges(),r.updateResumeToken(e.resumeToken);break;case WatchTargetChangeState.Removed:r.recordTargetResponse(),r.isPending||t.removeTarget(n),assert$1(!e.cause,"WatchChangeAggregator does not handle errored targets");break;case WatchTargetChangeState.Current:t.isActiveTarget(n)&&(r.markCurrent(),r.updateResumeToken(e.resumeToken));break;case WatchTargetChangeState.Reset:t.isActiveTarget(n)&&(t.resetTarget(n),r.updateResumeToken(e.resumeToken));break;default:fail("Unknown target watch change state: "+e.state)}})},e.prototype.forEachTarget=function(e,t){e.targetIds.length>0?e.targetIds.forEach(t):forEachNumber(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 DocumentKey(i.path);this.removeDocumentFromTarget(t,o,new NoDocument(o,SnapshotVersion.forDeletedDoc()))}else assert$1(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={};forEachNumber(this.targetStates,function(r,i){var o=t.queryDataForActiveTarget(r);if(o){if(i.current&&o.query.isDocumentQuery()){var a=new DocumentKey(o.query.path);null!==t.pendingDocumentUpdates.get(a)||t.targetContainsDocument(r,a)||t.removeDocumentFromTarget(r,a,new NoDocument(a,e))}i.hasPendingChanges&&(n[r]=i.toTargetChange(),i.clearPendingChanges())}});var r=documentKeySet();this.pendingDocumentTargetMapping.forEach(function(e,n){var i=!0;n.forEachWhile(function(e){var n=t.queryDataForActiveTarget(e);return!n||n.purpose===QueryPurpose.LimboResolution||(i=!1,!1)}),i&&(r=r.add(e))});var i=new RemoteEvent(e,n,this.pendingTargetResets,this.pendingDocumentUpdates,r);return this.pendingDocumentUpdates=maybeDocumentMap(),this.pendingDocumentTargetMapping=documentTargetMap(),this.pendingTargetResets=new SortedSet(primitiveComparator),i},e.prototype.addDocumentToTarget=function(e,t){if(this.isActiveTarget(e)){var n=this.targetContainsDocument(e,t.key)?ChangeType.Modified:ChangeType.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,ChangeType.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()},e.prototype.ensureTargetState=function(e){return this.targetStates[e]||(this.targetStates[e]=new TargetState),this.targetStates[e]},e.prototype.ensureDocumentTargetMapping=function(e){var t=this.pendingDocumentTargetMapping.get(e);return t||(t=new SortedSet(primitiveComparator),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e,t)),t},e.prototype.isActiveTarget=function(e){return null!==this.queryDataForActiveTarget(e)},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;assert$1(!this.targetStates[e].isPending,"Should only reset active targets"),this.targetStates[e]=new TargetState,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 documentTargetMap(){return new SortedMap$1(DocumentKey.comparator)}function snapshotChangesMap(){return new SortedMap$1(DocumentKey.comparator)}var DIRECTIONS=(dirs={},dirs[Direction.ASCENDING.name]="ASCENDING",dirs[Direction.DESCENDING.name]="DESCENDING",dirs),dirs,OPERATORS=(ops={},ops[RelationOp.LESS_THAN.name]="LESS_THAN",ops[RelationOp.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",ops[RelationOp.GREATER_THAN.name]="GREATER_THAN",ops[RelationOp.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",ops[RelationOp.EQUAL.name]="EQUAL",ops[RelationOp.ARRAY_CONTAINS.name]="ARRAY_CONTAINS",ops),ops,ISO_REG_EXP=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function assertPresent(e,t){assert$1(!isNullOrUndefined(e),t+" is missing")}function parseInt64(e){return"number"==typeof e?e:"string"==typeof e?Number(e):fail("can't parse "+e)}var JsonProtoSerializer=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?Code.UNKNOWN:mapCodeFromRpcCode(e.code);return new FirestoreError(t,e.message||"")},e.prototype.toInt32Value=function(e){return isNullOrUndefined(e)?void 0:{value:e}},e.prototype.fromInt32Value=function(e){var t;return isNullOrUndefined(t="object"==typeof e?e.value:e)?null:t},e.prototype.toTimestamp=function(e){return{seconds:e.seconds,nanos:e.nanoseconds}},e.prototype.fromTimestamp=function(e){if("string"==typeof e)return this.fromIso8601String(e);assert$1(!!e,"Cannot deserialize null or undefined timestamp.");var t=parseInt64(e.seconds||"0"),n=e.nanos||0;return new Timestamp(t,n)},e.prototype.fromIso8601String=function(e){var t=0,n=ISO_REG_EXP.exec(e);if(assert$1(!!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 Timestamp(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?(assert$1(this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Blob$1.fromBase64String(e)):(assert$1(!this.options.useProto3Json,"Expected bytes to be passed in as string, but got something else instead."),Blob$1.fromUint8Array(e))},e.prototype.toVersion=function(e){return this.toTimestamp(e.toTimestamp())},e.prototype.fromVersion=function(e){return assert$1(!!e,"Trying to deserialize version that isn't set"),SnapshotVersion.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=ResourcePath.fromString(e);return assert$1(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 assert$1(t.get(1)===this.databaseId.projectId,"Tried to deserialize key from different project: "+t.get(1)+" vs "+this.databaseId.projectId),assert$1(!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 DocumentKey(this.extractLocalPathFromResourceName(t))},e.prototype.toQueryPath=function(e){return 0===e.length?this.encodedDatabaseId:this.toResourceName(this.databaseId,e)},e.prototype.fromQueryPath=function(e){var t=this.fromResourceName(e);return 4===t.length?ResourcePath.EMPTY_PATH:this.extractLocalPathFromResourceName(t)},Object.defineProperty(e.prototype,"encodedDatabaseId",{get:function(){return new ResourcePath(["projects",this.databaseId.projectId,"databases",this.databaseId.database]).canonicalString()},enumerable:!0,configurable:!0}),e.prototype.fullyQualifiedPrefixPath=function(e){return new ResourcePath(["projects",e.projectId,"databases",e.database])},e.prototype.extractLocalPathFromResourceName=function(e){return assert$1(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 NullValue)return{nullValue:"NULL_VALUE"};if(e instanceof BooleanValue)return{booleanValue:e.value()};if(e instanceof IntegerValue)return{integerValue:""+e.value()};if(e instanceof DoubleValue){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 StringValue?{stringValue:e.value()}:e instanceof ObjectValue?{mapValue:this.toMapValue(e)}:e instanceof ArrayValue?{arrayValue:this.toArrayValue(e)}:e instanceof TimestampValue?{timestampValue:this.toTimestamp(e.internalValue)}:e instanceof GeoPointValue?{geoPointValue:{latitude:e.value().latitude,longitude:e.value().longitude}}:e instanceof BlobValue?{bytesValue:this.toBytes(e.value())}:e instanceof RefValue?{referenceValue:this.toResourceName(e.databaseId,e.key.path)}:fail("Unknown FieldValue "+JSON.stringify(e))},e.prototype.fromValue=function(e){var t=this,n=e.value_type;if(hasTag(e,n,"nullValue"))return NullValue.INSTANCE;if(hasTag(e,n,"booleanValue"))return BooleanValue.of(e.booleanValue);if(hasTag(e,n,"integerValue"))return new IntegerValue(parseInt64(e.integerValue));if(hasTag(e,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===e.doubleValue)return DoubleValue.NAN;if("Infinity"===e.doubleValue)return DoubleValue.POSITIVE_INFINITY;if("-Infinity"===e.doubleValue)return DoubleValue.NEGATIVE_INFINITY}return new DoubleValue(e.doubleValue)}if(hasTag(e,n,"stringValue"))return new StringValue(e.stringValue);if(hasTag(e,n,"mapValue"))return this.fromFields(e.mapValue.fields||{});if(hasTag(e,n,"arrayValue")){assertPresent(e.arrayValue,"arrayValue");var r=e.arrayValue.values||[];return new ArrayValue(r.map(function(e){return t.fromValue(e)}))}if(hasTag(e,n,"timestampValue"))return assertPresent(e.timestampValue,"timestampValue"),new TimestampValue(this.fromTimestamp(e.timestampValue));if(hasTag(e,n,"geoPointValue")){assertPresent(e.geoPointValue,"geoPointValue");var i=e.geoPointValue.latitude||0,o=e.geoPointValue.longitude||0;return new GeoPointValue(new GeoPoint(i,o))}if(hasTag(e,n,"bytesValue")){assertPresent(e.bytesValue,"bytesValue");var a=this.fromBlob(e.bytesValue);return new BlobValue(a)}if(hasTag(e,n,"referenceValue")){assertPresent(e.referenceValue,"referenceValue");var s=this.fromResourceName(e.referenceValue),u=new DatabaseId(s.get(1),s.get(3)),c=new DocumentKey(this.extractLocalPathFromResourceName(s));return new RefValue(u,c)}return fail("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 assert$1(!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){return new Document(this.fromName(e.name),this.fromVersion(e.updateTime),this.fromFields(e.fields||{}),{hasCommittedMutations:!!t})},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=ObjectValue.EMPTY;return forEach$1(n,function(e,n){r=r.set(new FieldPath([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){assert$1(!!e.found,"Tried to deserialize a found document from a missing document."),assertPresent(e.found.name,"doc.found.name"),assertPresent(e.found.updateTime,"doc.found.updateTime");var t=this.fromName(e.found.name),n=this.fromVersion(e.found.updateTime),r=this.fromFields(e.found.fields||{});return new Document(t,n,r,{})},e.prototype.fromMissing=function(e){assert$1(!!e.missing,"Tried to deserialize a missing document from a found document."),assert$1(!!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 NoDocument(t,n)},e.prototype.fromMaybeDocument=function(e){var t=e.result;return hasTag(e,t,"found")?this.fromFound(e):hasTag(e,t,"missing")?this.fromMissing(e):fail("invalid batch get response: "+JSON.stringify(e))},e.prototype.toWatchTargetChangeState=function(e){switch(e){case WatchTargetChangeState.Added:return"ADD";case WatchTargetChangeState.Current:return"CURRENT";case WatchTargetChangeState.NoChange:return"NO_CHANGE";case WatchTargetChangeState.Removed:return"REMOVE";case WatchTargetChangeState.Reset:return"RESET";default:return fail("Unknown WatchTargetChangeState: "+e)}},e.prototype.toTestWatchChange=function(e){if(e instanceof ExistenceFilterChange)return{filter:{count:e.existenceFilter.count,targetId:e.targetId}};if(e instanceof DocumentWatchChange){if(e.newDoc instanceof Document){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 NoDocument){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 WatchTargetChange){var n=void 0;return e.cause&&(n={code:mapRpcCodeFromCode(e.cause.code),message:e.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(e.state),targetIds:e.targetIds,resumeToken:this.unsafeCastProtoByteString(e.resumeToken),cause:n}}}return fail("Unrecognized watch change: "+JSON.stringify(e))},e.prototype.fromWatchChange=function(e){var t,n=e.response_type;if(hasTag(e,n,"targetChange")){assertPresent(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 WatchTargetChange(r,i,o,s||null)}else if(hasTag(e,n,"documentChange")){assertPresent(e.documentChange,"documentChange"),assertPresent(e.documentChange.document,"documentChange.name"),assertPresent(e.documentChange.document.name,"documentChange.document.name"),assertPresent(e.documentChange.document.updateTime,"documentChange.document.updateTime");var u=e.documentChange,c=this.fromName(u.document.name),h=this.fromVersion(u.document.updateTime),l=this.fromFields(u.document.fields||{}),d=new Document(c,h,l,{}),f=u.targetIds||[],p=u.removedTargetIds||[];t=new DocumentWatchChange(f,p,d.key,d)}else if(hasTag(e,n,"documentDelete")){assertPresent(e.documentDelete,"documentDelete"),assertPresent(e.documentDelete.document,"documentDelete.document");var m=e.documentDelete;c=this.fromName(m.document),h=m.readTime?this.fromVersion(m.readTime):SnapshotVersion.forDeletedDoc(),d=new NoDocument(c,h),p=m.removedTargetIds||[];t=new DocumentWatchChange([],p,d.key,d)}else if(hasTag(e,n,"documentRemove")){assertPresent(e.documentRemove,"documentRemove"),assertPresent(e.documentRemove.document,"documentRemove");var y=e.documentRemove;c=this.fromName(y.document),p=y.removedTargetIds||[];t=new DocumentWatchChange([],p,c,null)}else{if(!hasTag(e,n,"filter"))return fail("Unknown change type "+JSON.stringify(e));assertPresent(e.filter,"filter"),assertPresent(e.filter.targetId,"filter.targetId");var g=e.filter,v=g.count||0,_=new ExistenceFilter(v),b=g.targetId;t=new ExistenceFilterChange(b,_)}return t},e.prototype.fromWatchTargetChangeState=function(e){return"NO_CHANGE"===e?WatchTargetChangeState.NoChange:"ADD"===e?WatchTargetChangeState.Added:"REMOVE"===e?WatchTargetChangeState.Removed:"CURRENT"===e?WatchTargetChangeState.Current:"RESET"===e?WatchTargetChangeState.Reset:fail("Got unexpected TargetChange.state: "+e)},e.prototype.versionFromListenResponse=function(e){if(!hasTag(e,e.response_type,"targetChange"))return SnapshotVersion.MIN;var t=e.targetChange;return t.targetIds&&t.targetIds.length?SnapshotVersion.MIN:t.readTime?this.fromVersion(t.readTime):SnapshotVersion.MIN},e.prototype.toMutation=function(e){var t,n=this;if(e instanceof SetMutation)t={update:this.toMutationDocument(e.key,e.value)};else if(e instanceof DeleteMutation)t={delete:this.toName(e.key)};else if(e instanceof PatchMutation)t={update:this.toMutationDocument(e.key,e.data),updateMask:this.toDocumentMask(e.fieldMask)};else{if(!(e instanceof TransformMutation))return fail("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):Precondition.NONE;if(e.update){assertPresent(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 PatchMutation(r,i,o,n)}return new SetMutation(r,i,n)}if(e.delete){r=this.fromName(e.delete);return new DeleteMutation(r,n)}if(e.transform){r=this.fromName(e.transform.document);var a=e.transform.fieldTransforms.map(function(e){return t.fromFieldTransform(e)});return assert$1(!0===n.exists,'Transforms only support precondition "exists == true"'),new TransformMutation(r,a)}return fail("unknown mutation proto: "+JSON.stringify(e))},e.prototype.toPrecondition=function(e){return assert$1(!e.isNone,"Can't serialize an empty precondition"),void 0!==e.updateTime?{updateTime:this.toVersion(e.updateTime)}:void 0!==e.exists?{exists:e.exists}:fail("Unknown precondition")},e.prototype.fromPrecondition=function(e){return void 0!==e.updateTime?Precondition.updateTime(this.fromVersion(e.updateTime)):void 0!==e.exists?Precondition.exists(e.exists):Precondition.NONE},e.prototype.fromWriteResult=function(e,t){var n=this,r=e.updateTime?this.fromVersion(e.updateTime):this.fromVersion(t),i=null;return e.transformResults&&e.transformResults.length>0&&(i=e.transformResults.map(function(e){return n.fromValue(e)})),new MutationResult(r,i)},e.prototype.fromWriteResults=function(e,t){var n=this;return e&&e.length>0?(assert$1(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 ServerTimestampTransform)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof ArrayUnionTransformOperation)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:n.elements.map(function(e){return t.toValue(e)})}};if(n instanceof ArrayRemoveTransformOperation)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:n.elements.map(function(e){return t.toValue(e)})}};throw fail("Unknown transform: "+e.transform)},e.prototype.fromFieldTransform=function(e){var t=this,n=e.transform_type,r=null;if(hasTag(e,n,"setToServerValue"))assert$1("REQUEST_TIME"===e.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(e)),r=ServerTimestampTransform.instance;else if(hasTag(e,n,"appendMissingElements")){var i=e.appendMissingElements.values||[];r=new ArrayUnionTransformOperation(i.map(function(e){return t.fromValue(e)}))}else if(hasTag(e,n,"removeAllFromArray")){i=e.removeAllFromArray.values||[];r=new ArrayRemoveTransformOperation(i.map(function(e){return t.fromValue(e)}))}else fail("Unknown transform proto: "+JSON.stringify(e));var o=FieldPath.fromServerFormat(e.fieldPath);return new FieldTransform(o,r)},e.prototype.toDocumentsTarget=function(e){return{documents:[this.toQueryPath(e.path)]}},e.prototype.fromDocumentsTarget=function(e){var t=e.documents.length;assert$1(1===t,"DocumentsTarget contained other than 1 document: "+t);var n=e.documents[0];return Query$1.atPath(this.fromQueryPath(n))},e.prototype.toQueryTarget=function(e){var t={structuredQuery:{}};if(e.path.isEmpty())t.parent=this.toQueryPath(ResourcePath.EMPTY_PATH);else{var n=e.path;assert$1(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 void 0!==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=n.from?n.from.length:0;if(r>0){assert$1(1===r,"StructuredQuery.from with more than one collection is not supported.");var i=n.from[0];t=t.child(i.collectionId)}var o=[];n.where&&(o=this.fromFilter(n.where));var a=[];n.orderBy&&(a=this.fromOrder(n.orderBy));var s=null;n.limit&&(s=this.fromInt32Value(n.limit));var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var c=null;return n.endAt&&(c=this.fromCursor(n.endAt)),new Query$1(t,a,o,s,u,c)},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 QueryPurpose.Listen:return null;case QueryPurpose.ExistenceFilterMismatch:return"existence-filter-mismatch";case QueryPurpose.LimboResolution:return"limbo-document";default:return fail("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 RelationFilter?t.toRelationFilter(e):t.toUnaryFilter(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.fromRelationFilter(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(function(e){return t.fromFilter(e)}).reduce(function(e,t){return e.concat(t)}):fail("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 Bound(r,n)},e.prototype.toDirection=function(e){return DIRECTIONS[e.name]},e.prototype.fromDirection=function(e){switch(e){case"ASCENDING":return Direction.ASCENDING;case"DESCENDING":return Direction.DESCENDING;default:return}},e.prototype.toOperatorName=function(e){return OPERATORS[e.name]},e.prototype.fromOperatorName=function(e){switch(e){case"EQUAL":return RelationOp.EQUAL;case"GREATER_THAN":return RelationOp.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return RelationOp.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return RelationOp.LESS_THAN;case"LESS_THAN_OR_EQUAL":return RelationOp.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return RelationOp.ARRAY_CONTAINS;case"OPERATOR_UNSPECIFIED":return fail("Unspecified relation");default:return fail("Unknown relation")}},e.prototype.toFieldPathReference=function(e){return{fieldPath:e.canonicalString()}},e.prototype.fromFieldPathReference=function(e){return FieldPath.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 OrderBy(this.fromFieldPathReference(e.field),this.fromDirection(e.direction))},e.prototype.toRelationFilter=function(e){return e instanceof RelationFilter?{fieldFilter:{field:this.toFieldPathReference(e.field),op:this.toOperatorName(e.op),value:this.toValue(e.value)}}:fail("Unrecognized filter: "+JSON.stringify(e))},e.prototype.fromRelationFilter=function(e){return new RelationFilter(this.fromFieldPathReference(e.fieldFilter.field),this.fromOperatorName(e.fieldFilter.op),this.fromValue(e.fieldFilter.value))},e.prototype.toUnaryFilter=function(e){return e instanceof NanFilter?{unaryFilter:{field:this.toFieldPathReference(e.field),op:"IS_NAN"}}:e instanceof NullFilter?{unaryFilter:{field:this.toFieldPathReference(e.field),op:"IS_NULL"}}:fail("Unrecognized filter: "+JSON.stringify(e))},e.prototype.fromUnaryFilter=function(e){switch(e.unaryFilter.op){case"IS_NAN":var t=this.fromFieldPathReference(e.unaryFilter.field);return new NanFilter(t);case"IS_NULL":var n=this.fromFieldPathReference(e.unaryFilter.field);return new NullFilter(n);case"OPERATOR_UNSPECIFIED":return fail("Unspecified filter");default:return fail("Unknown filter")}},e.prototype.toDocumentMask=function(e){return{fieldPaths:e.fields.map(function(e){return e.canonicalString()})}},e.prototype.fromDocumentMask=function(e){var t=(e.fieldPaths||[]).map(function(e){return FieldPath.fromServerFormat(e)});return new FieldMask(t)},e}();function hasTag(e,t,n){return t===n||!t&&n in e}var isReactNative$1=function(){return"object"==typeof navigator&&"ReactNative"===navigator.product},ERROR_NAME$1="FirebaseError",captureStackTrace$1=Error.captureStackTrace,FirebaseError$1=function(){return function(e,t){if(this.code=e,this.message=t,captureStackTrace$1)captureStackTrace$1(this,ErrorFactory$1.prototype.create);else try{throw Error.apply(this,arguments)}catch(e){this.name=ERROR_NAME$1,Object.defineProperty(this,"stack",{get:function(){return e.stack}})}}}();FirebaseError$1.prototype=Object.create(Error.prototype),FirebaseError$1.prototype.constructor=FirebaseError$1,FirebaseError$1.prototype.name=ERROR_NAME$1;var ErrorFactory$1=function(){function e(e,t,n){this.service=e,this.serviceName=t,this.errors=n,this.pattern=/\{\$([^}]+)}/g}return e.prototype.create=function(e,t){void 0===t&&(t={});var n,r=this.errors[e],i=this.service+"/"+e;n=void 0===r?"Error":r.replace(this.pattern,function(e,n){var r=t[n];return void 0!==r?r.toString():"<"+n+"?>"}),n=this.serviceName+": "+n+" ("+i+").";var o=new FirebaseError$1(i,n);for(var a in t)t.hasOwnProperty(a)&&"_"!==a.slice(-1)&&(o[a]=t[a]);return o},e}(),Hash$1=function(){return function(){this.blockSize=-1}}(),Sha1$1=function(e){function t(){var t=e.call(this)||this;t.chain_=[],t.buf_=[],t.W_=[],t.pad_=[],t.inbuf_=0,t.total_=0,t.blockSize=64,t.pad_[0]=128;for(var n=1;n<t.blockSize;++n)t.pad_[n]=0;return t.reset(),t}return __extends(t,e),t.prototype.reset=function(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0},t.prototype.compress_=function(e,t){t||(t=0);var n=this.W_;if("string"==typeof e)for(var r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(r=16;r<80;r++){var i=n[r-3]^n[r-8]^n[r-14]^n[r-16];n[r]=4294967295&(i<<1|i>>>31)}var o,a,s=this.chain_[0],u=this.chain_[1],c=this.chain_[2],h=this.chain_[3],l=this.chain_[4];for(r=0;r<80;r++){r<40?r<20?(o=h^u&(c^h),a=1518500249):(o=u^c^h,a=1859775393):r<60?(o=u&c|h&(u|c),a=2400959708):(o=u^c^h,a=3395469782);i=(s<<5|s>>>27)+o+l+a+n[r]&4294967295;l=h,h=c,c=4294967295&(u<<30|u>>>2),u=s,s=i}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+u&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+h&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295},t.prototype.update=function(e,t){if(null!=e){void 0===t&&(t=e.length);for(var n=t-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r<t;){if(0==o)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[o]=e.charCodeAt(r),++r,++o==this.blockSize){this.compress_(i),o=0;break}}else for(;r<t;)if(i[o]=e[r],++r,++o==this.blockSize){this.compress_(i),o=0;break}}this.inbuf_=o,this.total_+=t}},t.prototype.digest=function(){var e=[],t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(var n=this.blockSize-1;n>=56;n--)this.buf_[n]=255&t,t/=256;this.compress_(this.buf_);var r=0;for(n=0;n<5;n++)for(var i=24;i>=0;i-=8)e[r]=this.chain_[n]>>i&255,++r;return e},t}(Hash$1),StreamBridge=function(){function e(e){this.sendFn=e.sendFn,this.closeFn=e.closeFn}return e.prototype.onOpen=function(e){assert$1(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=e},e.prototype.onClose=function(e){assert$1(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=e},e.prototype.onMessage=function(e){assert$1(!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(){assert$1(void 0!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},e.prototype.callOnClose=function(e){assert$1(void 0!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(e)},e.prototype.callOnMessage=function(e){assert$1(void 0!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(e)},e}(),LOG_TAG="Connection",RPC_STREAM_SERVICE="google.firestore.v1beta1.Firestore",RPC_URL_VERSION="v1beta1",RPC_NAME_REST_MAPPING={BatchGetDocuments:"batchGet",Commit:"commit"},X_GOOG_API_CLIENT_VALUE="gl-js/ fire/"+SDK_VERSION,XHR_TIMEOUT_SECS=15,WebChannelConnection=function(){function e(e){this.databaseId=e.databaseId,this.pool=new src_5;var t=e.ssl?"https":"http";this.baseUrl=t+"://"+e.host}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"]=X_GOOG_API_CLIENT_VALUE},e.prototype.invokeRPC=function(e,t,n){var r=this,i=this.makeUrl(e);return new Promise(function(o,a){r.pool.getObject(function(s){s.listenOnce(src_3.COMPLETE,function(){try{switch(s.getLastErrorCode()){case src_2.NO_ERROR:var t=s.getResponseJson();debug(LOG_TAG,"XHR received:",JSON.stringify(t)),o(t);break;case src_2.TIMEOUT:debug(LOG_TAG,'RPC "'+e+'" timed out'),a(new FirestoreError(Code.DEADLINE_EXCEEDED,"Request time out"));break;case src_2.HTTP_ERROR:var n=s.getStatus();debug(LOG_TAG,'RPC "'+e+'" failed with status:',n,"response text:",s.getResponseText()),n>0?a(new FirestoreError(mapCodeFromHttpStatus(n),"Server responded with status "+s.getStatusText())):(debug(LOG_TAG,'RPC "'+e+'" failed'),a(new FirestoreError(Code.UNAVAILABLE,"Connection failed.")));break;default:fail('RPC "'+e+'" failed with unanticipated webchannel error '+s.getLastErrorCode()+": "+s.getLastError()+", giving up.")}}finally{debug(LOG_TAG,'RPC "'+e+'" completed.'),r.pool.releaseObject(s)}});var u=JSON.stringify(t);debug(LOG_TAG,"XHR sending: ",i+" "+u);var c={"Content-Type":"text/plain"};r.modifyHeadersForRequest(c,n),s.send(i,"POST",u,c,XHR_TIMEOUT_SECS)})})},e.prototype.invokeStreamingRPC=function(e,t,n){return this.invokeRPC(e,t,n)},e.prototype.openStream=function(e,t){var n=[this.baseUrl,"/",RPC_STREAM_SERVICE,"/",e,"/channel"],r=src_1(),i={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(i.initMessageHeaders,t),isReactNative$1()||(i.httpHeadersOverwriteParam="$httpHeaders");var o=n.join("");debug(LOG_TAG,"Creating WebChannel: "+o+" "+i);var a=r.createWebChannel(o,i),s=!1,u=!1,c=new StreamBridge({sendFn:function(e){u?debug(LOG_TAG,"Not sending because WebChannel is closed:",e):(s||(debug(LOG_TAG,"Opening WebChannel transport."),a.open(),s=!0),debug(LOG_TAG,"WebChannel sending:",e),a.send(e))},closeFn:function(){return a.close()}}),h=function(e,t){a.listen(e,function(e){try{t(e)}catch(e){setTimeout(function(){throw e},0)}})};return h(src_4.EventType.OPEN,function(){u||debug(LOG_TAG,"WebChannel transport opened.")}),h(src_4.EventType.CLOSE,function(){u||(u=!0,debug(LOG_TAG,"WebChannel transport closed"),c.callOnClose())}),h(src_4.EventType.ERROR,function(e){u||(u=!0,debug(LOG_TAG,"WebChannel transport errored:",e),c.callOnClose(new FirestoreError(Code.UNAVAILABLE,"The operation could not be completed")))}),h(src_4.EventType.MESSAGE,function(e){if(!u){var t=e.data[0];assert$1(!!t,"Got a webchannel message without data.");var n=t.error||t[0]&&t[0].error;if(n){debug(LOG_TAG,"WebChannel received error:",n);var r=n.status,i=mapCodeFromRpcStatus(r),o=n.message;void 0===i&&(i=Code.INTERNAL,o="Unknown error status: "+r+" with message "+n.message),u=!0,c.callOnClose(new FirestoreError(i,o)),a.close()}else debug(LOG_TAG,"WebChannel received:",t),c.callOnMessage(t)}}),setTimeout(function(){c.callOnOpen()},0),c},e.prototype.makeUrl=function(e){var t=RPC_NAME_REST_MAPPING[e];assert$1(void 0!==t,"Unknown REST mapping for: "+e);var n=[this.baseUrl,"/",RPC_URL_VERSION];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}(),BrowserPlatform=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 WebChannelConnection(e))},e.prototype.newSerializer=function(e){return new JsonProtoSerializer(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}();PlatformSupport.setPlatform(new BrowserPlatform);var PersistencePromise=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&&fail("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(t){return e.reject(t)}},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)})},e.reject=function(t){return new e(function(e,n){n(t)})},e.waitFor=function(t){var n=t.length;if(0===n)return e.resolve();var r=0;return new e(function(e,i){for(var o=0,a=t;o<a.length;o++){a[o].next(function(){++r===n&&e()},function(e){return i(e)})}})},e.map=function(t){for(var n=[],r=[],i=function(e){r[e]=t[e].next(function(t){n[e]=t})},o=0;o<t.length;++o)i(o);return e.waitFor(r).next(function(){return n})},e.forEach=function(t,n){for(var r=e.resolve(),i=function(e){r=r.next(function(){return n(e)})},o=0,a=t;o<a.length;o++){i(a[o])}return r},e}(),EagerGarbageCollector=function(){function e(){this.isEager=!0,this.sources=[],this.potentialGarbage=documentKeySet()}return e.prototype.addGarbageSource=function(e){this.sources.push(e),e.setGarbageCollector(this)},e.prototype.removeGarbageSource=function(e){this.sources.splice(this.sources.indexOf(e),1),e.setGarbageCollector(null)},e.prototype.addPotentialGarbageKey=function(e){this.potentialGarbage=this.potentialGarbage.add(e)},e.prototype.collectGarbage=function(e){var t=this,n=[],r=documentKeySet();return this.potentialGarbage.forEach(function(i){var o=t.documentHasAnyReferences(e,i);n.push(o.next(function(e){return e||(r=r.add(i)),PersistencePromise.resolve()}))}),this.potentialGarbage=documentKeySet(),PersistencePromise.waitFor(n).next(function(){return r})},e.prototype.documentHasAnyReferences=function(e,t){var n=PersistencePromise.resolve(!1);return this.sources.map(function(n){return function(){return n.containsKey(e,t)}}).reduce(function(e,t){return e.next(function(e){return e?PersistencePromise.resolve(!0):t()})},n)},e}(),ListenSequence=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}(),Deferred$1=function(){return function(){var e=this;this.promise=new Promise(function(t,n){e.resolve=t,e.reject=n})}}(),TimerId;!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"}(TimerId||(TimerId={}));var DelayedOperation=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 Deferred$1,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 FirestoreError(Code.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}(),AsyncQueue=function(){function e(){this.tail=Promise.resolve(),this.delayedOperations=[],this.operationInProgress=!1}return e.prototype.enqueueAndForget=function(e){this.enqueue(e)},e.prototype.enqueue=function(e){var t=this;this.verifyNotFailed();var 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 error$2("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(),assert$1(t>=0,"Attempted to schedule an operation with a negative delay of "+t),assert$1(!this.containsDelayedOperation(e),"Attempted to schedule multiple operations with timer id "+e+".");var i=DelayedOperation.createAndSchedule(this,e,t,n,function(e){return r.removeDelayedOperation(e)});return this.delayedOperations.push(i),i},e.prototype.verifyNotFailed=function(){this.failure&&fail("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},e.prototype.verifyOperationInProgress=function(){assert$1(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},e.prototype.drain=function(){return this.enqueue(function(){return Promise.resolve()})},e.prototype.containsDelayedOperation=function(e){return this.delayedOperations.findIndex(function(t){return t.timerId===e})>=0},e.prototype.runDelayedOperationsEarly=function(e){var t=this;return this.drain().then(function(){assert$1(e===TimerId.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!==TimerId.All&&i.timerId===e)break}return t.drain()})},e.prototype.removeDelayedOperation=function(e){var t=this.delayedOperations.indexOf(e);assert$1(t>=0,"Delayed operation not found."),this.delayedOperations.splice(t,1)},e}(),BATCHID_UNKNOWN=-1,MutationBatch=function(){function e(e,t,n){this.batchId=e,this.localWriteTime=t,this.mutations=n}return e.prototype.applyToRemoteDocument=function(e,t,n){t&&assert$1(t.key.isEqual(e),"applyToRemoteDocument: key "+e+" should match maybeDoc key\n "+t.key);var r=n.mutationResults;assert$1(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&&assert$1(t.key.isEqual(e),"applyToLocalDocument: key "+e+" should match maybeDoc key\n "+t.key);for(var n=t,r=0;r<this.mutations.length;r++){var i=this.mutations[r];i.key.isEqual(e)&&(t=i.applyToLocalView(t,n,this.localWriteTime))}return t},e.prototype.keys=function(){for(var e=documentKeySet(),t=0,n=this.mutations;t<n.length;t++){var r=n[t];e=e.add(r.key)}return e},e.prototype.isEqual=function(e){return this.batchId===e.batchId&&arrayEquals(this.mutations,e.mutations)},e.prototype.isTombstone=function(){return 0===this.mutations.length},e.prototype.toTombstone=function(){return new e(this.batchId,this.localWriteTime,[])},e}(),MutationBatchResult=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){assert$1(t.mutations.length===r.length,"Mutations sent "+t.mutations.length+" must equal results received "+r.length);for(var o=documentVersionMap(),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}(),escapeChar="",encodedSeparatorChar="",encodedNul="",encodedEscape="";function encode(e){for(var t="",n=0;n<e.length;n++)t.length>0&&(t=encodeSeparator(t)),t=encodeSegment(e.get(n),t);return encodeSeparator(t)}function encodeSegment(e,t){for(var n=t,r=e.length,i=0;i<r;i++){var o=e.charAt(i);switch(o){case"\0":n+=escapeChar+encodedNul;break;case escapeChar:n+=escapeChar+encodedEscape;break;default:n+=o}}return n}function encodeSeparator(e){return e+escapeChar+encodedSeparatorChar}function decode$1(e){var t=e.length;if(assert$1(t>=2,"Invalid path "+e),2===t)return assert$1(e.charAt(0)===escapeChar&&e.charAt(1)===encodedSeparatorChar,"Non-empty path "+e+" had length 2"),ResourcePath.EMPTY_PATH;for(var n=t-2,r=[],i="",o=0;o<t;){var a=e.indexOf(escapeChar,o);switch((a<0||a>n)&&fail('Invalid encoded resource path: "'+e+'"'),e.charAt(a+1)){case encodedSeparatorChar:var s=e.substring(o,a),u=void 0;0===i.length?u=s:(u=i+=s,i=""),r.push(u);break;case encodedNul:i+=e.substring(o,a),i+="\0";break;case encodedEscape:i+=e.substring(o,a+1);break;default:fail('Invalid encoded resource path: "'+e+'"')}o=a+2}return new ResourcePath(r)}var SCHEMA_VERSION=5,SchemaConverter=function(){function e(e){this.serializer=e}return e.prototype.createOrUpgrade=function(e,t,n,r){var i=this;assert$1(n<r&&n>=0&&r<=SCHEMA_VERSION,"Unexpected schema upgrade from v"+n+" to v{toVersion}."),n<1&&r>=1&&(createPrimaryClientStore(e),createMutationQueue(e),createQueryCache(e),createRemoteDocumentCache(e));var o=PersistencePromise.resolve();return n<3&&r>=3&&(0!==n&&(dropQueryCache(e),createQueryCache(e)),o=o.next(function(){return writeEmptyTargetGlobalEntry(t)})),n<4&&r>=4&&(0!==n&&(o=o.next(function(){return upgradeMutationBatchSchemaAndMigrateData(e,t)})),o=o.next(function(){createClientMetadataStore(e),createRemoteDocumentChangesStore(e)})),n<5&&r>=5&&(o=o.next(function(){return i.removeAcknowledgedMutations(t)})),o},e.prototype.removeAcknowledgedMutations=function(e){var t=this,n=e.store(DbMutationQueue.store),r=e.store(DbMutationBatch.store);return n.loadAll().next(function(n){return PersistencePromise.forEach(n,function(n){var i=IDBKeyRange.bound([n.userId,BATCHID_UNKNOWN],[n.userId,n.lastAcknowledgedBatchId]);return r.loadAll(DbMutationBatch.userMutationsIndex,i).next(function(r){return PersistencePromise.forEach(r,function(r){assert$1(r.userId===n.userId,"Cannot process batch "+r.batchId+" from unexpected user");var i=t.serializer.fromDbMutationBatch(r);return removeMutationBatch(e,n.userId,i).next()})})})})},e}(),DbTimestamp=function(){return function(e,t){this.seconds=e,this.nanoseconds=t}}(),DbPrimaryClient=function(){function e(e,t,n){this.ownerId=e,this.allowTabSynchronization=t,this.leaseTimestampMs=n}return e.store="owner",e.key="owner",e}();function createPrimaryClientStore(e){e.createObjectStore(DbPrimaryClient.store)}var DbMutationQueue=function(){function e(e,t,n){this.userId=e,this.lastAcknowledgedBatchId=t,this.lastStreamToken=n}return e.store="mutationQueues",e.keyPath="userId",e}(),DbMutationBatch=function(){function e(e,t,n,r){this.userId=e,this.batchId=t,this.localWriteTimeMs=n,this.mutations=r}return e.store="mutations",e.keyPath="batchId",e.userMutationsIndex="userMutationsIndex",e.userMutationsKeyPath=["userId","batchId"],e}();function createMutationQueue(e){e.createObjectStore(DbMutationQueue.store,{keyPath:DbMutationQueue.keyPath}),e.createObjectStore(DbMutationBatch.store,{keyPath:DbMutationBatch.keyPath,autoIncrement:!0}).createIndex(DbMutationBatch.userMutationsIndex,DbMutationBatch.userMutationsKeyPath,{unique:!0}),e.createObjectStore(DbDocumentMutation.store)}function upgradeMutationBatchSchemaAndMigrateData(e,t){return t.store(DbMutationBatch.store).loadAll().next(function(n){e.deleteObjectStore(DbMutationBatch.store),e.createObjectStore(DbMutationBatch.store,{keyPath:DbMutationBatch.keyPath,autoIncrement:!0}).createIndex(DbMutationBatch.userMutationsIndex,DbMutationBatch.userMutationsKeyPath,{unique:!0});var r=t.store(DbMutationBatch.store),i=n.map(function(e){return r.put(e)});return PersistencePromise.waitFor(i)})}var DbDocumentMutation=function(){function e(){}return e.prefixForUser=function(e){return[e]},e.prefixForPath=function(e,t){return[e,encode(t)]},e.key=function(e,t,n){return[e,encode(t),n]},e.store="documentMutations",e.PLACEHOLDER=new e,e}();function createRemoteDocumentCache(e){e.createObjectStore(DbRemoteDocument.store)}var DbNoDocument=function(){return function(e,t){this.path=e,this.readTime=t}}(),DbUnknownDocument=function(){return function(e,t){this.path=e,this.version=t}}(),DbRemoteDocument=function(){function e(e,t,n,r){this.unknownDocument=e,this.noDocument=t,this.document=n,this.hasCommittedMutations=r}return e.store="remoteDocuments",e}(),DbTarget=function(){function e(e,t,n,r,i,o){this.targetId=e,this.canonicalId=t,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.query=o}return e.store="targets",e.keyPath="targetId",e.queryTargetsIndexName="queryTargetsIndex",e.queryTargetsKeyPath=["canonicalId","targetId"],e}(),DbTargetDocument=function(){function e(e,t){this.targetId=e,this.path=t}return e.store="targetDocuments",e.keyPath=["targetId","path"],e.documentTargetsIndex="documentTargetsIndex",e.documentTargetsKeyPath=["path","targetId"],e}(),DbTargetGlobal=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}();function createQueryCache(e){e.createObjectStore(DbTargetDocument.store,{keyPath:DbTargetDocument.keyPath}).createIndex(DbTargetDocument.documentTargetsIndex,DbTargetDocument.documentTargetsKeyPath,{unique:!0}),e.createObjectStore(DbTarget.store,{keyPath:DbTarget.keyPath}).createIndex(DbTarget.queryTargetsIndexName,DbTarget.queryTargetsKeyPath,{unique:!0}),e.createObjectStore(DbTargetGlobal.store)}function dropQueryCache(e){e.deleteObjectStore(DbTargetDocument.store),e.deleteObjectStore(DbTarget.store),e.deleteObjectStore(DbTargetGlobal.store)}function writeEmptyTargetGlobalEntry(e){var t=e.store(DbTargetGlobal.store),n=new DbTargetGlobal(0,0,SnapshotVersion.MIN.toTimestamp(),0);return t.put(DbTargetGlobal.key,n)}var DbRemoteDocumentChanges=function(){function e(e){this.changes=e}return e.store="remoteDocumentChanges",e.keyPath="id",e}();function createRemoteDocumentChangesStore(e){e.createObjectStore(DbRemoteDocumentChanges.store,{keyPath:"id",autoIncrement:!0})}var DbClientMetadata=function(){function e(e,t,n,r,i){this.clientId=e,this.updateTimeMs=t,this.networkEnabled=n,this.inForeground=r,this.lastProcessedDocumentChangeId=i}return e.store="clientMetadata",e.keyPath="clientId",e}();function createClientMetadataStore(e){e.createObjectStore(DbClientMetadata.store,{keyPath:DbClientMetadata.keyPath})}var V1_STORES=[DbMutationQueue.store,DbMutationBatch.store,DbDocumentMutation.store,DbRemoteDocument.store,DbTarget.store,DbPrimaryClient.store,DbTargetGlobal.store,DbTargetDocument.store],V3_STORES=V1_STORES,V4_STORES=V3_STORES.concat([DbClientMetadata.store,DbRemoteDocumentChanges.store]),ALL_STORES=V4_STORES,IndexedDbMutationQueue=function(){function e(e,t){this.userId=e,this.serializer=t,this.documentKeysByBatchId={},this.garbageCollector=null}return e.forUser=function(t,n){return assert$1(""!==t.uid,"UserID must not be an empty string."),new e(t.isAuthenticated()?t.uid:"",n)},e.prototype.start=function(e){return PersistencePromise.resolve()},e.prototype.checkEmpty=function(e){var t=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return mutationsStore(e).iterate({index:DbMutationBatch.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(r){var i=t.batchId;return assert$1(i>r.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),r.lastAcknowledgedBatchId=i,r.lastStreamToken=convertStreamToken(n),mutationQueuesStore(e).put(r)})},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=convertStreamToken(t),mutationQueuesStore(e).put(n)})},e.prototype.addMutationBatch=function(e,t,n){var r=this,i=documentMutationsStore(e),o=mutationsStore(e);return o.add({}).next(function(e){assert$1("number"==typeof e,"Auto-generated key is not a number");var a=new MutationBatch(e,t,n),s=r.serializer.toDbMutationBatch(r.userId,a);r.documentKeysByBatchId[e]=a.keys();for(var u=[],c=0,h=n;c<h.length;c++){var l=h[c],d=DbDocumentMutation.key(r.userId,l.key.path,e);u.push(o.put(s)),u.push(i.put(d,DbDocumentMutation.PLACEHOLDER))}return PersistencePromise.waitFor(u).next(function(){return a})})},e.prototype.lookupMutationBatch=function(e,t){var n=this;return mutationsStore(e).get(t).next(function(e){return e?(assert$1(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]?PersistencePromise.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;return this.getMutationQueueMetadata(e).next(function(r){var i=Math.max(t,r.lastAcknowledgedBatchId)+1,o=IDBKeyRange.lowerBound([n.userId,i]),a=null;return mutationsStore(e).iterate({index:DbMutationBatch.userMutationsIndex,range:o},function(e,t,r){t.userId===n.userId&&(assert$1(t.batchId>=i,"Should have found mutation after "+i),a=n.serializer.fromDbMutationBatch(t)),r.done()}).next(function(){return a})})},e.prototype.getAllMutationBatches=function(e){var t=this,n=IDBKeyRange.bound([this.userId,BATCHID_UNKNOWN],[this.userId,Number.POSITIVE_INFINITY]);return mutationsStore(e).loadAll(DbMutationBatch.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=DbDocumentMutation.prefixForPath(this.userId,t.path),i=IDBKeyRange.lowerBound(r),o=[];return documentMutationsStore(e).iterate({range:i},function(r,i,a){var s=r[0],u=r[1],c=r[2],h=decode$1(u);if(s===n.userId&&t.path.isEqual(h))return mutationsStore(e).get(c).next(function(e){if(!e)throw fail("Dangling document-mutation reference found: "+r+" which points to "+c);assert$1(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 SortedSet(primitiveComparator),i=[];return t.forEach(function(t){var o=DbDocumentMutation.prefixForPath(n.userId,t.path),a=IDBKeyRange.lowerBound(o),s=documentMutationsStore(e).iterate({range:a},function(e,i,o){var a=e[0],s=e[1],u=e[2],c=decode$1(s);a===n.userId&&t.path.isEqual(c)?r=r.add(u):o.done()});i.push(s)}),PersistencePromise.waitFor(i).next(function(){return n.lookupMutationBatches(e,r)})},e.prototype.getAllMutationBatchesAffectingQuery=function(e,t){var n=this;assert$1(!t.isDocumentQuery(),"Document queries shouldn't go down this path");var r=t.path,i=r.length+1,o=DbDocumentMutation.prefixForPath(this.userId,r),a=IDBKeyRange.lowerBound(o),s=new SortedSet(primitiveComparator);return documentMutationsStore(e).iterate({range:a},function(e,t,o){var a=e[0],u=e[1],c=e[2],h=decode$1(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(mutationsStore(e).get(t).next(function(e){if(null===e)throw fail("Dangling document-mutation reference found, which points to "+t);assert$1(e.userId===n.userId,"Unexpected user '"+e.userId+"' for mutation batch "+t),r.push(n.serializer.fromDbMutationBatch(e))}))}),PersistencePromise.waitFor(i).next(function(){return r})},e.prototype.removeMutationBatch=function(e,t){var n=this;return removeMutationBatch(e.simpleDbTransaction,this.userId,t).next(function(e){if(n.removeCachedMutationKeys(t.batchId),null!==n.garbageCollector)for(var r=0,i=e;r<i.length;r++){var o=i[r];n.garbageCollector.addPotentialGarbageKey(o)}})},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 PersistencePromise.resolve();var r=IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(t.userId)),i=[];return documentMutationsStore(e).iterate({range:r},function(e,n,r){if(e[0]===t.userId){var o=decode$1(e[1]);i.push(o)}else r.done()}).next(function(){assert$1(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map(function(e){return e.canonicalString()}))})})},e.prototype.setGarbageCollector=function(e){this.garbageCollector=e},e.prototype.containsKey=function(e,t){var n=this,r=DbDocumentMutation.prefixForPath(this.userId,t.path),i=r[1],o=IDBKeyRange.lowerBound(r),a=!1;return documentMutationsStore(e).iterate({range:o,keysOnly:!0},function(e,t,r){var o=e[0],s=e[1];e[2];o===n.userId&&s===i&&(a=!0),r.done()}).next(function(){return a})},e.prototype.getMutationQueueMetadata=function(e){var t=this;return mutationQueuesStore(e).get(this.userId).next(function(e){return e||new DbMutationQueue(t.userId,BATCHID_UNKNOWN,"")})},e}();function removeMutationBatch(e,t,n){var r=e.store(DbMutationBatch.store),i=e.store(DbDocumentMutation.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(){assert$1(1===s,"Dangling document-mutation reference found: Missing batch "+n.batchId)}));for(var c=[],h=0,l=n.mutations;h<l.length;h++){var d=l[h],f=DbDocumentMutation.key(t,d.key.path,n.batchId);o.push(i.delete(f)),c.push(d.key)}return PersistencePromise.waitFor(o).next(function(){return c})}function convertStreamToken(e){return e instanceof Uint8Array?(assert$1("YES"===process.env.USE_MOCK_PERSISTENCE,"Persisting non-string stream tokens is only supported with mock persistence."),e.toString()):e}function mutationsStore(e){return IndexedDbPersistence.getStore(e,DbMutationBatch.store)}function documentMutationsStore(e){return IndexedDbPersistence.getStore(e,DbDocumentMutation.store)}function mutationQueuesStore(e){return IndexedDbPersistence.getStore(e,DbMutationQueue.store)}var RESERVED_BITS=1,GeneratorIds;!function(e){e[e.QueryCache=0]="QueryCache",e[e.SyncEngine=1]="SyncEngine"}(GeneratorIds||(GeneratorIds={}));var TargetIdGenerator=function(){function e(e,t){this.generatorId=e,assert$1((e&RESERVED_BITS)===e,"Generator ID "+e+" contains more than "+RESERVED_BITS+" reserved bits"),this.seek(void 0!==t?t:this.generatorId)}return e.prototype.next=function(){var e=this.nextId;return this.nextId+=1<<RESERVED_BITS,e},e.prototype.after=function(e){return this.seek(e+(1<<RESERVED_BITS)),this.next()},e.prototype.seek=function(e){assert$1((e&RESERVED_BITS)===this.generatorId,"Cannot supply target ID from different generator ID"),this.nextId=e},e.forQueryCache=function(){return new e(GeneratorIds.QueryCache,2)},e.forSyncEngine=function(){return new e(GeneratorIds.SyncEngine)},e}(),LOG_TAG$1="SimpleDb",SimpleDb=function(){function e(e){this.db=e}return e.openOrCreate=function(t,n,r){return assert$1(e.isAvailable(),"IndexedDB not supported in current environment."),debug(LOG_TAG$1,"Opening database:",t),new PersistencePromise(function(i,o){var a=window.indexedDB.open(t,n);a.onsuccess=function(t){var n=t.target.result;i(new e(n))},a.onblocked=function(){o(new FirestoreError(Code.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){o(e.target.error)},a.onupgradeneeded=function(e){debug(LOG_TAG$1,'Database "'+t+'" requires upgrade from version:',e.oldVersion);var n=e.target.result,i=new SimpleDbTransaction(a.transaction);r.createOrUpgrade(n,i,e.oldVersion,SCHEMA_VERSION).next(function(){debug(LOG_TAG$1,"Database upgrade to version "+SCHEMA_VERSION+" complete")})}}).toPromise()},e.delete=function(e){return debug(LOG_TAG$1,"Removing database:",e),wrapRequest(window.indexedDB.deleteDatabase(e)).toPromise()},e.isAvailable=function(){if("undefined"==typeof window||null==window.indexedDB)return!1;if(void 0===window.navigator)return"YES"===process.env.USE_MOCK_PERSISTENCE;var e=window.navigator.userAgent;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0)},e.getStore=function(e,t){return e.store(t)},e.prototype.runTransaction=function(e,t,n){var r=SimpleDbTransaction.open(this.db,e,t),i=n(r).catch(function(e){r.abort(e)}).toPromise();return r.completionPromise.then(function(){return i})},e.prototype.close=function(){this.db.close()},e}(),IterationController=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 wrapRequest(this.dbCursor.delete())},e}(),SimpleDbTransaction=function(){function e(e){var t=this;this.transaction=e,this.aborted=!1,this.completionDeferred=new Deferred$1,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){t.completionDeferred.reject(e.target.error)}}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||(debug(LOG_TAG$1,"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 assert$1(!!t,"Object store not part of transaction: "+e),new SimpleDbStore(t)},e}(),SimpleDbStore=function(){function e(e){this.store=e}return e.prototype.put=function(e,t){var n;return void 0!==t?(debug(LOG_TAG$1,"PUT",this.store.name,e,t),n=this.store.put(t,e)):(debug(LOG_TAG$1,"PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),wrapRequest(n)},e.prototype.add=function(e){return debug(LOG_TAG$1,"ADD",this.store.name,e,e),wrapRequest(this.store.add(e))},e.prototype.get=function(e){var t=this;return wrapRequest(this.store.get(e)).next(function(n){return void 0===n&&(n=null),debug(LOG_TAG$1,"GET",t.store.name,e,n),n})},e.prototype.delete=function(e){return debug(LOG_TAG$1,"DELETE",this.store.name,e),wrapRequest(this.store.delete(e))},e.prototype.count=function(){return debug(LOG_TAG$1,"COUNT",this.store.name),wrapRequest(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){debug(LOG_TAG$1,"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.iterateCursor=function(e,t){var n=[];return new PersistencePromise(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 IterationController(i),a=t(i.primaryKey,i.value,o);a instanceof PersistencePromise&&n.push(a),o.isDone?r():null===o.skipToKey?i.continue():i.continue(o.skipToKey)}else r()}}).next(function(){return PersistencePromise.waitFor(n)})},e.prototype.options=function(e,t){var n=void 0;return void 0!==e&&("string"==typeof e?n=e:(assert$1(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 wrapRequest(e){return new PersistencePromise(function(t,n){e.onsuccess=function(e){var n=e.target.result;t(n)},e.onerror=function(e){n(e.target.error)}})}var IndexedDbQueryCache=function(){function e(e){this.serializer=e,this.garbageCollector=null,this.targetIdGenerator=TargetIdGenerator.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 SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))})},e.prototype.getHighestSequenceNumber=function(e){return getHighestListenSequenceNumber(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 targetsStore(e).delete(t.targetId)}).next(function(){return n.retrieveMetadata(e)}).next(function(t){return assert$1(t.targetCount>0,"Removing from an empty query cache"),t.targetCount-=1,n.saveMetadata(e,t)})},e.prototype.retrieveMetadata=function(e){return retrieveMetadata(e.simpleDbTransaction)},e.prototype.saveMetadata=function(e,t){return globalTargetStore(e).put(DbTargetGlobal.key,t)},e.prototype.saveQueryData=function(e,t){return targetsStore(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 targetsStore(e).iterate({range:i,index:DbTarget.queryTargetsIndexName},function(e,r,i){var a=n.serializer.fromDbTarget(r);t.isEqual(a.query)&&(o=a,i.done())}).next(function(){return o})},e.prototype.addMatchingKeys=function(e,t,n){var r=[],i=documentTargetStore(e);return t.forEach(function(e){var t=encode(e.path);r.push(i.put(new DbTargetDocument(n,t)))}),PersistencePromise.waitFor(r)},e.prototype.removeMatchingKeys=function(e,t,n){var r=this,i=[],o=documentTargetStore(e);return t.forEach(function(e){var t=encode(e.path);i.push(o.delete([n,t])),null!==r.garbageCollector&&r.garbageCollector.addPotentialGarbageKey(e)}),PersistencePromise.waitFor(i)},e.prototype.removeMatchingKeysForTargetId=function(e,t){var n=documentTargetStore(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return this.notifyGCForRemovedKeys(e,r).next(function(){return n.delete(r)})},e.prototype.notifyGCForRemovedKeys=function(e,t){var n=this,r=documentTargetStore(e);return null!==this.garbageCollector&&this.garbageCollector.isEager?r.iterate({range:t,keysOnly:!0},function(e,t,r){var i=decode$1(e[1]),o=new DocumentKey(i);assert$1(null!==n.garbageCollector,"GarbageCollector for query cache set to null during key removal."),n.garbageCollector.addPotentialGarbageKey(o)}):PersistencePromise.resolve()},e.prototype.getMatchingKeysForTargetId=function(e,t){var n=IDBKeyRange.bound([t],[t+1],!1,!0),r=documentTargetStore(e),i=documentKeySet();return r.iterate({range:n,keysOnly:!0},function(e,t,n){var r=decode$1(e[1]),o=new DocumentKey(r);i=i.add(o)}).next(function(){return i})},e.prototype.setGarbageCollector=function(e){this.garbageCollector=e},e.prototype.containsKey=function(e,t){assert$1(null!==e,"Persistence Transaction cannot be null for query cache containsKey");var n=encode(t.path),r=IDBKeyRange.bound([n],[immediateSuccessor(n)],!1,!0),i=0;return documentTargetStore(e).iterate({index:DbTargetDocument.documentTargetsIndex,keysOnly:!0,range:r},function(e,t,n){i++,n.done()}).next(function(){return i>0})},e.prototype.getQueryDataForTarget=function(e,t){var n=this;return targetsStore(e).get(t).next(function(e){return e?n.serializer.fromDbTarget(e):null})},e}();function targetsStore(e){return IndexedDbPersistence.getStore(e,DbTarget.store)}function globalTargetStore(e){return IndexedDbPersistence.getStore(e,DbTargetGlobal.store)}function retrieveMetadata(e){return SimpleDb.getStore(e,DbTargetGlobal.store).get(DbTargetGlobal.key).next(function(e){return assert$1(null!==e,"Missing metadata row."),e})}function getHighestListenSequenceNumber(e){return retrieveMetadata(e).next(function(e){return e.highestListenSequenceNumber})}function documentTargetStore(e){return IndexedDbPersistence.getStore(e,DbTargetDocument.store)}var IndexedDbRemoteDocumentCache=function(){function e(e,t){this.serializer=e,this.keepDocumentChangeLog=t,this._lastProcessedDocumentChangeId=0}return Object.defineProperty(e.prototype,"lastProcessedDocumentChangeId",{get:function(){return this._lastProcessedDocumentChangeId},enumerable:!0,configurable:!0}),e.prototype.start=function(e){var t=this;return this._lastProcessedDocumentChangeId=0,SimpleDb.getStore(e,DbRemoteDocumentChanges.store).iterate({keysOnly:!0,reverse:!0},function(e,n,r){t._lastProcessedDocumentChangeId=e,r.done()})},e.prototype.addEntries=function(e,t){var n=[];if(t.length>0){for(var r=remoteDocumentsStore(e),i=documentKeySet(),o=0,a=t;o<a.length;o++){var s=a[o];n.push(r.put(dbKey(s.key),this.serializer.toDbRemoteDocument(s))),i=i.add(s.key)}this.keepDocumentChangeLog&&n.push(documentChangesStore(e).put({changes:this.serializer.toDbResourcePaths(i)}))}return PersistencePromise.waitFor(n)},e.prototype.removeEntry=function(e,t){return remoteDocumentsStore(e).delete(dbKey(t))},e.prototype.getEntry=function(e,t){var n=this;return remoteDocumentsStore(e).get(dbKey(t)).next(function(e){return e?n.serializer.fromDbRemoteDocument(e):null})},e.prototype.getDocumentsMatchingQuery=function(e,t){var n=this,r=documentMap(),i=t.path.toArray(),o=IDBKeyRange.lowerBound(i);return remoteDocumentsStore(e).iterate({range:o},function(e,i,o){var a=n.serializer.fromDbRemoteDocument(i);t.path.isPrefixOf(a.key.path)?a instanceof Document&&t.matches(a)&&(r=r.insert(a.key,a)):o.done()}).next(function(){return r})},e.prototype.getNewDocumentChanges=function(e){var t=this;assert$1(this.keepDocumentChangeLog,"Can only call getNewDocumentChanges() when document change log is enabled");var n=documentKeySet(),r=maybeDocumentMap(),i=IDBKeyRange.lowerBound(this._lastProcessedDocumentChangeId,!0);return documentChangesStore(e).iterate({range:i},function(e,r){n=n.unionWith(t.serializer.fromDbResourcePaths(r.changes)),t._lastProcessedDocumentChangeId=r.id}).next(function(){var i=[];return n.forEach(function(n){i.push(t.getEntry(e,n).next(function(e){r=r.insert(n,e||new NoDocument(n,SnapshotVersion.forDeletedDoc()))}))}),PersistencePromise.waitFor(i)}).next(function(){return r})},e.prototype.removeDocumentChangesThroughChangeId=function(e,t){var n=IDBKeyRange.upperBound(t);return documentChangesStore(e).delete(n)},e}();function remoteDocumentsStore(e){return IndexedDbPersistence.getStore(e,DbRemoteDocument.store)}function documentChangesStore(e){return IndexedDbPersistence.getStore(e,DbRemoteDocumentChanges.store)}function dbKey(e){return e.path.toArray()}var LocalSerializer=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=DocumentKey.fromSegments(e.noDocument.path),n=this.fromDbTimestamp(e.noDocument.readTime);return new NoDocument(t,n,{hasCommittedMutations:!!e.hasCommittedMutations})}if(e.unknownDocument){t=DocumentKey.fromSegments(e.unknownDocument.path),n=this.fromDbTimestamp(e.unknownDocument.version);return new UnknownDocument(t,n)}return fail("Unexpected DbRemoteDocument")},e.prototype.toDbRemoteDocument=function(e){if(e instanceof Document){var t=this.remoteSerializer.toDocument(e),n=e.hasCommittedMutations;return new DbRemoteDocument(null,null,t,n)}if(e instanceof NoDocument){var r=e.key.path.toArray(),i=this.toDbTimestamp(e.version);n=e.hasCommittedMutations;return new DbRemoteDocument(null,new DbNoDocument(r,i),null,n)}if(e instanceof UnknownDocument){r=e.key.path.toArray(),i=this.toDbTimestamp(e.version);return new DbRemoteDocument(new DbUnknownDocument(r,i),null,null,!0)}return fail("Unexpected MaybeDocumment")},e.prototype.toDbTimestamp=function(e){var t=e.toTimestamp();return new DbTimestamp(t.seconds,t.nanoseconds)},e.prototype.fromDbTimestamp=function(e){var t=new Timestamp(e.seconds,e.nanoseconds);return SnapshotVersion.fromTimestamp(t)},e.prototype.toDbMutationBatch=function(e,t){var n=this,r=t.mutations.map(function(e){return n.remoteSerializer.toMutation(e)});return new DbMutationBatch(e,t.batchId,t.localWriteTime.toMillis(),r)},e.prototype.fromDbMutationBatch=function(e){var t=this,n=e.mutations.map(function(e){return t.remoteSerializer.fromMutation(e)}),r=Timestamp.fromMillis(e.localWriteTimeMs);return new MutationBatch(e.batchId,r,n)},e.prototype.toDbResourcePaths=function(e){var t=[];return e.forEach(function(e){t.push(encode(e.path))}),t},e.prototype.fromDbResourcePaths=function(e){for(var t=documentKeySet(),n=0,r=e;n<r.length;n++){var i=r[n];t=t.add(new DocumentKey(decode$1(i)))}return t},e.prototype.fromDbTarget=function(e){var t,n=this.fromDbTimestamp(e.readTime);return t=isDocumentQuery(e.query)?this.remoteSerializer.fromDocumentsTarget(e.query):this.remoteSerializer.fromQueryTarget(e.query),new QueryData(t,e.targetId,QueryPurpose.Listen,e.lastListenSequenceNumber,n,e.resumeToken)},e.prototype.toDbTarget=function(e){assert$1(QueryPurpose.Listen===e.purpose,"Only queries with purpose "+QueryPurpose.Listen+" may be stored, got "+e.purpose);var t,n,r=this.toDbTimestamp(e.snapshotVersion);return t=e.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(e.query):this.remoteSerializer.toQueryTarget(e.query),e.resumeToken instanceof Uint8Array?(assert$1("YES"===process.env.USE_MOCK_PERSISTENCE,"Persisting non-string stream tokens is only supported with mock persistence ."),n=e.resumeToken.toString()):n=e.resumeToken,new DbTarget(e.targetId,e.query.canonicalId(),r,n,e.sequenceNumber,t)},e}();function isDocumentQuery(e){return void 0!==e.documents}var PersistenceTransaction=function(){return function(){}}(),LOG_TAG$2="IndexedDbPersistence",CLIENT_METADATA_MAX_AGE_MS=5e3,CLIENT_STATE_GARBAGE_COLLECTION_THRESHOLD_MS=18e5,CLIENT_METADATA_REFRESH_INTERVAL_MS=4e3,PRIMARY_LEASE_LOST_ERROR_MSG="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `experimentalTabSynchronization:true` in all tabs.",UNSUPPORTED_PLATFORM_ERROR_MSG="This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.",ZOMBIED_CLIENTS_KEY_PREFIX="firestore_zombie",IndexedDbTransaction=function(e){function t(t,n){var r=e.call(this)||this;return r.simpleDbTransaction=t,r.currentSequenceNumber=n,r}return __extends(t,e),t}(PersistenceTransaction),IndexedDbPersistence=function(){function e(t,n,r,i,o,a){if(this.persistenceKey=t,this.clientId=n,this.queue=i,this.multiClientParams=a,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.inForeground=!1,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(e){return Promise.resolve()},!e.isAvailable())throw new FirestoreError(Code.UNIMPLEMENTED,UNSUPPORTED_PLATFORM_ERROR_MSG);if(this.dbName=t+e.MAIN_DATABASE,this.serializer=new LocalSerializer(o),this.document=r.document,this.allowTabSynchronization=void 0!==a,this.queryCache=new IndexedDbQueryCache(this.serializer),this.remoteDocumentCache=new IndexedDbRemoteDocumentCache(this.serializer,this.allowTabSynchronization),!r.window||!r.window.localStorage)throw new FirestoreError(Code.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=r.window,this.webStorage=this.window.localStorage}return e.getStore=function(e,t){if(e instanceof IndexedDbTransaction)return SimpleDb.getStore(e.simpleDbTransaction,t);throw fail("IndexedDbPersistence must use instances of IndexedDbTransaction")},e.createIndexedDbPersistence=function(t,n,r,i,o){return __awaiter(this,void 0,void 0,function(){var a;return __generator(this,function(s){switch(s.label){case 0:return[4,(a=new e(t,n,r,i,o)).start()];case 1:return s.sent(),[2,a]}})})},e.createMultiClientIndexedDbPersistence=function(t,n,r,i,o,a){return __awaiter(this,void 0,void 0,function(){var s;return __generator(this,function(u){switch(u.label){case 0:return[4,(s=new e(t,n,r,i,o,a)).start()];case 1:return u.sent(),[2,s]}})})},e.prototype.start=function(){var e=this;return assert$1(!this.started,"IndexedDbPersistence double-started!"),assert$1(null!==this.window,"Expected 'window' to be defined"),SimpleDb.openOrCreate(this.dbName,SCHEMA_VERSION,new SchemaConverter(this.serializer)).then(function(t){e.simpleDb=t}).then(function(){return e.startRemoteDocumentCache()}).then(function(){return e.attachVisibilityHandler(),e.attachWindowUnloadHook(),e.updateClientMetadataAndTryBecomePrimary().then(function(){return e.scheduleClientMetadataAndPrimaryLeaseRefreshes()})}).then(function(){return e.simpleDb.runTransaction("readonly",[DbTargetGlobal.store],function(t){return getHighestListenSequenceNumber(t).next(function(t){var n=e.multiClientParams?e.multiClientParams.sequenceNumberSyncer:void 0;e.listenSequence=new ListenSequence(t,n)})})}).then(function(){e._started=!0}).catch(function(t){return e.simpleDb&&e.simpleDb.close(),Promise.reject(t)})},e.prototype.startRemoteDocumentCache=function(){var e=this;return this.simpleDb.runTransaction("readonly",ALL_STORES,function(t){return e.remoteDocumentCache.start(t)})},e.prototype.setPrimaryStateListener=function(e){return this.primaryStateListener=e,e(this.isPrimary)},e.prototype.setNetworkEnabled=function(e){var t=this;this.networkEnabled!==e&&(this.networkEnabled=e,this.queue.enqueueAndForget(function(){return __awaiter(t,void 0,void 0,function(){return __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",ALL_STORES,function(t){return clientMetadataStore(t).put(new DbClientMetadata(e.clientId,Date.now(),e.networkEnabled,e.inForeground,e.remoteDocumentCache.lastProcessedDocumentChangeId)).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 __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){return this.started?[2,this.primaryStateListener(this.isPrimary)]:[2]})})}),r&&!e.isPrimary?e.releasePrimaryLeaseIfHeld(t):e.isPrimary?e.acquireOrExtendPrimaryLease(t):void 0})})},e.prototype.removeClientMetadata=function(e){return clientMetadataStore(e).delete(this.clientId)},e.prototype.maybeGarbageCollectMultiClientState=function(){return __awaiter(this,void 0,void 0,function(){var t,n,r=this;return __generator(this,function(i){switch(i.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,CLIENT_STATE_GARBAGE_COLLECTION_THRESHOLD_MS)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),n=[],[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(i){var o=e.getStore(i,DbClientMetadata.store);return o.loadAll().next(function(e){t=r.filterActiveClients(e,CLIENT_STATE_GARBAGE_COLLECTION_THRESHOLD_MS),n=e.filter(function(e){return-1===t.indexOf(e)})}).next(function(){return PersistencePromise.forEach(n,function(e){return o.delete(e.clientId)})}).next(function(){if((t=t.filter(function(e){return e.clientId!==r.clientId})).length>0){var e=t.map(function(e){return e.lastProcessedDocumentChangeId||0}),n=Math.min.apply(Math,e);return r.remoteDocumentCache.removeDocumentChangesThroughChangeId(i,n)}})})]);case 1:i.sent(),n.forEach(function(e){r.window.localStorage.removeItem(r.zombiedClientLocalStorageKey(e.clientId))}),i.label=2;case 2:return[2]}})})},e.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var e=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(TimerId.ClientMetadataRefresh,CLIENT_METADATA_REFRESH_INTERVAL_MS,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 primaryClientStore(e).get(DbPrimaryClient.key).next(function(n){if(null!==n&&t.isWithinAge(n.leaseTimestampMs,CLIENT_METADATA_MAX_AGE_MS)&&!t.isClientZombied(n.ownerId)){if(t.isLocalClient(n)&&t.networkEnabled)return!0;if(!t.isLocalClient(n)){if(!n.allowTabSynchronization)throw new FirestoreError(Code.FAILED_PRECONDITION,PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG);return!1}}return!(!t.networkEnabled||!t.inForeground)||clientMetadataStore(e).loadAll().next(function(e){return void 0===t.filterActiveClients(e,CLIENT_METADATA_MAX_AGE_MS).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&&debug(LOG_TAG$2,"Client "+(e?"is":"is not")+" eligible for a primary lease."),e})},e.prototype.shutdown=function(e){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(n){switch(n.label){case 0:return this._started=!1,this.markClientZombied(),this.clientMetadataRefresher&&this.clientMetadataRefresher.cancel(),this.detachVisibilityHandler(),this.detachWindowUnloadHook(),[4,this.simpleDb.runTransaction("readwrite",[DbPrimaryClient.store,DbClientMetadata.store],function(e){return t.releasePrimaryLeaseIfHeld(e).next(function(){return t.removeClientMetadata(e)})})];case 1:return n.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),e?[4,SimpleDb.delete(this.dbName)]:[3,3];case 2:n.sent(),n.label=3;case 3:return[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",[DbClientMetadata.store],function(t){return clientMetadataStore(t).loadAll().next(function(t){return e.filterActiveClients(t,CLIENT_METADATA_MAX_AGE_MS).map(function(e){return e.clientId})})})},Object.defineProperty(e.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),e.prototype.getMutationQueue=function(e){return assert$1(this.started,"Cannot initialize MutationQueue before persistence is started."),IndexedDbMutationQueue.forUser(e,this.serializer)},e.prototype.getQueryCache=function(){return assert$1(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},e.prototype.getRemoteDocumentCache=function(){return assert$1(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},e.prototype.runTransaction=function(e,t,n){var r=this;return debug(LOG_TAG$2,"Starting transaction:",e),this.simpleDb.runTransaction("readonly"===t?"readonly":"readwrite",ALL_STORES,function(i){return"readwrite-primary"===t?r.canActAsPrimary(i).next(function(t){if(!t)throw error$2("Failed to obtain primary lease for action '"+e+"'."),r.isPrimary=!1,r.queue.enqueueAndForget(function(){return r.primaryStateListener(!1)}),new FirestoreError(Code.FAILED_PRECONDITION,PRIMARY_LEASE_LOST_ERROR_MSG);return n(new IndexedDbTransaction(i,r.listenSequence.next()))}).next(function(e){return r.acquireOrExtendPrimaryLease(i).next(function(){return e})}):r.verifyAllowTabSynchronization(i).next(function(){return n(new IndexedDbTransaction(i,r.listenSequence.next()))})})},e.prototype.verifyAllowTabSynchronization=function(e){var t=this;return primaryClientStore(e).get(DbPrimaryClient.key).next(function(e){if(null!==e&&t.isWithinAge(e.leaseTimestampMs,CLIENT_METADATA_MAX_AGE_MS)&&!t.isClientZombied(e.ownerId)&&!t.isLocalClient(e)&&!e.allowTabSynchronization)throw new FirestoreError(Code.FAILED_PRECONDITION,PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG)})},e.prototype.acquireOrExtendPrimaryLease=function(e){var t=new DbPrimaryClient(this.clientId,this.allowTabSynchronization,Date.now());return primaryClientStore(e).put(DbPrimaryClient.key,t)},e.isAvailable=function(){return SimpleDb.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;this.isPrimary=!1;var n=primaryClientStore(e);return n.get(DbPrimaryClient.key).next(function(e){return t.isLocalClient(e)?(debug(LOG_TAG$2,"Releasing primary lease."),n.delete(DbPrimaryClient.key)):PersistencePromise.resolve()})},e.prototype.isWithinAge=function(e,t){var n=Date.now();return!(e<n-t)&&(!(e>n)||(error$2("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&&(assert$1(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&&(assert$1("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 debug(LOG_TAG$2,"Client '"+e+"' "+(t?"is":"is not")+" zombied in LocalStorage"),t}catch(e){return error$2(LOG_TAG$2,"Failed to get zombied client id.",e),!1}},e.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(e){error$2("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 ZOMBIED_CLIENTS_KEY_PREFIX+"_"+this.persistenceKey+"_"+e},e.MAIN_DATABASE="main",e}();function isPrimaryLeaseLostError(e){return e.code===Code.FAILED_PRECONDITION&&e.message===PRIMARY_LEASE_LOST_ERROR_MSG}function primaryClientStore(e){return e.store(DbPrimaryClient.store)}function clientMetadataStore(e){return e.store(DbClientMetadata.store)}var LocalDocumentsView=function(){function e(e,t){this.remoteDocumentCache=e,this.mutationQueue=t}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.getDocuments=function(e,t){var n=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(function(r){var i=[],o=maybeDocumentMap();return t.forEach(function(t){i.push(n.getDocumentInternal(e,t,r).next(function(e){e||(e=new NoDocument(t,SnapshotVersion.forDeletedDoc())),o=o.insert(t,e)}))}),PersistencePromise.waitFor(i).next(function(){return o})})},e.prototype.getDocumentsMatchingQuery=function(e,t){return DocumentKey.isDocumentKey(t.path)?this.getDocumentsMatchingDocumentQuery(e,t.path):this.getDocumentsMatchingCollectionQuery(e,t)},e.prototype.getDocumentsMatchingDocumentQuery=function(e,t){return this.getDocument(e,new DocumentKey(t)).next(function(e){var t=documentMap();return e instanceof Document&&(t=t.insert(e.key,e)),t})},e.prototype.getDocumentsMatchingCollectionQuery=function(e,t){var n,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(e,t).next(function(i){return n=i,r.mutationQueue.getAllMutationBatchesAffectingQuery(e,t)}).next(function(e){for(var r=0,i=e;r<i.length;r++)for(var o=i[r],a=0,s=o.mutations;a<s.length;a++){var u=s[a],c=u.key;if(t.path.isImmediateParentOf(c.path)){var h=n.get(c),l=u.applyToLocalView(h,h,o.localWriteTime);n=l instanceof Document?n.insert(c,l):n.remove(c)}}}).next(function(){return n.forEach(function(e,r){t.matches(r)||(n=n.remove(e))}),n})},e}(),ReferenceSet=function(){function e(){this.refsByKey=new SortedSet(DocReference.compareByKey),this.refsByTarget=new SortedSet(DocReference.compareByTargetId),this.garbageCollector=null}return e.prototype.isEmpty=function(){return this.refsByKey.isEmpty()},e.prototype.addReference=function(e,t){var n=new DocReference(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 DocReference(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=DocumentKey.EMPTY,r=new DocReference(n,e),i=new DocReference(n,e+1);this.refsByTarget.forEachInRange([r,i],function(e){t.removeRef(e)})},e.prototype.removeAllReferences=function(){var e=this;this.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),null!==this.garbageCollector&&this.garbageCollector.addPotentialGarbageKey(e.key)},e.prototype.referencesForId=function(e){var t=DocumentKey.EMPTY,n=new DocReference(t,e),r=new DocReference(t,e+1),i=documentKeySet();return this.refsByTarget.forEachInRange([n,r],function(e){i=i.add(e.key)}),i},e.prototype.setGarbageCollector=function(e){this.garbageCollector=e},e.prototype.containsKey=function(e,t){var n=new DocReference(t,0),r=this.refsByKey.firstAfterOrEqual(n);return PersistencePromise.resolve(null!==r&&t.isEqual(r.key))},e}(),DocReference=function(){function e(e,t){this.key=e,this.targetOrBatchId=t}return e.compareByKey=function(e,t){return DocumentKey.comparator(e.key,t.key)||primitiveComparator(e.targetOrBatchId,t.targetOrBatchId)},e.compareByTargetId=function(e,t){return primitiveComparator(e.targetOrBatchId,t.targetOrBatchId)||DocumentKey.comparator(e.key,t.key)},e}(),RemoteDocumentChangeBuffer=function(){function e(e){this.remoteDocumentCache=e,this.changes=maybeDocumentMap()}return e.prototype.addEntry=function(e){var t=this.assertChanges();this.changes=t.insert(e.key,e)},e.prototype.getEntry=function(e,t){var n=this.assertChanges().get(t);return n?PersistencePromise.resolve(n):this.remoteDocumentCache.getEntry(e,t)},e.prototype.apply=function(e){var t=[];return this.assertChanges().forEach(function(e,n){t.push(n)}),this.changes=null,this.remoteDocumentCache.addEntries(e,t)},e.prototype.assertChanges=function(){return assert$1(null!==this.changes,"Changes have already been applied."),this.changes},e}(),LOG_TAG$3="LocalStore",LocalStore=function(){function e(e,t,n){this.persistence=e,this.garbageCollector=n,this.localViewReferences=new ReferenceSet,this.queryDataByTarget={},assert$1(e.started,"LocalStore was passed an unstarted persistence implementation"),this.mutationQueue=e.getMutationQueue(t),this.remoteDocuments=e.getRemoteDocumentCache(),this.queryCache=e.getQueryCache(),this.localDocuments=new LocalDocumentsView(this.remoteDocuments,this.mutationQueue),this.garbageCollector.addGarbageSource(this.localViewReferences),this.garbageCollector.addGarbageSource(this.queryCache),this.garbageCollector.addGarbageSource(this.mutationQueue)}return e.prototype.start=function(){var e=this;return this.persistence.runTransaction("Start LocalStore","readonly",function(t){return e.startMutationQueue(t)})},e.prototype.handleUserChange=function(e){var t=this;return this.persistence.runTransaction("Handle user change","readonly",function(n){var r;return t.mutationQueue.getAllMutationBatches(n).next(function(i){return r=i,t.garbageCollector.removeGarbageSource(t.mutationQueue),t.mutationQueue=t.persistence.getMutationQueue(e),t.garbageCollector.addGarbageSource(t.mutationQueue),t.startMutationQueue(n)}).next(function(){return t.localDocuments=new LocalDocumentsView(t.remoteDocuments,t.mutationQueue),t.mutationQueue.getAllMutationBatches(n)}).next(function(e){for(var i=[],o=[],a=documentKeySet(),s=0,u=r;s<u.length;s++){var c=u[s];i.push(c.batchId);for(var h=0,l=c.mutations;h<l.length;h++){var d=l[h];a=a.add(d.key)}}for(var f=0,p=e;f<p.length;f++){c=p[f];o.push(c.batchId);for(var m=0,y=c.mutations;m<y.length;m++){d=y[m];a=a.add(d.key)}}return t.localDocuments.getDocuments(n,a).next(function(e){return{affectedDocuments:e,removedBatchIds:i,addedBatchIds:o}})})})},e.prototype.startMutationQueue=function(e){return this.mutationQueue.start(e)},e.prototype.localWrite=function(e){var t=this;return this.persistence.runTransaction("Locally write mutations","readwrite",function(n){var r,i=Timestamp.now();return t.mutationQueue.addMutationBatch(n,i,e).next(function(e){var i=(r=e).keys();return t.localDocuments.getDocuments(n,i)}).next(function(e){return{batchId:r.batchId,changes:e}})})},e.prototype.lookupMutationDocuments=function(e){var t=this;return this.persistence.runTransaction("Lookup mutation documents","readonly",function(n){return t.mutationQueue.lookupMutationKeys(n,e).next(function(e){return e?t.localDocuments.getDocuments(n,e):PersistencePromise.resolve(null)})})},e.prototype.acknowledgeBatch=function(e){var t=this;return this.persistence.runTransaction("Acknowledge batch","readwrite-primary",function(n){var r=e.batch.keys(),i=new RemoteDocumentChangeBuffer(t.remoteDocuments);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",function(n){var r;return t.mutationQueue.lookupMutationBatch(n,e).next(function(e){return assert$1(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.getLastStreamToken=function(){var e=this;return this.persistence.runTransaction("Get last stream token","readonly",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",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",function(t){return e.queryCache.getLastRemoteSnapshotVersion(t)})},e.prototype.applyRemoteEvent=function(t){var n=this,r=new RemoteDocumentChangeBuffer(this.remoteDocuments);return this.persistence.runTransaction("Apply remote event","readwrite-primary",function(i){var o=[],a=documentKeySet();forEachNumber(t.targetChanges,function(r,s){var u=n.queryDataByTarget[r];if(u){s.addedDocuments.forEach(function(e){a=a.add(e)}),s.modifiedDocuments.forEach(function(e){a=a.add(e)}),o.push(n.queryCache.removeMatchingKeys(i,s.removedDocuments,r).next(function(){return n.queryCache.addMatchingKeys(i,s.addedDocuments,r)}));var c=s.resumeToken;if(c.length>0){var h=u;u=u.copy({resumeToken:c,snapshotVersion:t.snapshotVersion}),n.queryDataByTarget[r]=u,e.shouldPersistQueryData(h,u,s)&&o.push(n.queryCache.updateQueryData(i,u))}}});var s=documentKeySet();t.documentUpdates.forEach(function(e,t){s=s.add(e),o.push(r.getEntry(i,e).next(function(i){null==i||t.version.isEqual(SnapshotVersion.MIN)||a.has(t.key)&&!i.hasPendingWrites||t.version.compareTo(i.version)>=0?r.addEntry(t):debug(LOG_TAG$3,"Ignoring outdated watch update for ",e,". Current version:",i.version," Watch version:",t.version),n.garbageCollector.addPotentialGarbageKey(e)}))});var u=t.snapshotVersion;if(!u.isEqual(SnapshotVersion.MIN)){var c=n.queryCache.getLastRemoteSnapshotVersion(i).next(function(e){return assert$1(u.compareTo(e)>=0,"Watch stream reverted to previous snapshot?? "+u+" < "+e),n.queryCache.setTargetsMetadata(i,i.currentSequenceNumber,u)});o.push(c)}return PersistencePromise.waitFor(o).next(function(){return r.apply(i)}).next(function(){return n.localDocuments.getDocuments(i,s)})})},e.shouldPersistQueryData=function(e,t,n){return 0!==t.resumeToken.length&&(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=0,n=e;t<n.length;t++){var r=n[t];this.localViewReferences.addReferences(r.addedKeys,r.targetId),this.localViewReferences.removeReferences(r.removedKeys,r.targetId)}},e.prototype.nextMutationBatch=function(e){var t=this;return this.persistence.runTransaction("Get next mutation batch","readonly",function(n){return void 0===e&&(e=BATCHID_UNKNOWN),t.mutationQueue.getNextMutationBatchAfterBatchId(n,e)})},e.prototype.readDocument=function(e){var t=this;return this.persistence.runTransaction("read document","readonly",function(n){return t.localDocuments.getDocument(n,e)})},e.prototype.allocateQuery=function(e){var t=this;return this.persistence.runTransaction("Allocate query","readwrite",function(n){var r;return t.queryCache.getQueryData(n,e).next(function(i){return i?(r=i,PersistencePromise.resolve()):t.queryCache.allocateTargetId(n).next(function(i){return r=new QueryData(e,i,QueryPurpose.Listen,n.currentSequenceNumber),t.queryCache.addQueryData(n,r)})}).next(function(){return assert$1(!t.queryDataByTarget[r.targetId],"Tried to allocate an already allocated query: "+e),t.queryDataByTarget[r.targetId]=r,r})})},e.prototype.releaseQuery=function(e,t){var n=this,r=t?"readonly":"readwrite-primary";return this.persistence.runTransaction("Release query",r,function(r){return n.queryCache.getQueryData(r,e).next(function(i){assert$1(null!=i,"Tried to release nonexistent query: "+e);var o=i.targetId,a=n.queryDataByTarget[o];return n.localViewReferences.removeReferencesForId(o),delete n.queryDataByTarget[o],!t&&n.garbageCollector.isEager?n.queryCache.removeQueryData(r,i):a.snapshotVersion>i.snapshotVersion?n.queryCache.updateQueryData(r,a):PersistencePromise.resolve()})})},e.prototype.executeQuery=function(e){var t=this;return this.persistence.runTransaction("Execute query","readonly",function(n){return t.localDocuments.getDocumentsMatchingQuery(n,e)})},e.prototype.remoteDocumentKeys=function(e){var t=this;return this.persistence.runTransaction("Remote document keys","readonly",function(n){return t.queryCache.getMatchingKeysForTargetId(n,e)})},e.prototype.collectGarbage=function(){var e=this;return this.persistence.runTransaction("Garbage collection","readwrite-primary",function(t){return e.garbageCollector.collectGarbage(t).next(function(n){var r=[];return n.forEach(function(n){r.push(e.remoteDocuments.removeEntry(t,n))}),PersistencePromise.waitFor(r)})})},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=PersistencePromise.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);assert$1(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):assert$1(!e,"Mutation batch "+i+" applied to document "+e+" resulted in null"))})}),a.next(function(){return r.mutationQueue.removeMutationBatch(e,i)})},e.prototype.getQueryForTarget=function(e){var t=this;return this.queryDataByTarget[e]?Promise.resolve(this.queryDataByTarget[e].query):this.persistence.runTransaction("Get query data","readonly",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",function(t){return e.remoteDocuments.getNewDocumentChanges(t)})},e.RESUME_TOKEN_MAX_AGE_MICROS=3e8,e}(),MemoryMutationQueue=function(){function e(){this.mutationQueue=[],this.nextBatchId=1,this.highestAcknowledgedBatchId=BATCHID_UNKNOWN,this.lastStreamToken=emptyByteString(),this.garbageCollector=null,this.batchesByDocumentKey=new SortedSet(DocReference.compareByKey)}return e.prototype.start=function(e){return assert$1(this.highestAcknowledgedBatchId<this.nextBatchId,"highestAcknowledgedBatchId must be less than the nextBatchId"),PersistencePromise.resolve()},e.prototype.checkEmpty=function(e){return PersistencePromise.resolve(0===this.mutationQueue.length)},e.prototype.acknowledgeBatch=function(e,t,n){var r=t.batchId;assert$1(r>this.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var i=this.indexOfExistingBatchId(r,"acknowledged"),o=this.mutationQueue[i];return assert$1(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),assert$1(!o.isTombstone(),"Can't acknowledge a previously removed batch"),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,PersistencePromise.resolve()},e.prototype.getLastStreamToken=function(e){return PersistencePromise.resolve(this.lastStreamToken)},e.prototype.setLastStreamToken=function(e,t){return this.lastStreamToken=t,PersistencePromise.resolve()},e.prototype.addMutationBatch=function(e,t,n){assert$1(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;(this.nextBatchId++,this.mutationQueue.length>0)&&assert$1(this.mutationQueue[this.mutationQueue.length-1].batchId<r,"Mutation batchIDs must be monotonically increasing order");var i=new MutationBatch(r,t,n);this.mutationQueue.push(i);for(var o=0,a=n;o<a.length;o++){var s=a[o];this.batchesByDocumentKey=this.batchesByDocumentKey.add(new DocReference(s.key,r))}return PersistencePromise.resolve(i)},e.prototype.lookupMutationBatch=function(e,t){return PersistencePromise.resolve(this.findMutationBatch(t))},e.prototype.lookupMutationKeys=function(e,t){var n=this.findMutationBatch(t);return assert$1(null!=n,"Failed to find local mutation batch."),PersistencePromise.resolve(n.isTombstone()?null:n.keys())},e.prototype.getNextMutationBatchAfterBatchId=function(e,t){for(var n=this.mutationQueue.length,r=Math.max(t,this.highestAcknowledgedBatchId)+1,i=this.indexOfBatchId(r),o=i<0?0:i;o<n;o++){var a=this.mutationQueue[o];if(!a.isTombstone())return PersistencePromise.resolve(a)}return PersistencePromise.resolve(null)},e.prototype.getAllMutationBatches=function(e){return PersistencePromise.resolve(this.getAllLiveMutationBatchesBeforeIndex(this.mutationQueue.length))},e.prototype.getAllMutationBatchesAffectingDocumentKey=function(e,t){var n=this,r=new DocReference(t,0),i=new DocReference(t,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([r,i],function(e){assert$1(t.isEqual(e.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(e.targetOrBatchId);assert$1(null!==r,"Batches in the index must exist in the main table"),o.push(r)}),PersistencePromise.resolve(o)},e.prototype.getAllMutationBatchesAffectingDocumentKeys=function(e,t){var n=this,r=new SortedSet(primitiveComparator);return t.forEach(function(e){var t=new DocReference(e,0),i=new DocReference(e,Number.POSITIVE_INFINITY);n.batchesByDocumentKey.forEachInRange([t,i],function(t){assert$1(e.isEqual(t.key),"For each key, should only iterate over a single key's batches"),r=r.add(t.targetOrBatchId)})}),PersistencePromise.resolve(this.findMutationBatches(r))},e.prototype.getAllMutationBatchesAffectingQuery=function(e,t){var n=t.path,r=n.length+1,i=n;DocumentKey.isDocumentKey(i)||(i=i.child(""));var o=new DocReference(new DocumentKey(i),0),a=new SortedSet(primitiveComparator);return this.batchesByDocumentKey.forEachWhile(function(e){var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.targetOrBatchId)),!0)},o),PersistencePromise.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.indexOfExistingBatchId(t.batchId,"removed");if(assert$1(this.mutationQueue[n].batchId===t.batchId,"Removed batches must exist in the queue"),0===n){for(var r=1;r<this.mutationQueue.length;r++){if(!this.mutationQueue[r].isTombstone())break}this.mutationQueue.splice(0,r)}else this.mutationQueue[n]=this.mutationQueue[n].toTombstone();for(var i=this.batchesByDocumentKey,o=0,a=t.mutations;o<a.length;o++){var s=a[o].key;null!==this.garbageCollector&&this.garbageCollector.addPotentialGarbageKey(s);var u=new DocReference(s,t.batchId);i=i.delete(u)}return this.batchesByDocumentKey=i,PersistencePromise.resolve()},e.prototype.removeCachedMutationKeys=function(e){},e.prototype.setGarbageCollector=function(e){this.garbageCollector=e},e.prototype.containsKey=function(e,t){var n=new DocReference(t,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return PersistencePromise.resolve(t.isEqual(r&&r.key))},e.prototype.performConsistencyCheck=function(e){return 0===this.mutationQueue.length&&assert$1(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),PersistencePromise.resolve()},e.prototype.getAllLiveMutationBatchesBeforeIndex=function(e){for(var t=[],n=0;n<e;n++){var r=this.mutationQueue[n];r.isTombstone()||t.push(r)}return t},e.prototype.indexOfExistingBatchId=function(e,t){var n=this.indexOfBatchId(e);return assert$1(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 assert$1(n.batchId===e,"If found batch must match"),n.isTombstone()?null:n},e}(),ObjectMap=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){forEach$1(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 isEmpty$1(this.inner)},e}(),MemoryQueryCache=function(){function e(){this.queries=new ObjectMap(function(e){return e.canonicalId()}),this.lastRemoteSnapshotVersion=SnapshotVersion.MIN,this.highestTargetId=0,this.highestSequenceNumber=0,this.references=new ReferenceSet,this.targetCount=0,this.targetIdGenerator=TargetIdGenerator.forQueryCache()}return e.prototype.getLastRemoteSnapshotVersion=function(e){return PersistencePromise.resolve(this.lastRemoteSnapshotVersion)},e.prototype.getHighestSequenceNumber=function(e){return PersistencePromise.resolve(this.highestSequenceNumber)},e.prototype.allocateTargetId=function(e){var t=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=t,PersistencePromise.resolve(t)},e.prototype.setTargetsMetadata=function(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.highestSequenceNumber&&(this.highestSequenceNumber=t),PersistencePromise.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 assert$1(!this.queries.has(t.query),"Adding a query that already exists"),this.saveQueryData(t),this.targetCount+=1,PersistencePromise.resolve()},e.prototype.updateQueryData=function(e,t){return assert$1(this.queries.has(t.query),"Updating a non-existent query"),this.saveQueryData(t),PersistencePromise.resolve()},e.prototype.removeQueryData=function(e,t){return assert$1(this.targetCount>0,"Removing a target from an empty cache"),assert$1(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,PersistencePromise.resolve()},e.prototype.getQueryCount=function(e){return PersistencePromise.resolve(this.targetCount)},e.prototype.getQueryData=function(e,t){var n=this.queries.get(t)||null;return PersistencePromise.resolve(n)},e.prototype.getQueryDataForTarget=function(e,t){return fail("Not yet implemented.")},e.prototype.addMatchingKeys=function(e,t,n){return this.references.addReferences(t,n),PersistencePromise.resolve()},e.prototype.removeMatchingKeys=function(e,t,n){return this.references.removeReferences(t,n),PersistencePromise.resolve()},e.prototype.removeMatchingKeysForTargetId=function(e,t){return this.references.removeReferencesForId(t),PersistencePromise.resolve()},e.prototype.getMatchingKeysForTargetId=function(e,t){var n=this.references.referencesForId(t);return PersistencePromise.resolve(n)},e.prototype.setGarbageCollector=function(e){this.references.setGarbageCollector(e)},e.prototype.containsKey=function(e,t){return this.references.containsKey(e,t)},e}(),MemoryRemoteDocumentCache=function(){function e(){this.docs=maybeDocumentMap(),this.newDocumentChanges=documentKeySet()}return e.prototype.addEntries=function(e,t){for(var n=0,r=t;n<r.length;n++){var i=r[n];this.docs=this.docs.insert(i.key,i),this.newDocumentChanges=this.newDocumentChanges.add(i.key)}return PersistencePromise.resolve()},e.prototype.removeEntry=function(e,t){return this.docs=this.docs.remove(t),PersistencePromise.resolve()},e.prototype.getEntry=function(e,t){return PersistencePromise.resolve(this.docs.get(t))},e.prototype.getDocumentsMatchingQuery=function(e,t){for(var n=documentMap(),r=new DocumentKey(t.path.child("")),i=this.docs.getIteratorFrom(r);i.hasNext();){var o=i.getNext(),a=o.key,s=o.value;if(!t.path.isPrefixOf(a.path))break;s instanceof Document&&t.matches(s)&&(n=n.insert(s.key,s))}return PersistencePromise.resolve(n)},e.prototype.getNewDocumentChanges=function(e){var t=this,n=maybeDocumentMap();return this.newDocumentChanges.forEach(function(e){n=n.insert(e,t.docs.get(e)||new NoDocument(e,SnapshotVersion.forDeletedDoc()))}),this.newDocumentChanges=documentKeySet(),PersistencePromise.resolve(n)},e}(),LOG_TAG$4="MemoryPersistence",MemoryPersistence=function(){function e(e){this.clientId=e,this.mutationQueues={},this.remoteDocumentCache=new MemoryRemoteDocumentCache,this.queryCache=new MemoryQueryCache,this._started=!1,this._started=!0}return e.prototype.shutdown=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this._started=!1,[2]})})},Object.defineProperty(e.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),e.prototype.getActiveClients=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,[this.clientId]]})})},e.prototype.setPrimaryStateListener=function(e){return e(!0)},e.prototype.setNetworkEnabled=function(e){},e.prototype.getMutationQueue=function(e){var t=this.mutationQueues[e.toKey()];return t||(t=new MemoryMutationQueue,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){return debug(LOG_TAG$4,"Starting transaction:",e),n(new MemoryTransaction(ListenSequence.INVALID)).toPromise()},e}(),MemoryTransaction=function(){return function(e){this.currentSequenceNumber=e}}(),NoOpGarbageCollector=function(){function e(){this.isEager=!1}return e.prototype.addGarbageSource=function(e){},e.prototype.removeGarbageSource=function(e){},e.prototype.addPotentialGarbageKey=function(e){},e.prototype.collectGarbage=function(e){return PersistencePromise.resolve(documentKeySet())},e}(),LOG_TAG$5="ExponentialBackoff",ExponentialBackoff=function(){function e(e,t,n,r,i){this.queue=e,this.timerId=t,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=i,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();var n=Math.floor(this.currentBaseMs+this.jitterDelayMs()),r=Math.max(0,Date.now()-this.lastAttemptTime),i=Math.max(0,n-r);this.currentBaseMs>0&&debug(LOG_TAG$5,"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}(),LOG_TAG$6="PersistentStream",PersistentStreamState;!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"}(PersistentStreamState||(PersistentStreamState={}));var BACKOFF_INITIAL_DELAY_MS=1e3,BACKOFF_MAX_DELAY_MS=6e4,BACKOFF_FACTOR=1.5,IDLE_TIMEOUT_MS=6e4,PersistentStream=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=PersistentStreamState.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new ExponentialBackoff(e,t,BACKOFF_INITIAL_DELAY_MS,BACKOFF_FACTOR,BACKOFF_MAX_DELAY_MS)}return e.prototype.isStarted=function(){return this.state===PersistentStreamState.Starting||this.state===PersistentStreamState.Open||this.state===PersistentStreamState.Backoff},e.prototype.isOpen=function(){return this.state===PersistentStreamState.Open},e.prototype.start=function(){this.state!==PersistentStreamState.Error?(assert$1(this.state===PersistentStreamState.Initial,"Already started"),this.auth()):this.performBackoff()},e.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this.isStarted()?[4,this.close(PersistentStreamState.Initial)]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},e.prototype.inhibitBackoff=function(){assert$1(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=PersistentStreamState.Initial,this.backoff.reset()},e.prototype.markIdle=function(){var e=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,IDLE_TIMEOUT_MS,function(){return e.handleIdleCloseTimer()}))},e.prototype.sendRequest=function(e){this.cancelIdleCheck(),this.stream.send(e)},e.prototype.handleIdleCloseTimer=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.isOpen()?[2,this.close(PersistentStreamState.Initial)]:[2]})})},e.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},e.prototype.close=function(e,t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(n){switch(n.label){case 0:return assert$1(this.isStarted(),"Only started streams should be closed."),assert$1(e===PersistentStreamState.Error||isNullOrUndefined(t),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,e!==PersistentStreamState.Error?this.backoff.reset():t&&t.code===Code.RESOURCE_EXHAUSTED?(error$2(t.toString()),error$2("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):t&&t.code===Code.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;assert$1(this.state===PersistentStreamState.Initial,"Must be in initial state to auth"),this.state=PersistentStreamState.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 FirestoreError(Code.UNKNOWN,"Fetching auth token failed: "+n.message);return e.handleStreamClose(t)})})},e.prototype.startStream=function(e){var t=this;assert$1(this.state===PersistentStreamState.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 assert$1(t.state===PersistentStreamState.Starting,"Expected stream to be in state Starting, but was "+t.state),t.state=PersistentStreamState.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;assert$1(this.state===PersistentStreamState.Error,"Should only perform backoff when in Error state"),this.state=PersistentStreamState.Backoff,this.backoff.backoffAndRun(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){return assert$1(this.state===PersistentStreamState.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=PersistentStreamState.Initial,this.start(),assert$1(this.isStarted(),"PersistentStream should have started"),[2]})})})},e.prototype.handleStreamClose=function(e){return assert$1(this.isStarted(),"Can't handle server close on non-started stream"),debug(LOG_TAG$6,"close with error: "+e),this.stream=null,this.close(PersistentStreamState.Error,e)},e.prototype.getCloseGuardedDispatcher=function(e){var t=this;return function(n){t.queue.enqueueAndForget(function(){return t.closeCount===e?n():(debug(LOG_TAG$6,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}},e}(),PersistentListenStream=function(e){function t(t,n,r,i,o){var a=e.call(this,t,TimerId.ListenStreamConnectionBackoff,TimerId.ListenStreamIdle,n,r,o)||this;return a.serializer=i,a}return __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}(PersistentStream),PersistentWriteStream=function(e){function t(t,n,r,i,o){var a=e.call(this,t,TimerId.WriteStreamConnectionBackoff,TimerId.WriteStreamIdle,n,r,o)||this;return a.serializer=i,a.handshakeComplete_=!1,a}return __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(assert$1(!!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 assert$1(!e.writeResults||0===e.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},t.prototype.writeHandshake=function(){assert$1(this.isOpen(),"Writing handshake requires an opened stream"),assert$1(!this.handshakeComplete_,"Handshake already completed");var e={};e.database=this.serializer.encodedDatabaseId,this.sendRequest(e)},t.prototype.writeMutations=function(e){var t=this;assert$1(this.isOpen(),"Writing mutations requires an opened stream"),assert$1(this.handshakeComplete_,"Handshake must be complete before writing mutations"),assert$1(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}(PersistentStream),Datastore=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 PersistentWriteStream(this.queue,this.connection,this.credentials,this.serializer,e)},e.prototype.newPersistentWatchStream=function(e){return new PersistentListenStream(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=maybeDocumentMap();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);assert$1(!!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===Code.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===Code.UNAUTHENTICATED&&n.credentials.invalidateToken(),e})},e}(),Transaction=function(){function e(e){this.datastore=e,this.readVersions=documentVersionMap(),this.mutations=[],this.committed=!1}return e.prototype.recordVersion=function(e){var t;if(e instanceof Document)t=e.version;else{if(!(e instanceof NoDocument))throw fail("Document in a transaction was a "+e.constructor.name);t=SnapshotVersion.forDeletedDoc()}var n=this.readVersions.get(e.key);if(null!==n){if(!t.isEqual(n))throw new FirestoreError(Code.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(e.key,t)},e.prototype.lookup=function(e){var t=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(e).then(function(e){return e.forEach(function(e){e instanceof NoDocument||e instanceof Document?t.recordVersion(e):fail("Document in a transaction was a "+e.constructor.name)}),e})},e.prototype.write=function(e){if(this.committed)throw new FirestoreError(Code.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(e)},e.prototype.precondition=function(e){var t=this.readVersions.get(e);return t?Precondition.updateTime(t):Precondition.NONE},e.prototype.preconditionForUpdate=function(e){var t=this.readVersions.get(e);if(t&&t.isEqual(SnapshotVersion.forDeletedDoc()))throw new FirestoreError(Code.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return t?Precondition.updateTime(t):Precondition.exists(!0)},e.prototype.set=function(e,t){this.write(t.toMutations(e,this.precondition(e)))},e.prototype.update=function(e,t){this.write(t.toMutations(e,this.preconditionForUpdate(e)))},e.prototype.delete=function(e){this.write([new DeleteMutation(e,this.precondition(e))]),this.readVersions=this.readVersions.insert(e,SnapshotVersion.forDeletedDoc())},e.prototype.commit=function(){var e=this,t=this.readVersions;return this.mutations.forEach(function(e){t=t.remove(e.key)}),t.isEmpty()?this.datastore.commit(this.mutations).then(function(){e.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},e}(),OnlineState,OnlineStateSource;!function(e){e[e.Unknown=0]="Unknown",e[e.Online=1]="Online",e[e.Offline=2]="Offline"}(OnlineState||(OnlineState={})),function(e){e[e.RemoteStore=0]="RemoteStore",e[e.SharedClientState=1]="SharedClientState"}(OnlineStateSource||(OnlineStateSource={}));var LOG_TAG$7="OnlineStateTracker",MAX_WATCH_STREAM_FAILURES=1,ONLINE_STATE_TIMEOUT_MS=1e4,OnlineStateTracker=function(){function e(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state=OnlineState.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}return e.prototype.handleWatchStreamStart=function(){var e=this;0===this.watchStreamFailures&&(this.setAndBroadcast(OnlineState.Unknown),assert$1(null===this.onlineStateTimer,"onlineStateTimer shouldn't be started yet"),this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(TimerId.OnlineStateTimeout,ONLINE_STATE_TIMEOUT_MS,function(){return e.onlineStateTimer=null,assert$1(e.state===OnlineState.Unknown,"Timer should be canceled if we transitioned to a different state."),e.logClientOfflineWarningIfNecessary("Backend didn't respond within "+ONLINE_STATE_TIMEOUT_MS/1e3+" seconds."),e.setAndBroadcast(OnlineState.Offline),Promise.resolve()}))},e.prototype.handleWatchStreamFailure=function(e){this.state===OnlineState.Online?(this.setAndBroadcast(OnlineState.Unknown),assert$1(0===this.watchStreamFailures,"watchStreamFailures must be 0"),assert$1(null===this.onlineStateTimer,"onlineStateTimer must be null")):(this.watchStreamFailures++,this.watchStreamFailures>=MAX_WATCH_STREAM_FAILURES&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary("Connection failed "+MAX_WATCH_STREAM_FAILURES+" times. Most recent error: "+e.toString()),this.setAndBroadcast(OnlineState.Offline)))},e.prototype.set=function(e){this.clearOnlineStateTimer(),this.watchStreamFailures=0,e===OnlineState.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?(error$2(t),this.shouldWarnClientIsOffline=!1):debug(LOG_TAG$7,t)},e.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},e}(),LOG_TAG$8="RemoteStore",MAX_PENDING_WRITES=10,RemoteStore=function(){function e(e,t,n,r){this.localStore=e,this.datastore=t,this.writePipeline=[],this.listenTargets={},this.watchChangeAggregator=null,this.networkEnabled=!1,this.isPrimary=!1,this.onlineStateTracker=new OnlineStateTracker(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 __awaiter(this,void 0,void 0,function(){var e;return __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(OnlineState.Unknown),[4,this.fillWritePipeline()];case 2:t.sent(),t.label=3;case 3:return[2]}})})},e.prototype.disableNetwork=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return e.sent(),this.onlineStateTracker.set(OnlineState.Offline),[2]}})})},e.prototype.disableNetworkInternal=function(){return __awaiter(this,void 0,void 0,function(){return __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&&(debug(LOG_TAG$8,"Stopping write stream with "+this.writePipeline.length+" pending writes"),this.writePipeline=[]),this.cleanUpWatchStreamState(),[2]}})})},e.prototype.shutdown=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return debug(LOG_TAG$8,"RemoteStore shutting down."),this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return e.sent(),this.onlineStateTracker.set(OnlineState.Unknown),[2]}})})},e.prototype.listen=function(e){assert$1(!contains$2(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){assert$1(contains$2(this.listenTargets,e),"unlisten called without assigned target ID!"),delete this.listenTargets[e],this.watchStream.isOpen()&&this.sendUnwatchRequest(e),isEmpty$1(this.listenTargets)&&(this.watchStream.isOpen()?this.watchStream.markIdle():this.canUseNetwork()&&this.onlineStateTracker.set(OnlineState.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(){assert$1(this.shouldStartWatchStream(),"startWatchStream() called when shouldStartWatchStream() is false."),this.watchChangeAggregator=new WatchChangeAggregator(this),this.watchStream.start(),this.onlineStateTracker.handleWatchStreamStart()},e.prototype.shouldStartWatchStream=function(){return this.canUseNetwork()&&!this.watchStream.isStarted()&&!isEmpty$1(this.listenTargets)},e.prototype.canUseNetwork=function(){return this.isPrimary&&this.networkEnabled},e.prototype.cleanUpWatchStreamState=function(){this.watchChangeAggregator=null},e.prototype.onWatchStreamOpen=function(){return __awaiter(this,void 0,void 0,function(){var e=this;return __generator(this,function(t){return forEachNumber(this.listenTargets,function(t,n){e.sendWatchRequest(n)}),[2]})})},e.prototype.onWatchStreamClose=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return void 0===e&&assert$1(!this.shouldStartWatchStream(),"Watch stream was stopped gracefully while still needed."),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.onlineStateTracker.handleWatchStreamFailure(e),this.startWatchStream()):this.onlineStateTracker.set(OnlineState.Unknown),[2]})})},e.prototype.onWatchStreamChange=function(e,t){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(r){switch(r.label){case 0:return this.onlineStateTracker.set(OnlineState.Online),e instanceof WatchTargetChange&&e.state===WatchTargetChangeState.Removed&&e.cause?[2,this.handleTargetError(e)]:(e instanceof DocumentWatchChange?this.watchChangeAggregator.handleDocumentChange(e):e instanceof ExistenceFilterChange?this.watchChangeAggregator.handleExistenceFilter(e):(assert$1(e instanceof WatchTargetChange,"Expected watchChange to be an instance of WatchTargetChange"),this.watchChangeAggregator.handleTargetChange(e)),t.isEqual(SnapshotVersion.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;assert$1(!e.isEqual(SnapshotVersion.MIN),"Can't raise event for unknown SnapshotVersion");var n=this.watchChangeAggregator.createRemoteEvent(e);return forEachNumber(n.targetChanges,function(n,r){if(r.resumeToken.length>0){var i=t.listenTargets[n];i&&(t.listenTargets[n]=i.copy({resumeToken:r.resumeToken,snapshotVersion:e}))}}),n.targetMismatches.forEach(function(e){var n=t.listenTargets[e];if(n){t.listenTargets[e]=n.copy({resumeToken:emptyByteString()}),t.sendUnwatchRequest(e);var r=new QueryData(n.query,e,QueryPurpose.ExistenceFilterMismatch,n.sequenceNumber);t.sendWatchRequest(r)}}),this.syncEngine.applyRemoteEvent(n)},e.prototype.handleTargetError=function(e){var t=this;assert$1(!!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 __awaiter(t,void 0,void 0,function(){return __generator(this,function(t){return contains$2(this.listenTargets,e)?(delete this.listenTargets[e],this.watchChangeAggregator.removeTarget(e),[2,this.syncEngine.rejectListen(e,n)]):[2]})})})}),r},e.prototype.fillWritePipeline=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(n){switch(n.label){case 0:return this.canAddToWritePipeline()?(e=this.writePipeline.length>0?this.writePipeline[this.writePipeline.length-1].batchId:BATCHID_UNKNOWN,[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<MAX_PENDING_WRITES},e.prototype.outstandingWrites=function(){return this.writePipeline.length},e.prototype.addToWritePipeline=function(e){assert$1(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(){assert$1(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},e.prototype.onWriteStreamOpen=function(){return __awaiter(this,void 0,void 0,function(){return __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(function(t){return e.ignoreIfPrimaryLeaseLoss(t)})},e.prototype.ignoreIfPrimaryLeaseLoss=function(e){if(!isPrimaryLeaseLostError(e))throw e;debug(LOG_TAG$8,"Unexpectedly lost primary lease")},e.prototype.onMutationResult=function(e,t){var n=this;assert$1(this.writePipeline.length>0,"Got result for empty write pipeline");var r=this.writePipeline.shift(),i=MutationBatchResult.from(r,e,t,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then(function(){return n.fillWritePipeline()})},e.prototype.onWriteStreamClose=function(e){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(n){return void 0===e&&assert$1(!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 __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(n){return isPermanentError(e.code)||e.code===Code.ABORTED?(debug(LOG_TAG$8,"RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=emptyByteString(),[2,this.localStore.setLastStreamToken(emptyByteString()).catch(function(e){return t.ignoreIfPrimaryLeaseLoss(e)})]):[2]})})},e.prototype.handleWriteError=function(e){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(r){return isPermanentError(e.code)?(t=this.writePipeline.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(t.batchId,e).then(function(){return n.fillWritePipeline()})]):[2]})})},e.prototype.createTransaction=function(){return new Transaction(this.datastore)},e.prototype.handleCredentialChange=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this.canUseNetwork()?(debug(LOG_TAG$8,"RemoteStore restarting streams for new credential"),this.networkEnabled=!1,[4,this.disableNetworkInternal()]):[3,3];case 1:return e.sent(),this.onlineStateTracker.set(OnlineState.Unknown),[4,this.enableNetwork()];case 2:e.sent(),e.label=3;case 3:return[2]}})})},e.prototype.applyPrimaryState=function(e){return __awaiter(this,void 0,void 0,function(){return __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(OnlineState.Unknown),t.label=4;case 4:return[2]}})})},e}(),QueryListenersInfo=function(){return function(){this.listeners=[]}}(),EventManager=function(){function e(e){this.syncEngine=e,this.queries=new ObjectMap(function(e){return e.canonicalId()}),this.onlineState=OnlineState.Unknown,this.syncEngine.subscribe(this)}return e.prototype.listen=function(e){var t=e.query,n=!1,r=this.queries.get(t);return r||(n=!0,r=new QueryListenersInfo,this.queries.set(t,r)),r.listeners.push(e),e.applyOnlineStateChange(this.onlineState),r.viewSnap&&e.onViewSnapshot(r.viewSnap),n?this.syncEngine.listen(t).then(function(e){return r.targetId=e,e}):Promise.resolve(r.targetId)},e.prototype.unlisten=function(e){return __awaiter(this,void 0,void 0,function(){var t,n,r,i;return __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=0,n=e;t<n.length;t++){var r=n[t],i=r.query,o=this.queries.get(i);if(o){for(var a=0,s=o.listeners;a<s.length;a++){s[a].onViewSnapshot(r)}o.viewSnap=r}}},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,this.queries.forEach(function(t,n){for(var r=0,i=n.listeners;r<i.length;r++){i[r].applyOnlineStateChange(e)}})},e}(),QueryListener=function(){function e(e,t,n){this.query=e,this.queryObserver=t,this.raisedInitialEvent=!1,this.onlineState=OnlineState.Unknown,this.options=n||{}}return e.prototype.onViewSnapshot=function(e){if(assert$1(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!==ChangeType.Metadata&&t.push(i)}e=new ViewSnapshot(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}this.raisedInitialEvent?this.shouldRaiseEvent(e)&&this.queryObserver.next(e):this.shouldRaiseInitialEvent(e,this.onlineState)&&this.raiseInitialEvent(e),this.snap=e},e.prototype.onError=function(e){this.queryObserver.error(e)},e.prototype.applyOnlineStateChange=function(e){this.onlineState=e,this.snap&&!this.raisedInitialEvent&&this.shouldRaiseInitialEvent(this.snap,e)&&this.raiseInitialEvent(this.snap)},e.prototype.shouldRaiseInitialEvent=function(e,t){if(assert$1(!this.raisedInitialEvent,"Determining whether to raise first event but already had first event"),!e.fromCache)return!0;var n=t!==OnlineState.Offline;return this.options.waitForSyncWhenOnline&&n?(assert$1(e.fromCache,"Waiting for sync, but snapshot is not from cache"),!1):!e.docs.isEmpty()||t===OnlineState.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){assert$1(!this.raisedInitialEvent,"Trying to raise initial events for second time"),e=ViewSnapshot.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.raisedInitialEvent=!0,this.queryObserver.next(e)},e}(),LocalViewChanges=function(){function e(e,t,n){this.targetId=e,this.addedKeys=t,this.removedKeys=n}return e.fromSnapshot=function(t,n){for(var r=documentKeySet(),i=documentKeySet(),o=0,a=n.docChanges;o<a.length;o++){var s=a[o];switch(s.type){case ChangeType.Added:r=r.add(s.doc.key);break;case ChangeType.Removed:i=i.add(s.doc.key)}}return new e(t,r,i)},e}(),AddedLimboDocument=function(){return function(e){this.key=e}}(),RemovedLimboDocument=function(){return function(e){this.key=e}}(),View$1=function(){function e(e,t){this.query=e,this._syncedDocuments=t,this.syncState=null,this.current=!1,this.limboDocuments=documentKeySet(),this.mutatedKeys=documentKeySet(),this.documentSet=new DocumentSet(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 DocumentChangeSet,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():null;if(e.inorderTraversal(function(e,t){var c=i.get(e),h=t instanceof Document?t:null;h&&(assert$1(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),d=!!h&&(h.hasLocalMutations||n.mutatedKeys.has(h.key)&&h.hasCommittedMutations),f=!1;c&&h?c.data.isEqual(h.data)?l!==d&&(r.track({type:ChangeType.Metadata,doc:h}),f=!0):n.shouldWaitForSyncedDocument(c,h)||(r.track({type:ChangeType.Modified,doc:h}),f=!0,u&&n.query.docComparator(h,u)>0&&(s=!0)):!c&&h?(r.track({type:ChangeType.Added,doc:h}),f=!0):c&&!h&&(r.track({type:ChangeType.Removed,doc:c}),f=!0,u&&(s=!0));f&&(h?(a=a.add(h),o=d?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:ChangeType.Removed,doc:c})}return assert$1(!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;assert$1(!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 compareChangeType(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?SyncState.Synced:SyncState.Local,u=s!==this.syncState;return this.syncState=s,0!==o.length||u?{snapshot:new ViewSnapshot(this.query,e.documentSet,i,o,e.mutatedKeys,s===SyncState.Local,u,!1),limboChanges:a}:{limboChanges:a}},e.prototype.applyOnlineStateChange=function(e){return this.current&&e===OnlineState.Offline?(this.current=!1,this.applyChanges({documentSet:this.documentSet,changeSet:new DocumentChangeSet,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 assert$1(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=documentKeySet(),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 RemovedLimboDocument(t))}),this.limboDocuments.forEach(function(e){t.has(e)||n.push(new AddedLimboDocument(e))}),n},e.prototype.synchronizeWithPersistedState=function(e,t){this._syncedDocuments=t,this.limboDocuments=documentKeySet();var n=this.computeDocChanges(e);return this.applyChanges(n,!0)},e.prototype.computeInitialSnapshot=function(){return ViewSnapshot.fromInitialDocuments(this.query,this.documentSet,this.mutatedKeys,this.syncState===SyncState.Local)},e}();function compareChangeType(e,t){var n=function(e){switch(e){case ChangeType.Added:return 1;case ChangeType.Modified:case ChangeType.Metadata:return 2;case ChangeType.Removed:return 0;default:return fail("Unknown ChangeType: "+e)}};return n(e)-n(t)}var LOG_TAG$9="SyncEngine",QueryView=function(){return function(e,t,n){this.query=e,this.targetId=t,this.view=n}}(),LimboResolution=function(){return function(e){this.key=e}}(),SyncEngine=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 ObjectMap(function(e){return e.canonicalId()}),this.queryViewsByTarget={},this.limboTargetsByKey=new SortedMap$1(DocumentKey.comparator),this.limboResolutionsByTarget={},this.limboDocumentRefs=new ReferenceSet,this.mutationUserCallbacks={},this.limboTargetIdGenerator=TargetIdGenerator.forSyncEngine(),this.isPrimary=void 0,this.onlineState=OnlineState.Unknown}return Object.defineProperty(e.prototype,"isPrimaryClient",{get:function(){return!0===this.isPrimary},enumerable:!0,configurable:!0}),e.prototype.subscribe=function(e){assert$1(null!==e,"SyncEngine listener cannot be null"),assert$1(null===this.syncEngineListener,"SyncEngine already has a subscriber."),this.syncEngineListener=e},e.prototype.listen=function(e){return __awaiter(this,void 0,void 0,function(){var t,n,r,i,o;return __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){var n=this,r=e.query;return this.localStore.executeQuery(r).then(function(i){return n.localStore.remoteDocumentKeys(e.targetId).then(function(o){var a=new View$1(r,o),s=a.computeDocChanges(i),u=TargetChange.createSynthesizedTargetChangeForCurrentChange(e.targetId,t&&n.onlineState!==OnlineState.Offline),c=a.applyChanges(s,!0===n.isPrimary,u);assert$1(0===c.limboChanges.length,"View returned limbo docs before target ack from the server."),assert$1(!!c.snapshot,"applyChanges for new view should always return a snapshot");var h=new QueryView(r,e.targetId,a);return n.queryViewsByQuery.set(r,h),n.queryViewsByTarget[e.targetId]=h,c.snapshot})})},e.prototype.synchronizeViewAndComputeSnapshot=function(e){var t=this;return this.localStore.executeQuery(e.query).then(function(n){return t.localStore.remoteDocumentKeys(e.targetId).then(function(r){return __awaiter(t,void 0,void 0,function(){var t;return __generator(this,function(i){switch(i.label){case 0:return t=e.view.synchronizeWithPersistedState(n,r),this.isPrimary?[4,this.updateTrackedLimbos(e.targetId,t.limboChanges)]:[3,2];case 1:i.sent(),i.label=2;case 2:return[2,t]}})})})})},e.prototype.unlisten=function(e){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(r){switch(r.label){case 0:return this.assertSubscribed("unlisten()"),assert$1(!!(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(){return n.sharedClientState.clearQueryState(t.targetId),n.remoteStore.unlisten(t.targetId),n.removeAndCleanupQuery(t)}).then(function(){return n.localStore.collectGarbage()}).catch(function(e){return n.ignoreIfPrimaryLeaseLoss(e)})]):[3,3];case 1:r.sent(),r.label=2;case 2:return[3,6];case 3:return[4,this.removeAndCleanupQuery(t)];case 4:return r.sent(),[4,this.localStore.releaseQuery(e,!0)];case 5:r.sent(),r.label=6;case 6:return[2]}})})},e.prototype.write=function(e,t){var n=this;return this.assertSubscribed("write()"),this.localStore.localWrite(e).then(function(e){return n.sharedClientState.addPendingMutation(e.batchId),n.addMutationCallback(e.batchId,t),n.emitNewSnapsAndNotifyLocalStore(e.changes)}).then(function(){return n.remoteStore.fillWritePipeline()})},e.prototype.wrapUpdateFunctionError=function(e){return e},e.prototype.runTransaction=function(e,t){var n=this;void 0===t&&(t=5),assert$1(t>=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var t=e(r);return!isNullOrUndefined(t)&&t.catch&&t.then?t.catch(function(e){return Promise.reject(n.wrapUpdateFunctionError(e))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(e){return Promise.reject(n.wrapUpdateFunctionError(e))}}().then(function(i){return r.commit().then(function(){return i}).catch(function(r){return 0===t?Promise.reject(r):n.runTransaction(e,t-1)})})},e.prototype.applyRemoteEvent=function(e){var t=this;return this.assertSubscribed("applyRemoteEvent()"),this.localStore.applyRemoteEvent(e).then(function(n){return forEach$1(e.targetChanges,function(e,n){var r=t.limboResolutionsByTarget[e];r&&(assert$1(n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size<=1,"Limbo resolution for single document contains multiple changes."),n.addedDocuments.size>0?r.receivedDocument=!0:n.modifiedDocuments.size>0?assert$1(r.receivedDocument,"Received change for limbo target document without add."):n.removedDocuments.size>0&&(assert$1(r.receivedDocument,"Received remove for limbo target document without add."),r.receivedDocument=!1))}),t.emitNewSnapsAndNotifyLocalStore(n,e)}).catch(function(e){return t.ignoreIfPrimaryLeaseLoss(e)})},e.prototype.applyOnlineStateChange=function(e,t){if(this.isPrimary&&t===OnlineStateSource.RemoteStore||!this.isPrimary&&t===OnlineStateSource.SharedClientState){var n=[];this.queryViewsByQuery.forEach(function(t,r){var i=r.view.applyOnlineStateChange(e);assert$1(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 __awaiter(this,void 0,void 0,function(){var n,r,i,o,a,s,u=this;return __generator(this,function(c){switch(c.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 SortedMap$1(DocumentKey.comparator)).insert(r,new NoDocument(r,SnapshotVersion.forDeletedDoc())),o=documentKeySet().add(r),a=new RemoteEvent(SnapshotVersion.MIN,{},new SortedSet(primitiveComparator),i,o),[2,this.applyRemoteEvent(a)]):[3,1];case 1:return assert$1(!!(s=this.queryViewsByTarget[e]),"Unknown targetId: "+e),[4,this.localStore.releaseQuery(s.query,!1).then(function(){return u.removeAndCleanupQuery(s)}).catch(function(e){return u.ignoreIfPrimaryLeaseLoss(e)})];case 2:c.sent(),this.syncEngineListener.onWatchError(s.query,t),c.label=3;case 3:return[2]}})})},e.prototype.applyBatchState=function(e,t,n){return __awaiter(this,void 0,void 0,function(){var r;return __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())?(debug(LOG_TAG$9,"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)):fail("Unknown batchState: "+t),i.label=4;case 4:return[4,this.emitNewSnapsAndNotifyLocalStore(r)];case 5:return i.sent(),[2]}})})},e.prototype.applySuccessfulWrite=function(e){var t=this;this.assertSubscribed("applySuccessfulWrite()");var n=e.batch.batchId;return this.processUserCallback(n,null),this.localStore.acknowledgeBatch(e).then(function(e){return t.sharedClientState.updateMutationState(n,"acknowledged"),t.emitNewSnapsAndNotifyLocalStore(e)}).catch(function(e){return t.ignoreIfPrimaryLeaseLoss(e)})},e.prototype.rejectFailedWrite=function(e,t){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(e,t),this.localStore.rejectBatch(e).then(function(r){return n.sharedClientState.updateMutationState(e,"rejected",t),n.emitNewSnapsAndNotifyLocalStore(r)}).catch(function(e){return n.ignoreIfPrimaryLeaseLoss(e)})},e.prototype.addMutationCallback=function(e,t){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new SortedMap$1(primitiveComparator)),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&&(assert$1(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){return __awaiter(this,void 0,void 0,function(){var t,n=this;return __generator(this,function(r){switch(r.label){case 0:return this.sharedClientState.removeLocalQueryTarget(e.targetId),this.queryViewsByQuery.delete(e.query),delete this.queryViewsByTarget[e.targetId],this.isPrimary?(t=this.limboDocumentRefs.referencesForId(e.targetId),this.limboDocumentRefs.removeReferencesForId(e.targetId),[4,PersistencePromise.forEach(t.toArray(),function(e){return n.limboDocumentRefs.containsKey(null,e).next(function(t){t||n.removeLimboTarget(e)})}).toPromise()]):[3,2];case 1:r.sent(),r.label=2;case 2:return[2]}})})},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){return __awaiter(this,void 0,void 0,function(){var n,r,i,o,a,s=this;return __generator(this,function(u){switch(u.label){case 0:n=function(t){return __generator(this,function(n){switch(n.label){case 0:return t instanceof AddedLimboDocument?(r.limboDocumentRefs.addReference(t.key,e),r.trackLimboChange(t),[3,4]):[3,1];case 1:return t instanceof RemovedLimboDocument?(debug(LOG_TAG$9,"Document no longer in limbo: "+t.key),r.limboDocumentRefs.removeReference(t.key,e),[4,r.limboDocumentRefs.containsKey(null,t.key).next(function(e){e||s.removeLimboTarget(t.key)}).toPromise()]):[3,3];case 2:return n.sent(),[3,4];case 3:fail("Unknown limbo change: "+JSON.stringify(t)),n.label=4;case 4:return[2]}})},r=this,i=0,o=t,u.label=1;case 1:return i<o.length?(a=o[i],[5,n(a)]):[3,4];case 2:u.sent(),u.label=3;case 3:return i++,[3,1];case 4:return[2]}})})},e.prototype.trackLimboChange=function(e){var t=e.key;if(!this.limboTargetsByKey.get(t)){debug(LOG_TAG$9,"New document in limbo: "+t);var n=this.limboTargetIdGenerator.next(),r=Query$1.atPath(t.path);this.limboResolutionsByTarget[n]=new LimboResolution(t),this.remoteStore.listen(new QueryData(r,n,QueryPurpose.LimboResolution,ListenSequence.INVALID)),this.limboTargetsByKey=this.limboTargetsByKey.insert(t,n)}},e.prototype.currentLimboDocs=function(){return this.limboTargetsByKey},e.prototype.emitNewSnapsAndNotifyLocalStore=function(e,t){return __awaiter(this,void 0,void 0,function(){var n,r,i,o=this;return __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).then(function(e){return s.view.computeDocChanges(e,t)}):t}).then(function(e){var i=t&&t.targetChanges[s.targetId],a=s.view.applyChanges(e,!0===o.isPrimary,i);return o.updateTrackedLimbos(s.targetId,a.limboChanges).then(function(){if(a.snapshot){o.isPrimary&&o.sharedClientState.updateQueryState(s.targetId,a.snapshot.fromCache?"not-current":"current"),n.push(a.snapshot);var e=LocalViewChanges.fromSnapshot(s.targetId,a.snapshot);r.push(e)}})}))}),[4,Promise.all(i)];case 1:return a.sent(),this.syncEngineListener.onWatchChange(n),this.localStore.notifyLocalViewChanges(r),this.isPrimary?[4,this.localStore.collectGarbage().catch(function(e){return o.ignoreIfPrimaryLeaseLoss(e)})]:[3,3];case 2:a.sent(),a.label=3;case 3:return[2]}})})},e.prototype.ignoreIfPrimaryLeaseLoss=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){if(!isPrimaryLeaseLostError(e))throw e;return debug(LOG_TAG$9,"Unexpectedly lost primary lease"),[2]})})},e.prototype.assertSubscribed=function(e){assert$1(null!==this.syncEngineListener,"Trying to call "+e+" before calling subscribe().")},e.prototype.handleCredentialChange=function(e){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(r){switch(r.label){case 0:return t=!this.currentUser.isEqual(e),this.currentUser=e,t?[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 __awaiter(this,void 0,void 0,function(){var t,n,r,i,o,a,s,u=this;return __generator(this,function(c){switch(c.label){case 0:return!0!==e||!0===this.isPrimary?[3,3]:(this.isPrimary=!0,[4,this.remoteStore.applyPrimaryState(!0)]);case 1:return c.sent(),t=this.sharedClientState.getAllActiveQueryTargets(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(t.toArray())];case 2:for(n=c.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,a=[],s=Promise.resolve(),forEachNumber(this.queryViewsByTarget,function(e,t){u.sharedClientState.isLocalQueryTarget(e)?a.push(e):s=s.then(function(){return u.unlisten(t.query)}),u.remoteStore.unlisten(t.targetId)}),[4,s]);case 4:return c.sent(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(a)];case 5:return c.sent(),this.resetLimboDocuments(),[4,this.remoteStore.applyPrimaryState(!1)];case 6:c.sent(),c.label=7;case 7:return[2]}})})},e.prototype.resetLimboDocuments=function(){var e=this;forEachNumber(this.limboResolutionsByTarget,function(t){e.remoteStore.unlisten(t)}),this.limboResolutionsByTarget=[],this.limboTargetsByKey=new SortedMap$1(DocumentKey.comparator)},e.prototype.synchronizeQueryViewsAndRaiseSnapshots=function(e){for(var t=this,n=Promise.resolve(),r=[],i=[],o=function(e){n=n.then(function(){return __awaiter(t,void 0,void 0,function(){var t,n,o,a;return __generator(this,function(s){switch(s.label){case 0:return(n=this.queryViewsByTarget[e])?[4,this.localStore.releaseQuery(n.query,!0)]:[3,4];case 1:return s.sent(),[4,this.localStore.allocateQuery(n.query)];case 2:return t=s.sent(),[4,this.synchronizeViewAndComputeSnapshot(n)];case 3:return(o=s.sent()).snapshot&&i.push(o.snapshot),[3,8];case 4:return assert$1(!0===this.isPrimary,"A secondary tab should never have an active query without an active view."),[4,this.localStore.getQueryForTarget(e)];case 5:return assert$1(!!(a=s.sent()),"Query data for target "+e+" not found"),[4,this.localStore.allocateQuery(a)];case 6:return t=s.sent(),[4,this.initializeViewAndComputeSnapshot(t,!1)];case 7:s.sent(),s.label=8;case 8:return r.push(t),[2]}})})})},a=0,s=e;a<s.length;a++){o(s[a])}return n.then(function(){return t.syncEngineListener.onWatchChange(i),r})},e.prototype.getActiveClients=function(){return this.localStore.getActiveClients()},e.prototype.applyTargetState=function(e,t,n){return __awaiter(this,void 0,void 0,function(){var r,i,o;return __generator(this,function(a){switch(a.label){case 0:if(this.isPrimary)return debug(LOG_TAG$9,"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,3]}return[3,6];case 1:return[4,this.localStore.getNewDocumentChanges()];case 2:return r=a.sent(),i=RemoteEvent.createSynthesizedRemoteEventForCurrentChange(e,"current"===t),[2,this.emitNewSnapsAndNotifyLocalStore(r,i)];case 3:return o=this.queryViewsByTarget[e],[4,this.removeAndCleanupQuery(o)];case 4:return a.sent(),[4,this.localStore.releaseQuery(o.query,!0)];case 5:return a.sent(),this.syncEngineListener.onWatchError(o.query,n),[3,7];case 6:fail("Unexpected target state: "+t),a.label=7;case 7:return[2]}})})},e.prototype.applyActiveTargetsChange=function(e,t){return __awaiter(this,void 0,void 0,function(){var n,r,i,o,a,s,u,c,h,l=this;return __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?(h=r[n],assert$1(!this.queryViewsByTarget[h],"Trying to add an already active target"),[4,this.localStore.getQueryForTarget(h)]):[3,6];case 2:return assert$1(!!(i=d.sent()),"Query data for active target "+h+" 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:a=function(e){var t;return __generator(this,function(n){switch(n.label){case 0:return(t=s.queryViewsByTarget[e])?[4,s.localStore.releaseQuery(t.query,!1).then(function(){return l.remoteStore.unlisten(e),l.removeAndCleanupQuery(t)}).catch(function(e){return l.ignoreIfPrimaryLeaseLoss(e)})]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})},s=this,u=0,c=t,d.label=7;case 7:return u<c.length?(h=c[u],[5,a(h)]):[3,10];case 8:d.sent(),d.label=9;case 9:return u++,[3,7];case 10:return[2]}})})},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?documentKeySet().add(t.key):this.queryViewsByTarget[e]?this.queryViewsByTarget[e].view.syncedDocuments:documentKeySet()},e}(),User=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}(),LOG_TAG$10="SharedClientState",CLIENT_STATE_KEY_PREFIX="firestore_clients",MUTATION_BATCH_KEY_PREFIX="firestore_mutations",QUERY_TARGET_KEY_PREFIX="firestore_targets",ONLINE_STATE_KEY_PREFIX="firestore_online_state",SEQUENCE_NUMBER_KEY_PREFIX="firestore_sequence_number",MutationMetadata=function(){function e(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r,assert$1(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 FirestoreError(i.error.code,i.error.message)),o?new e(t,n,i.state,a):(error$2(LOG_TAG$10,"Failed to parse mutation state for ID '"+n+"': "+r),null)},e.prototype.toWebStorageJSON=function(){var e={state:this.state};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)},e}(),QueryTargetMetadata=function(){function e(e,t,n){this.targetId=e,this.state=t,this.error=n,assert$1(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 FirestoreError(r.error.code,r.error.message)),i?new e(t,r.state,o):(error$2(LOG_TAG$10,"Failed to parse target state for ID '"+t+"': "+n),null)},e.prototype.toWebStorageJSON=function(){var e={state:this.state};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)},e}(),RemoteClientState=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=targetIdSet(),a=0;i&&a<r.activeTargetIds.length;++a)i=isSafeInteger(r.activeTargetIds[a]),o=o.add(r.activeTargetIds[a]);return i?new e(t,o):(error$2(LOG_TAG$10,"Failed to parse client data for instance '"+t+"': "+n),null)},e}(),SharedOnlineState=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&&void 0!==OnlineState[n.onlineState]&&"string"==typeof n.clientId?new e(n.clientId,OnlineState[n.onlineState]):(error$2(LOG_TAG$10,"Failed to parse online state: "+t),null)},e}(),LocalClientState=function(){function e(){this.activeTargetIds=targetIdSet()}return e.prototype.addQueryTarget=function(e){assert$1(!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()};return JSON.stringify(e)},e}(),WebStorageSharedClientState=function(){function e(t,n,r,i,o){if(this.queue=t,this.platform=n,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 FirestoreError(Code.UNIMPLEMENTED,"LocalStorage is not available on this platform.");this.escapedPersistenceKey=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),this.storage=this.platform.window.localStorage,this.currentUser=o,this.localClientStorageKey=this.toWebStorageClientStateKey(this.localClientId),this.sequenceNumberKey=SEQUENCE_NUMBER_KEY_PREFIX+"_"+this.escapedPersistenceKey,this.activeClients[this.localClientId]=new LocalClientState,this.clientStateKeyRe=new RegExp("^"+CLIENT_STATE_KEY_PREFIX+"_"+this.escapedPersistenceKey+"_([^_]*)$"),this.mutationBatchKeyRe=new RegExp("^"+MUTATION_BATCH_KEY_PREFIX+"_"+this.escapedPersistenceKey+"_(\\d+)(?:_(.*))?$"),this.queryTargetKeyRe=new RegExp("^"+QUERY_TARGET_KEY_PREFIX+"_"+this.escapedPersistenceKey+"_(\\d+)$"),this.onlineStateKey=ONLINE_STATE_KEY_PREFIX+"_"+this.escapedPersistenceKey,this.platform.window.addEventListener("storage",this.storageListener)}return e.isAvailable=function(e){return!(!e.window||null==e.window.localStorage)},e.prototype.start=function(){return __awaiter(this,void 0,void 0,function(){var e,t,n,r,i,o,a,s,u,c,h,l=this;return __generator(this,function(d){switch(d.label){case 0:return assert$1(!this.started,"WebStorageSharedClientState already started"),assert$1(null!==this.syncEngine,"syncEngine property must be set before calling start()"),assert$1(null!==this.onlineStateHandler,"onlineStateHandler property must be set before calling start()"),[4,this.syncEngine.getActiveClients()];case 1:for(e=d.sent(),t=0,n=e;t<n.length;t++)(r=n[t])!==this.localClientId&&(i=this.getItem(this.toWebStorageClientStateKey(r)))&&(o=RemoteClientState.fromWebStorageEntry(r,i))&&(this.activeClients[o.clientId]=o);for(this.persistClientState(),(a=this.storage.getItem(this.onlineStateKey))&&(s=this.fromWebStorageOnlineState(a))&&this.handleOnlineStateEvent(s),u=0,c=this.earlyEvents;u<c.length;u++)h=c[u],this.handleWebStorageEvent(h);return this.earlyEvents=[],this.platform.window.addEventListener("unload",function(){return l.shutdown()}),this.started=!0,[2]}})})},e.prototype.writeSequenceNumber=function(e){this.setItem(this.sequenceNumberKey,JSON.stringify(e))},e.prototype.getAllActiveQueryTargets=function(){var e=targetIdSet();return forEach$1(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=QueryTargetMetadata.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 debug(LOG_TAG$10,"READ",e,t),t},e.prototype.setItem=function(e,t){debug(LOG_TAG$10,"SET",e,t),this.storage.setItem(e,t)},e.prototype.removeItem=function(e){debug(LOG_TAG$10,"REMOVE",e),this.storage.removeItem(e)},e.prototype.handleWebStorageEvent=function(e){var t=this;if(e.storageArea===this.storage){if(debug(LOG_TAG$10,"EVENT",e.key,e.newValue),e.key===this.localClientStorageKey)return void error$2("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.queue.enqueueAndForget(function(){return __awaiter(t,void 0,void 0,function(){var t,n,r,i,o,a;return __generator(this,function(s){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.key),[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&&(assert$1(!!this.sequenceNumberHandler,"Missing sequenceNumberHandler"),(a=fromWebStorageSequenceNumber(e.newValue))!==ListenSequence.INVALID&&this.sequenceNumberHandler(a));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 MutationMetadata(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:OnlineState[e]};this.storage.setItem(this.onlineStateKey,JSON.stringify(t))},e.prototype.persistQueryTargetState=function(e,t,n){var r=this.toWebStorageQueryTargetMetadataKey(e),i=new QueryTargetMetadata(e,t,n);this.setItem(r,i.toWebStorageJSON())},e.prototype.toWebStorageClientStateKey=function(e){return assert$1(-1===e.indexOf("_"),"Client key cannot contain '_', but was '"+e+"'"),CLIENT_STATE_KEY_PREFIX+"_"+this.escapedPersistenceKey+"_"+e},e.prototype.toWebStorageQueryTargetMetadataKey=function(e){return QUERY_TARGET_KEY_PREFIX+"_"+this.escapedPersistenceKey+"_"+e},e.prototype.toWebStorageMutationBatchKey=function(e){var t=MUTATION_BATCH_KEY_PREFIX+"_"+this.escapedPersistenceKey+"_"+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 assert$1(null!==n,"Cannot parse client state key '"+e+"'"),RemoteClientState.fromWebStorageEntry(n,t)},e.prototype.fromWebStorageMutationMetadata=function(e,t){var n=this.mutationBatchKeyRe.exec(e);assert$1(null!==n,"Cannot parse mutation batch key '"+e+"'");var r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return MutationMetadata.fromWebStorageEntry(new User(i),r,t)},e.prototype.fromWebStorageQueryTargetMetadata=function(e,t){var n=this.queryTargetKeyRe.exec(e);assert$1(null!==n,"Cannot parse query target key '"+e+"'");var r=Number(n[1]);return QueryTargetMetadata.fromWebStorageEntry(r,t)},e.prototype.fromWebStorageOnlineState=function(e){return SharedOnlineState.fromWebStorageEntry(e)},e.prototype.handleMutationBatchEvent=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return e.user.uid!==this.currentUser.uid?(debug(LOG_TAG$10,"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=[],a=[];return i.forEach(function(e){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(t){return r.has(e)||o.push(e),[2]})})}),r.forEach(function(e){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(t){return i.has(e)||a.push(e),[2]})})}),this.syncEngine.applyActiveTargetsChange(o,a)},e.prototype.handleOnlineStateEvent=function(e){this.activeClients[e.clientId]&&this.onlineStateHandler(e.onlineState)},e}();function fromWebStorageSequenceNumber(e){var t=ListenSequence.INVALID;if(null!=e)try{var n=JSON.parse(e);assert$1("number"==typeof n,"Found non-numeric sequence number"),t=n}catch(e){error$2(LOG_TAG$10,"Failed to read sequence number from WebStorage",e)}return t}var MemorySharedClientState=function(){function e(){this.localState=new LocalClientState,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 LocalClientState,Promise.resolve()},e.prototype.handleUserChange=function(e,t,n){},e.prototype.setOnlineState=function(e){},e.prototype.shutdown=function(){},e.prototype.writeSequenceNumber=function(e){},e}(),LOG_TAG$11="FirestoreClient",DOM_EXCEPTION_ABORTED=20,DOM_EXCEPTION_QUOTA_EXCEEDED=22,FirestoreClient=function(){function e(e,t,n,r){this.platform=e,this.databaseInfo=t,this.credentials=n,this.asyncQueue=r,this.clientId=AutoId.newId()}return e.prototype.start=function(e){var t=this,n=new Deferred$1,r=new Deferred$1,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(){return t.initializeRest(o)}).then(n.resolve,n.reject))}),this.asyncQueue.enqueueAndForget(function(){return n.promise}),r.promise},e.prototype.enableNetwork=function(){var e=this;return this.asyncQueue.enqueue(function(){return e.syncEngine.enableNetwork()})},e.prototype.initializePersistence=function(e,t,n){var r=this;return e.enabled?this.startIndexedDbPersistence(n,e).then(t.resolve).catch(function(e){return t.reject(e),r.canFallback(e)?(console.warn("Error enabling offline storage. Falling back to storage disabled: "+e),r.startMemoryPersistence()):Promise.reject(e)}):(t.resolve(),this.startMemoryPersistence())},e.prototype.canFallback=function(e){return e instanceof FirestoreError?e.code===Code.FAILED_PRECONDITION||e.code===Code.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||(e.code===DOM_EXCEPTION_QUOTA_EXCEEDED||e.code===DOM_EXCEPTION_ABORTED)},e.prototype.startIndexedDbPersistence=function(e,t){var n=this;assert$1(t.enabled,"Should only start IndexedDb persitence with offline persistence enabled."),this.garbageCollector=new NoOpGarbageCollector;var r=IndexedDbPersistence.buildStoragePrefix(this.databaseInfo),i=new JsonProtoSerializer(this.databaseInfo.databaseId,{useProto3Json:!0});return Promise.resolve().then(function(){return __awaiter(n,void 0,void 0,function(){var n,o;return __generator(this,function(a){switch(a.label){case 0:if(t.experimentalTabSynchronization&&!WebStorageSharedClientState.isAvailable(this.platform))throw new FirestoreError(Code.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");return t.experimentalTabSynchronization?(this.sharedClientState=new WebStorageSharedClientState(this.asyncQueue,this.platform,r,this.clientId,e),n=this,[4,IndexedDbPersistence.createMultiClientIndexedDbPersistence(r,this.clientId,this.platform,this.asyncQueue,i,{sequenceNumberSyncer:this.sharedClientState})]):[3,2];case 1:return n.persistence=a.sent(),[3,4];case 2:return this.sharedClientState=new MemorySharedClientState,o=this,[4,IndexedDbPersistence.createIndexedDbPersistence(r,this.clientId,this.platform,this.asyncQueue,i)];case 3:o.persistence=a.sent(),a.label=4;case 4:return[2]}})})})},e.prototype.startMemoryPersistence=function(){return this.garbageCollector=new EagerGarbageCollector,this.persistence=new MemoryPersistence(this.clientId),this.sharedClientState=new MemorySharedClientState,Promise.resolve()},e.prototype.initializeRest=function(e){var t=this;return debug(LOG_TAG$11,"Initializing. user=",e.uid),this.platform.loadConnection(this.databaseInfo).then(function(n){return __awaiter(t,void 0,void 0,function(){var t,r,i,o,a=this;return __generator(this,function(s){switch(s.label){case 0:return this.localStore=new LocalStore(this.persistence,e,this.garbageCollector),t=this.platform.newSerializer(this.databaseInfo.databaseId),r=new Datastore(this.asyncQueue,n,this.credentials,t),i=function(e){return a.syncEngine.applyOnlineStateChange(e,OnlineStateSource.RemoteStore)},o=function(e){return a.syncEngine.applyOnlineStateChange(e,OnlineStateSource.SharedClientState)},this.remoteStore=new RemoteStore(this.localStore,r,this.asyncQueue,i),this.syncEngine=new SyncEngine(this.localStore,this.remoteStore,this.sharedClientState,e),this.sharedClientState.onlineStateHandler=o,this.remoteStore.syncEngine=this.syncEngine,this.sharedClientState.syncEngine=this.syncEngine,this.eventMgr=new EventManager(this.syncEngine),[4,this.localStore.start()];case 1:return s.sent(),[4,this.sharedClientState.start()];case 2:return s.sent(),[4,this.remoteStore.start()];case 3:return s.sent(),[4,this.persistence.setPrimaryStateListener(function(e){return a.syncEngine.applyPrimaryState(e)})];case 4:return s.sent(),[2]}})})})},e.prototype.handleCredentialChange=function(e){return this.asyncQueue.verifyOperationInProgress(),debug(LOG_TAG$11,"Credential Changed. Current user: "+e.uid),this.syncEngine.handleCredentialChange(e)},e.prototype.disableNetwork=function(){var e=this;return this.asyncQueue.enqueue(function(){return e.syncEngine.disableNetwork()})},e.prototype.shutdown=function(e){var t=this;return this.asyncQueue.enqueue(function(){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,this.remoteStore.shutdown()];case 1:return t.sent(),[4,this.sharedClientState.shutdown()];case 2:return t.sent(),[4,this.persistence.shutdown(e&&e.purgePersistenceWithDataLoss)];case 3:return t.sent(),this.credentials.removeChangeListener(),[2]}})})})},e.prototype.listen=function(e,t,n){var r=this,i=new QueryListener(e,t,n);return this.asyncQueue.enqueueAndForget(function(){return r.eventMgr.listen(i)}),i},e.prototype.unlisten=function(e){var t=this;this.asyncQueue.enqueueAndForget(function(){return t.eventMgr.unlisten(e)})},e.prototype.getDocumentFromLocalCache=function(e){var t=this;return this.asyncQueue.enqueue(function(){return t.localStore.readDocument(e)}).then(function(e){if(e instanceof Document)return e;if(e instanceof NoDocument)return null;throw new FirestoreError(Code.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.asyncQueue.enqueue(function(){return t.localStore.executeQuery(e)}).then(function(t){var n=documentKeySet(),r=new View$1(e,n),i=r.computeDocChanges(t);return r.applyChanges(i,!1).snapshot})},e.prototype.write=function(e){var t=this,n=new Deferred$1;return this.asyncQueue.enqueueAndForget(function(){return t.syncEngine.write(e,n)}),n.promise},e.prototype.databaseId=function(){return this.databaseInfo.databaseId},e.prototype.transaction=function(e){var t=this;return this.asyncQueue.enqueue(function(){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){return[2]})})}).then(function(){return t.syncEngine.runTransaction(e)})},e}(),AsyncObserver=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}(),FieldPath$1=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];validateNamedArrayAtLeastNumberOfElements("FieldPath",e,"fieldNames",1);for(var n=0;n<e.length;++n)if(validateArgType("FieldPath","string",n,e[n]),0===e[n].length)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new FieldPath(e)}return e.documentId=function(){return e._DOCUMENT_ID},e.prototype.isEqual=function(t){if(!(t instanceof e))throw invalidClassError("isEqual","FieldPath",1,t);return this._internalPath.isEqual(t._internalPath)},e._DOCUMENT_ID=new e(FieldPath.keyField().canonicalString()),e}(),RESERVED=new RegExp("[~\\*/\\[\\]]");function fromDotSeparatedString(e){if(e.search(RESERVED)>=0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid field path ("+e+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(FieldPath$1.bind.apply(FieldPath$1,[void 0].concat(e.split("."))))}catch(t){throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid field path ("+e+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}var OAuthToken=function(){return function(e,t){this.user=t,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+e}}}(),EmptyCredentialsProvider=function(){function e(){this.changeListener=null}return e.prototype.getToken=function(){return Promise.resolve(null)},e.prototype.invalidateToken=function(){},e.prototype.setChangeListener=function(e){assert$1(!this.changeListener,"Can only call setChangeListener() once."),this.changeListener=e,e(User.UNAUTHENTICATED)},e.prototype.removeChangeListener=function(){assert$1(null!==this.changeListener,"removeChangeListener() when no listener registered"),this.changeListener=null},e}(),FirebaseCredentialsProvider=function(){function e(e){var t=this;this.app=e,this.tokenListener=null,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.tokenCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return e.prototype.getToken=function(){var e=this;assert$1(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 FirestoreError(Code.ABORTED,"getToken aborted due to token change.");return n?(assert$1("string"==typeof n.accessToken,"Invalid tokenData returned from getToken():"+n),new OAuthToken(n.accessToken,e.currentUser)):null})},e.prototype.invalidateToken=function(){this.forceRefresh=!0},e.prototype.setChangeListener=function(e){assert$1(!this.changeListener,"Can only call setChangeListener() once."),this.changeListener=e,this.currentUser&&e(this.currentUser)},e.prototype.removeChangeListener=function(){assert$1(null!=this.tokenListener,"removeChangeListener() called twice"),assert$1(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 assert$1(null===e||"string"==typeof e,"Received invalid UID: "+e),new User(e)},e}(),FirstPartyToken=function(){function e(e,t){this.gapi=e,this.sessionIndex=t,this.type="FirstParty",this.user=User.FIRST_PARTY,assert$1(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return Object.defineProperty(e.prototype,"authHeaders",{get:function(){return{Authorization:this.gapi.auth.getAuthHeaderValueForFirstParty([]),"X-Goog-AuthUser":this.sessionIndex}},enumerable:!0,configurable:!0}),e}(),FirstPartyCredentialsProvider=function(){function e(e,t){this.gapi=e,this.sessionIndex=t,assert$1(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return e.prototype.getToken=function(){return Promise.resolve(new FirstPartyToken(this.gapi,this.sessionIndex))},e.prototype.setChangeListener=function(e){e(User.FIRST_PARTY)},e.prototype.removeChangeListener=function(){},e.prototype.invalidateToken=function(){},e}();function makeCredentialsProvider(e){if(!e)return new EmptyCredentialsProvider;switch(e.type){case"gapi":return new FirstPartyCredentialsProvider(e.client,e.sessionIndex||"0");case"provider":return e.client;default:throw new FirestoreError(Code.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}function isPartialObserver(e){return implementsAnyMethods$1(e,["next","error","complete"])}function implementsAnyMethods$1(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}var FieldValueImpl=function(){function e(e){this._methodName=e}return e.delete=function(){return DeleteFieldValueImpl.instance},e.serverTimestamp=function(){return ServerTimestampFieldValueImpl.instance},e.arrayUnion=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return validateAtLeastNumberOfArgs("FieldValue.arrayUnion",arguments,1),new ArrayUnionFieldValueImpl(e)},e.arrayRemove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return validateAtLeastNumberOfArgs("FieldValue.arrayRemove",arguments,1),new ArrayRemoveFieldValueImpl(e)},e.prototype.isEqual=function(e){return this===e},e}(),DeleteFieldValueImpl=function(e){function t(){return e.call(this,"FieldValue.delete")||this}return __extends(t,e),t.instance=new t,t}(FieldValueImpl),ServerTimestampFieldValueImpl=function(e){function t(){return e.call(this,"FieldValue.serverTimestamp")||this}return __extends(t,e),t.instance=new t,t}(FieldValueImpl),ArrayUnionFieldValueImpl=function(e){function t(t){var n=e.call(this,"FieldValue.arrayUnion")||this;return n._elements=t,n}return __extends(t,e),t}(FieldValueImpl),ArrayRemoveFieldValueImpl=function(e){function t(t){var n=e.call(this,"FieldValue.arrayRemove")||this;return n._elements=t,n}return __extends(t,e),t}(FieldValueImpl),PublicFieldValue=makeConstructorPrivate(FieldValueImpl,"Use FieldValue.<field>() instead."),RESERVED_FIELD_REGEX=/^__.*__$/,ParsedSetData=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 PatchMutation(e,this.data,this.fieldMask,t)):n.push(new SetMutation(e,this.data,t)),this.fieldTransforms.length>0&&n.push(new TransformMutation(e,this.fieldTransforms)),n},e}(),ParsedUpdateData=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 PatchMutation(e,this.data,this.fieldMask,t)];return this.fieldTransforms.length>0&&n.push(new TransformMutation(e,this.fieldTransforms)),n},e}(),UserDataSource;function isWrite(e){switch(e){case UserDataSource.Set:case UserDataSource.MergeSet:case UserDataSource.Update:return!0;case UserDataSource.Argument:return!1;default:throw fail("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"}(UserDataSource||(UserDataSource={}));var ParseContext=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 FirestoreError(Code.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(isWrite(this.dataSource)&&RESERVED_FIELD_REGEX.test(e))throw this.createError("Document fields cannot begin and end with __")},e}(),DocumentKeyReference=function(){return function(e,t){this.databaseId=e,this.key=t}}(),UserDataConverter=function(){function e(e){this.preConverter=e}return e.prototype.parseSetData=function(e,t){var n=new ParseContext(UserDataSource.Set,e,FieldPath.EMPTY_PATH);validatePlainObject("Data must be an object, but it was:",n,t);var r=this.parseData(t,n);return new ParsedSetData(r,null,n.fieldTransforms)},e.prototype.parseMergeData=function(e,t,n){var r=new ParseContext(UserDataSource.MergeSet,e,FieldPath.EMPTY_PATH);validatePlainObject("Data must be an object, but it was:",r,t);var i,o,a=this.parseData(t,r);if(n){for(var s=[],u=0,c=n;u<c.length;u++){var h=c[u],l=void 0;if(h instanceof FieldPath$1)l=h._internalPath;else{if("string"!=typeof h)throw fail("Expected stringOrFieldPath to be a string or a FieldPath");l=fieldPathFromDotSeparatedString(e,h)}if(!r.contains(l))throw new FirestoreError(Code.INVALID_ARGUMENT,"Field '"+l+"' is specified in your field mask but missing from your input data.");s.push(l)}i=new FieldMask(s),o=r.fieldTransforms.filter(function(e){return i.covers(e.field)})}else i=new FieldMask(r.fieldMask),o=r.fieldTransforms;return new ParsedSetData(a,i,o)},e.prototype.parseUpdateData=function(e,t){var n=this,r=new ParseContext(UserDataSource.Update,e,FieldPath.EMPTY_PATH);validatePlainObject("Data must be an object, but it was:",r,t);var i=[],o=ObjectValue.EMPTY;forEach$1(t,function(t,a){var s=fieldPathFromDotSeparatedString(e,t),u=r.childContextForFieldPath(s);if((a=n.runPreConverter(a,u))instanceof DeleteFieldValueImpl)i.push(s);else{var c=n.parseData(a,u);null!=c&&(i.push(s),o=o.set(s,c))}});var a=new FieldMask(i);return new ParsedUpdateData(o,a,r.fieldTransforms)},e.prototype.parseUpdateVarargs=function(e,t,n,r){var i=new ParseContext(UserDataSource.Update,e,FieldPath.EMPTY_PATH),o=[fieldPathFromArgument(e,t)],a=[n];if(r.length%2!=0)throw new FirestoreError(Code.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(fieldPathFromArgument(e,r[s])),a.push(r[s+1]);var u=[],c=ObjectValue.EMPTY;for(s=0;s<o.length;++s){var h=o[s],l=i.childContextForFieldPath(h),d=this.runPreConverter(a[s],l);if(d instanceof DeleteFieldValueImpl)u.push(h);else{var f=this.parseData(d,l);null!=f&&(u.push(h),c=c.set(h,f))}}var p=new FieldMask(u);return new ParsedUpdateData(c,p,i.fieldTransforms)},e.prototype.parseQueryValue=function(e,t){var n=new ParseContext(UserDataSource.Argument,e,FieldPath.EMPTY_PATH),r=this.parseData(t,n);return assert$1(null!=r,"Parsed data should not be null."),assert$1(0===n.fieldTransforms.length,"Field transforms should have been disallowed."),r},e.prototype.runPreConverter=function(e,t){try{return this.preConverter(e)}catch(e){var n=errorMessage(e);throw t.createError(n)}},e.prototype.parseData=function(e,t){if(looksLikeJsonObject(e=this.runPreConverter(e,t)))return validatePlainObject("Unsupported field value:",t,e),this.parseObject(e,t);if(e instanceof FieldValueImpl)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 SortedMap$1(primitiveComparator);return isEmpty$1(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):forEach$1(e,function(e,i){var o=n.parseData(i,t.childContextForField(e));null!=o&&(r=r.insert(e,o))}),new ObjectValue(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=NullValue.INSTANCE),n.push(s),r++}return new ArrayValue(n)},e.prototype.parseSentinelFieldValue=function(e,t){if(!isWrite(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 DeleteFieldValueImpl){if(t.dataSource!==UserDataSource.MergeSet)throw t.dataSource===UserDataSource.Update?(assert$1(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 ServerTimestampFieldValueImpl)t.fieldTransforms.push(new FieldTransform(t.path,ServerTimestampTransform.instance));else if(e instanceof ArrayUnionFieldValueImpl){var n=this.parseArrayTransformElements(e._methodName,e._elements),r=new ArrayUnionTransformOperation(n);t.fieldTransforms.push(new FieldTransform(t.path,r))}else if(e instanceof ArrayRemoveFieldValueImpl){n=this.parseArrayTransformElements(e._methodName,e._elements);var i=new ArrayRemoveTransformOperation(n);t.fieldTransforms.push(new FieldTransform(t.path,i))}else fail("Unknown FieldValue type: "+e)},e.prototype.parseScalarValue=function(e,t){if(null===e)return NullValue.INSTANCE;if("number"==typeof e)return isSafeInteger(e)?new IntegerValue(e):new DoubleValue(e);if("boolean"==typeof e)return BooleanValue.of(e);if("string"==typeof e)return new StringValue(e);if(e instanceof Date)return new TimestampValue(Timestamp.fromDate(e));if(e instanceof Timestamp)return new TimestampValue(new Timestamp(e.seconds,1e3*Math.floor(e.nanoseconds/1e3)));if(e instanceof GeoPoint)return new GeoPointValue(e);if(e instanceof Blob$1)return new BlobValue(e);if(e instanceof DocumentKeyReference)return new RefValue(e.databaseId,e.key);throw t.createError("Unsupported field value: "+valueDescription(e))},e.prototype.parseArrayTransformElements=function(e,t){var n=this;return t.map(function(t,r){var i=new ParseContext(UserDataSource.Argument,e,FieldPath.EMPTY_PATH);return n.parseData(t,i.childContextForArray(r))})},e}();function looksLikeJsonObject(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Timestamp||e instanceof GeoPoint||e instanceof Blob$1||e instanceof DocumentKeyReference||e instanceof FieldValueImpl)}function validatePlainObject(e,t,n){if(!looksLikeJsonObject(n)||!isPlainObject(n)){var r=valueDescription(n);throw"an object"===r?t.createError(e+" a custom object"):t.createError(e+" "+r)}}function fieldPathFromArgument(e,t){if(t instanceof FieldPath$1)return t._internalPath;if("string"==typeof t)return fieldPathFromDotSeparatedString(e,t);throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function fieldPathFromDotSeparatedString(e,t){try{return fromDotSeparatedString(t)._internalPath}catch(t){var n=errorMessage(t);throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+e+"() called with invalid data. "+n)}}function errorMessage(e){return e instanceof Error?e.message:e.toString()}var DEFAULT_HOST="firestore.googleapis.com",DEFAULT_SSL=!0,DEFAULT_TIMESTAMPS_IN_SNAPSHOTS=!1,DEFAULT_SYNCHRONIZE_TABS=!1,FirestoreSettings=function(){function e(e){if(void 0===e.host){if(void 0!==e.ssl)throw new FirestoreError(Code.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=DEFAULT_HOST,this.ssl=DEFAULT_SSL}else validateNamedType("settings","non-empty string","host",e.host),this.host=e.host,validateNamedOptionalType("settings","boolean","ssl",e.ssl),this.ssl=defaulted(e.ssl,DEFAULT_SSL);validateOptionNames("settings",e,["host","ssl","credentials","timestampsInSnapshots"]),validateNamedOptionalType("settings","object","credentials",e.credentials),this.credentials=e.credentials,validateNamedOptionalType("settings","boolean","timestampsInSnapshots",e.timestampsInSnapshots),this.timestampsInSnapshots=defaulted(e.timestampsInSnapshots,DEFAULT_TIMESTAMPS_IN_SNAPSHOTS)}return e.prototype.isEqual=function(e){return this.host===e.host&&this.ssl===e.ssl&&this.timestampsInSnapshots===e.timestampsInSnapshots&&this.credentials===e.credentials},e}(),FirestoreConfig=function(){return function(){}}(),PersistenceSettings=function(){function e(e,t){this.enabled=e,assert$1(e||!t,"Can only provide PersistenceSettings with persistence enabled"),t=t||{},this.experimentalTabSynchronization=defaulted(t.experimentalTabSynchronization,DEFAULT_SYNCHRONIZE_TABS)}return e.prototype.isEqual=function(e){return this.enabled===e.enabled&&this.experimentalTabSynchronization===e.experimentalTabSynchronization},e}(),Firestore=function(){function e(t){var n=this;this._queue=new AsyncQueue,this.INTERNAL={delete:function(e){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(t){return this._firestoreClient?[2,this._firestoreClient.shutdown(e)]:[2]})})}};var r=new FirestoreConfig;if("object"==typeof t.options){var i=t;r.firebaseApp=i,r.databaseId=e.databaseIdFromApp(i),r.persistenceKey=r.firebaseApp.name,r.credentials=new FirebaseCredentialsProvider(i)}else{var o=t;if(!o.projectId)throw new FirestoreError(Code.INVALID_ARGUMENT,"Must provide projectId");r.databaseId=new DatabaseId(o.projectId,o.database),r.persistenceKey="[DEFAULT]",r.credentials=new EmptyCredentialsProvider}r.settings=new FirestoreSettings({}),this._config=r,this._databaseId=r.databaseId}return e.prototype.settings=function(e){if(validateExactNumberOfArgs("Firestore.settings",arguments,1),validateArgType("Firestore.settings","object",1,e),contains$2(e,"persistence"))throw new FirestoreError(Code.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var t=new FirestoreSettings(e);if(this._firestoreClient&&!this._config.settings.isEqual(t))throw new FirestoreError(Code.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._config.settings=t,void 0!==t.credentials&&(this._config.credentials=makeCredentialsProvider(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 FirestoreError(Code.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");return this.configureClient(new PersistenceSettings(!0,e))},e.prototype.ensureClientConfigured=function(){return this._firestoreClient||this.configureClient(new PersistenceSettings(!1)),this._firestoreClient},e.prototype.configureClient=function(e){var t=this;assert$1(!!this._config.settings.host,"FirestoreSettings.host cannot be falsey"),this._config.settings.timestampsInSnapshots||error$2("\nThe behavior for Date objects stored in Firestore is going to change\nAND YOUR APP MAY BREAK.\nTo hide this warning and ensure your app does not break, you need to add the\nfollowing code to your app before calling any other Cloud Firestore methods:\n\n const firestore = firebase.firestore();\n const settings = {/* your settings... */ timestampsInSnapshots: true};\n firestore.settings(settings);\n\nWith this change, timestamps stored in Cloud Firestore will be read back as\nFirebase Timestamp objects instead of as system Date objects. So you will also\nneed to update code expecting a Date to instead expect a Timestamp. For example:\n\n // Old:\n const date = snapshot.get('created_at');\n // New:\n const timestamp = snapshot.get('created_at');\n const date = timestamp.toDate();\n\nPlease audit all existing usages of Date when you enable the new behavior. In a\nfuture release, the behavior will change to the new behavior, so if you do not\nfollow these steps, YOUR APP MAY BREAK."),assert$1(!this._firestoreClient,"configureClient() called multiple times");var n=new DatabaseInfo(this._config.databaseId,this._config.persistenceKey,this._config.settings.host,this._config.settings.ssl);return this._dataConverter=new UserDataConverter(function(e){if(e instanceof DocumentReference){var n=t._config.databaseId,r=e.firestore._config.databaseId;if(!r.isEqual(n))throw new FirestoreError(Code.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new DocumentKeyReference(t._config.databaseId,e._key)}return e}),this._firestoreClient=new FirestoreClient(PlatformSupport.getPlatform(),n,this._config.credentials,this._queue),this._firestoreClient.start(e)},e.databaseIdFromApp=function(e){var t=e.options;if(!contains$2(t,"projectId"))throw new FirestoreError(Code.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');var n=t.projectId;if(!n||"string"!=typeof n)throw new FirestoreError(Code.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new DatabaseId(n)},Object.defineProperty(e.prototype,"app",{get:function(){if(!this._config.firebaseApp)throw new FirestoreError(Code.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._config.firebaseApp},enumerable:!0,configurable:!0}),e.prototype.collection=function(e){if(validateExactNumberOfArgs("Firestore.collection",arguments,1),validateArgType("Firestore.collection","non-empty string",1,e),!e)throw new FirestoreError(Code.INVALID_ARGUMENT,"Must provide a non-empty collection path to collection()");return this.ensureClientConfigured(),new CollectionReference(ResourcePath.fromString(e),this)},e.prototype.doc=function(e){if(validateExactNumberOfArgs("Firestore.doc",arguments,1),validateArgType("Firestore.doc","non-empty string",1,e),!e)throw new FirestoreError(Code.INVALID_ARGUMENT,"Must provide a non-empty document path to doc()");return this.ensureClientConfigured(),DocumentReference.forPath(ResourcePath.fromString(e),this)},e.prototype.runTransaction=function(e){var t=this;return validateExactNumberOfArgs("Firestore.runTransaction",arguments,1),validateArgType("Firestore.runTransaction","function",1,e),this.ensureClientConfigured().transaction(function(n){return e(new Transaction$1(t,n))})},e.prototype.batch=function(){return this.ensureClientConfigured(),new WriteBatch(this)},Object.defineProperty(e,"logLevel",{get:function(){switch(getLogLevel()){case LogLevel$1.DEBUG:return"debug";case LogLevel$1.ERROR:return"error";case LogLevel$1.SILENT:return"silent";default:return fail("Unknown log level: "+getLogLevel())}},enumerable:!0,configurable:!0}),e.setLogLevel=function(e){switch(validateExactNumberOfArgs("Firestore.setLogLevel",arguments,1),validateArgType("Firestore.setLogLevel","non-empty string",1,e),e){case"debug":setLogLevel$1(LogLevel$1.DEBUG);break;case"error":setLogLevel$1(LogLevel$1.ERROR);break;case"silent":setLogLevel$1(LogLevel$1.SILENT);break;default:throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid log level: "+e)}},e.prototype._areTimestampsInSnapshotsEnabled=function(){return this._config.settings.timestampsInSnapshots},e}(),Transaction$1=function(){function e(e,t){this._firestore=e,this._transaction=t}return e.prototype.get=function(e){var t=this;validateExactNumberOfArgs("Transaction.get",arguments,1);var n=validateReference("Transaction.get",e,this._firestore);return this._transaction.lookup([n._key]).then(function(e){if(!e||1!==e.length)return fail("Mismatch in docs returned from document lookup.");var r=e[0];if(r instanceof NoDocument)return new DocumentSnapshot(t._firestore,n._key,null,!1,!1);if(r instanceof Document)return new DocumentSnapshot(t._firestore,n._key,r,!1,!1);throw fail("BatchGetDocumentsRequest returned unexpected document type: "+r.constructor.name)})},e.prototype.set=function(e,t,n){validateBetweenNumberOfArgs("Transaction.set",arguments,2,3);var r=validateReference("Transaction.set",e,this._firestore),i=(n=validateSetOptions("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 FieldPath$1?(validateAtLeastNumberOfArgs("Transaction.update",arguments,3),r=validateReference("Transaction.update",e,this._firestore),i=this._firestore._dataConverter.parseUpdateVarargs("Transaction.update",t,n,o)):(validateExactNumberOfArgs("Transaction.update",arguments,2),r=validateReference("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){validateExactNumberOfArgs("Transaction.delete",arguments,1);var t=validateReference("Transaction.delete",e,this._firestore);return this._transaction.delete(t._key),this},e}(),WriteBatch=function(){function e(e){this._firestore=e,this._mutations=[],this._committed=!1}return e.prototype.set=function(e,t,n){validateBetweenNumberOfArgs("WriteBatch.set",arguments,2,3),this.verifyNotCommitted();var r=validateReference("WriteBatch.set",e,this._firestore),i=(n=validateSetOptions("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,Precondition.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 FieldPath$1?(validateAtLeastNumberOfArgs("WriteBatch.update",arguments,3),r=validateReference("WriteBatch.update",e,this._firestore),i=this._firestore._dataConverter.parseUpdateVarargs("WriteBatch.update",t,n,o)):(validateExactNumberOfArgs("WriteBatch.update",arguments,2),r=validateReference("WriteBatch.update",e,this._firestore),i=this._firestore._dataConverter.parseUpdateData("WriteBatch.update",t)),this._mutations=this._mutations.concat(i.toMutations(r._key,Precondition.exists(!0))),this},e.prototype.delete=function(e){validateExactNumberOfArgs("WriteBatch.delete",arguments,1),this.verifyNotCommitted();var t=validateReference("WriteBatch.delete",e,this._firestore);return this._mutations=this._mutations.concat(new DeleteMutation(t._key,Precondition.NONE)),this},e.prototype.commit=function(){return __awaiter(this,void 0,void 0,function(){return __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 FirestoreError(Code.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},e}(),DocumentReference=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 FirestoreError(Code.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+t.canonicalString()+" has "+t.length);return new e(new DocumentKey(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 CollectionReference(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(validateExactNumberOfArgs("DocumentReference.collection",arguments,1),validateArgType("DocumentReference.collection","non-empty string",1,e),!e)throw new FirestoreError(Code.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var t=ResourcePath.fromString(e);return new CollectionReference(this._key.path.child(t),this.firestore)},e.prototype.isEqual=function(t){if(!(t instanceof e))throw invalidClassError("isEqual","DocumentReference",1,t);return this.firestore===t.firestore&&this._key.isEqual(t._key)},e.prototype.set=function(e,t){validateBetweenNumberOfArgs("DocumentReference.set",arguments,1,2);var n=(t=validateSetOptions("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,Precondition.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 FieldPath$1?(validateAtLeastNumberOfArgs("DocumentReference.update",arguments,2),n=this.firestore._dataConverter.parseUpdateVarargs("DocumentReference.update",e,t,r)):(validateExactNumberOfArgs("DocumentReference.update",arguments,1),n=this.firestore._dataConverter.parseUpdateData("DocumentReference.update",e)),this._firestoreClient.write(n.toMutations(this._key,Precondition.exists(!0)))},e.prototype.delete=function(){return validateExactNumberOfArgs("DocumentReference.delete",arguments,0),this._firestoreClient.write([new DeleteMutation(this._key,Precondition.NONE)])},e.prototype.onSnapshot=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];validateBetweenNumberOfArgs("DocumentReference.onSnapshot",arguments,1,4);var n,r={includeMetadataChanges:!1},i=0;"object"!=typeof e[i]||isPartialObserver(e[i])||(validateOptionNames("DocumentReference.onSnapshot",r=e[i],["includeMetadataChanges"]),validateNamedOptionalType("DocumentReference.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++);var o={includeMetadataChanges:r.includeMetadataChanges};return isPartialObserver(e[i])?n=e[i]:(validateArgType("DocumentReference.onSnapshot","function",i,e[i]),validateOptionalArgType("DocumentReference.onSnapshot","function",i+1,e[i+1]),validateOptionalArgType("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 AsyncObserver({next:function(e){if(t.next){assert$1(e.docs.size<=1,"Too many documents returned on a document query");var r=e.docs.get(n._key);t.next(new DocumentSnapshot(n.firestore,n._key,r,e.fromCache,e.hasPendingWrites))}},error:r}),o=this._firestoreClient.listen(Query$1.atPath(this._key.path),i,e);return function(){i.mute(),n._firestoreClient.unlisten(o)}},e.prototype.get=function(e){var t=this;return validateBetweenNumberOfArgs("DocumentReference.get",arguments,0,1),validateGetOptions("DocumentReference.get",e),new Promise(function(n,r){e&&"cache"===e.source?t.firestore.ensureClientConfigured().getDocumentFromLocalCache(t._key).then(function(e){n(new DocumentSnapshot(t.firestore,t._key,e,!0,e instanceof Document&&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 FirestoreError(Code.UNAVAILABLE,"Failed to get document because the client is offline.")):i.exists&&i.metadata.fromCache&&n&&"server"===n.source?t(new FirestoreError(Code.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}(),SnapshotMetadata=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}(),DocumentSnapshot=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 validateBetweenNumberOfArgs("DocumentSnapshot.data",arguments,0,1),e=validateSnapshotOptions("DocumentSnapshot.data",e),this._document?this.convertObject(this._document.data,FieldValueOptions.fromSnapshotOptions(e,this._firestore._areTimestampsInSnapshotsEnabled())):void 0},e.prototype.get=function(e,t){if(validateBetweenNumberOfArgs("DocumentSnapshot.get",arguments,1,2),t=validateSnapshotOptions("DocumentSnapshot.get",t),this._document){var n=this._document.data.field(fieldPathFromArgument("DocumentSnapshot.get",e));if(void 0!==n)return this.convertValue(n,FieldValueOptions.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 DocumentReference(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 SnapshotMetadata(this._hasPendingWrites,this._fromCache)},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){if(!(t instanceof e))throw invalidClassError("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 ObjectValue)return this.convertObject(e,t);if(e instanceof ArrayValue)return this.convertArray(e,t);if(e instanceof RefValue){var n=e.value(t),r=this._firestore.ensureClientConfigured().databaseId();return e.databaseId.isEqual(r)||error$2("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 DocumentReference(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}(),QueryDocumentSnapshot=function(e){function t(t,n,r,i,o){return e.call(this,t,n,r,i,o)||this}return __extends(t,e),t.prototype.data=function(t){var n=e.prototype.data.call(this,t);return assert$1("object"==typeof n,"Document in a QueryDocumentSnapshot should exist"),n},t}(DocumentSnapshot),Query$1$1=function(){function e(e,t){this._query=e,this.firestore=t}return e.prototype.where=function(t,n,r){var i;validateExactNumberOfArgs("Query.where",arguments,3),validateArgType("Query.where","non-empty string",2,n),validateDefined("Query.where",3,r);var o=fieldPathFromArgument("Query.where",t),a=RelationOp.fromString(n);if(o.isKeyField()){if(a===RelationOp.ARRAY_CONTAINS)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid Query. You can't perform array-contains queries on FieldPath.documentId() since document IDs are not arrays.");if("string"==typeof r){if(-1!==r.indexOf("/"))throw new FirestoreError(Code.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a valid document ID if the first parameter is FieldPath.documentId(), but it contains a slash.");if(""===r)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a valid document ID if the first parameter is FieldPath.documentId(), but it was an empty string.");var s=this._query.path.child(new ResourcePath([r]));assert$1(s.length%2==0,"Path should be a document key"),i=new RefValue(this.firestore._databaseId,new DocumentKey(s))}else{if(!(r instanceof DocumentReference))throw new FirestoreError(Code.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a string or a DocumentReference if the first parameter is FieldPath.documentId(), but it was: "+valueDescription(r)+".");var u=r;i=new RefValue(this.firestore._databaseId,u._key)}}else i=this.firestore._dataConverter.parseQueryValue("Query.where",r);var c=Filter.create(o,a,i);return this.validateNewFilter(c),new e(this._query.addFilter(c),this.firestore)},e.prototype.orderBy=function(t,n){var r;if(validateBetweenNumberOfArgs("Query.orderBy",arguments,1,2),validateOptionalArgType("Query.orderBy","non-empty string",2,n),void 0===n||"asc"===n)r=Direction.ASCENDING;else{if("desc"!==n)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function Query.orderBy() has unknown direction '"+n+"', expected 'asc' or 'desc'.");r=Direction.DESCENDING}if(null!==this._query.startAt)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");if(null!==this._query.endAt)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");var i=fieldPathFromArgument("Query.orderBy",t),o=new OrderBy(i,r);return this.validateNewOrderBy(o),new e(this._query.addOrderBy(o),this.firestore)},e.prototype.limit=function(t){if(validateExactNumberOfArgs("Query.limit",arguments,1),validateArgType("Query.limit","number",1,t),t<=0)throw new FirestoreError(Code.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];validateAtLeastNumberOfArgs("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];validateAtLeastNumberOfArgs("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];validateAtLeastNumberOfArgs("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];validateAtLeastNumberOfArgs("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 invalidClassError("isEqual","Query",1,t);return this.firestore===t.firestore&&this._query.isEqual(t._query)},e.prototype.boundFromDocOrFields=function(e,t,n,r){if(validateDefined(e,1,t),t instanceof DocumentSnapshot){if(n.length>0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Too many arguments provided to "+e+"().");var i=t;if(!i.exists)throw new FirestoreError(Code.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 RefValue(this.firestore._databaseId,t.key));else{var s=t.field(a.field);if(void 0===s){var u=a.field.canonicalString();throw new FirestoreError(Code.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 Bound(r,n)},e.prototype.boundFromFields=function(e,t,n){var r=this._query.explicitOrderBy;if(t.length>r.length)throw new FirestoreError(Code.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];if(r[o].field.isKeyField()){if("string"!=typeof a)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in "+e+"(), but got a "+typeof a);if(-1!==a.indexOf("/"))throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. Document ID '"+a+"' contains a slash in "+e+"()");var s=new DocumentKey(this._query.path.child(a));i.push(new RefValue(this.firestore._databaseId,s))}else{var u=this.firestore._dataConverter.parseQueryValue(e,a);i.push(u)}}return new Bound(i,n)},e.prototype.onSnapshot=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];validateBetweenNumberOfArgs("Query.onSnapshot",arguments,1,4);var n,r={},i=0;return"object"!=typeof e[i]||isPartialObserver(e[i])||(validateOptionNames("Query.onSnapshot",r=e[i],["includeMetadataChanges"]),validateNamedOptionalType("Query.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++),isPartialObserver(e[i])?n=e[i]:(validateArgType("Query.onSnapshot","function",i,e[i]),validateOptionalArgType("Query.onSnapshot","function",i+1,e[i+1]),validateOptionalArgType("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 AsyncObserver({next:function(e){t.next&&t.next(new QuerySnapshot(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 validateBetweenNumberOfArgs("Query.get",arguments,0,1),validateGetOptions("Query.get",e),new Promise(function(n,r){e&&"cache"===e.source?t.firestore.ensureClientConfigured().getDocumentsFromLocalCache(t._query).then(function(e){n(new QuerySnapshot(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 FirestoreError(Code.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.validateNewFilter=function(e){if(e instanceof RelationFilter)if(e.isInequality()){var t=this._query.getInequalityFilterField();if(null!==t&&!t.isEqual(e.field))throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+t.toString()+"' and '"+e.field.toString()+"'");var n=this._query.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(e.field,n)}else if(e.op===RelationOp.ARRAY_CONTAINS&&this._query.hasArrayContainsFilter())throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. Queries only support a single array-contains filter.")},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 FirestoreError(Code.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}(),QuerySnapshot=function(){function e(e,t,n){this._firestore=e,this._originalQuery=t,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new SnapshotMetadata(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;validateBetweenNumberOfArgs("QuerySnapshot.forEach",arguments,1,2),validateArgType("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 Query$1$1(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),e.prototype.docChanges=function(e){e&&(validateOptionNames("QuerySnapshot.docChanges",e,["includeMetadataChanges"]),validateNamedOptionalType("QuerySnapshot.docChanges","boolean","includeMetadataChanges",e.includeMetadataChanges));var t=!(!e||!e.includeMetadataChanges);if(t&&this._snapshot.excludesMetadataChanges)throw new FirestoreError(Code.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=changesFromSnapshot(this._firestore,t,this._snapshot),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges},e.prototype.isEqual=function(t){if(!(t instanceof e))throw invalidClassError("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 QueryDocumentSnapshot(this._firestore,e.key,e,this.metadata.fromCache,this._snapshot.mutatedKeys.has(e.key))},e}();function throwDocChangesMethodError(){throw new FirestoreError(Code.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}var docChangesPropertiesToOverride=["length","forEach","map"].concat("undefined"!=typeof Symbol?[Symbol.iterator]:[]);docChangesPropertiesToOverride.forEach(function(e){try{Object.defineProperty(QuerySnapshot.prototype.docChanges,e,{get:function(){return throwDocChangesMethodError()}})}catch(e){}});var CollectionReference=function(e){function t(t,n){var r=e.call(this,Query$1.atPath(t),n)||this;if(t.length%2!=1)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+t.canonicalString()+" has "+t.length);return r}return __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 DocumentReference(new DocumentKey(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(validateBetweenNumberOfArgs("CollectionReference.doc",arguments,0,1),0===arguments.length&&(e=AutoId.newId()),validateArgType("CollectionReference.doc","non-empty string",1,e),""===e)throw new FirestoreError(Code.INVALID_ARGUMENT,"Document path must be a non-empty string");var t=ResourcePath.fromString(e);return DocumentReference.forPath(this._query.path.child(t),this.firestore)},t.prototype.add=function(e){validateExactNumberOfArgs("CollectionReference.add",arguments,1),validateArgType("CollectionReference.add","object",1,e);var t=this.doc();return t.set(e).then(function(){return t})},t}(Query$1$1);function validateSetOptions(e,t){if(void 0===t)return{merge:!1};if(validateOptionNames(e,t,["merge","mergeFields"]),validateNamedOptionalType(e,"boolean","merge",t.merge),validateOptionalArrayElements(e,"mergeFields","a string or a FieldPath",t.mergeFields,function(e){return"string"==typeof e||e instanceof FieldPath$1}),void 0!==t.mergeFields&&void 0!==t.merge)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid options passed to function "+e+'(): You cannot specify both "merge" and "mergeFields".');return t}function validateSnapshotOptions(e,t){return void 0===t?{}:(validateOptionNames(e,t,["serverTimestamps"]),validateNamedOptionalPropertyEquals(e,"options","serverTimestamps",t.serverTimestamps,["estimate","previous","none"]),t)}function validateGetOptions(e,t){validateOptionalArgType(e,"object",1,t),t&&(validateOptionNames(e,t,["source"]),validateNamedOptionalPropertyEquals(e,"options","source",t.source,["default","server","cache"]))}function validateReference(e,t,n){if(t instanceof DocumentReference){if(t.firestore!==n)throw new FirestoreError(Code.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return t}throw invalidClassError(e,"DocumentReference",1,t)}function changesFromSnapshot(e,t,n){if(n.oldDocs.isEmpty()){var r,i=0;return n.docChanges.map(function(t){var o=new QueryDocumentSnapshot(e,t.doc.key,t.doc,n.fromCache,n.mutatedKeys.has(t.doc.key));return assert$1(t.type===ChangeType.Added,"Invalid event type for first snapshot"),assert$1(!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!==ChangeType.Metadata}).map(function(t){var r=new QueryDocumentSnapshot(e,t.doc.key,t.doc,n.fromCache,n.mutatedKeys.has(t.doc.key)),i=-1,a=-1;return t.type!==ChangeType.Added&&(assert$1((i=o.indexOf(t.doc.key))>=0,"Index for document not found"),o=o.delete(t.doc.key)),t.type!==ChangeType.Removed&&(a=(o=o.add(t.doc)).indexOf(t.doc.key)),{type:resultChangeType(t.type),doc:r,oldIndex:i,newIndex:a}})}function resultChangeType(e){switch(e){case ChangeType.Added:return"added";case ChangeType.Modified:case ChangeType.Metadata:return"modified";case ChangeType.Removed:return"removed";default:return fail("Unknown change type: "+e)}}var PublicFirestore=makeConstructorPrivate(Firestore,"Use firebase.firestore() instead."),PublicTransaction=makeConstructorPrivate(Transaction$1,"Use firebase.firestore().runTransaction() instead."),PublicWriteBatch=makeConstructorPrivate(WriteBatch,"Use firebase.firestore().batch() instead."),PublicDocumentReference=makeConstructorPrivate(DocumentReference,"Use firebase.firestore().doc() instead."),PublicDocumentSnapshot=makeConstructorPrivate(DocumentSnapshot),PublicQueryDocumentSnapshot=makeConstructorPrivate(QueryDocumentSnapshot),PublicQuery=makeConstructorPrivate(Query$1$1),PublicQuerySnapshot=makeConstructorPrivate(QuerySnapshot),PublicCollectionReference=makeConstructorPrivate(CollectionReference,"Use firebase.firestore().collection() instead."),firestoreNamespace={Firestore:PublicFirestore,GeoPoint:GeoPoint,Timestamp:Timestamp,Blob:PublicBlob,Transaction:PublicTransaction,WriteBatch:PublicWriteBatch,DocumentReference:PublicDocumentReference,DocumentSnapshot:PublicDocumentSnapshot,Query:PublicQuery,QueryDocumentSnapshot:PublicQueryDocumentSnapshot,QuerySnapshot:PublicQuerySnapshot,CollectionReference:PublicCollectionReference,FieldPath:FieldPath$1,FieldValue:PublicFieldValue,setLogLevel:Firestore.setLogLevel};function configureForFirebase(e){e.INTERNAL.registerService("firestore",function(e){return new Firestore(e)},shallowCopy(firestoreNamespace))}function registerFirestore(e){configureForFirebase(e)}registerFirestore(firebase);var errorCodeMap={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"},HttpsErrorImpl=function(e){function t(n,r,i){var o=e.call(this,r)||this;return Object.setPrototypeOf(o,t.prototype),o.code=n,o.details=i,o}return __extends(t,e),t}(Error);function codeForHTTPStatus(e){if(e>=200&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}function _errorForResponse(e,t,n){var r=codeForHTTPStatus(e),i=r,o=void 0;try{var a=t.error;if(a){var s=a.status;if("string"==typeof s){if(!errorCodeMap[s])return new HttpsErrorImpl("internal","internal");r=errorCodeMap[s]}i=s;var u=a.message;"string"==typeof u&&(i=u),void 0!==(o=a.details)&&(o=n.decode(o))}}catch(e){}return"ok"===r?null:new HttpsErrorImpl(r,i,o)}var ContextProvider=function(){function e(e){this.app=e}return e.prototype.getAuthToken=function(){return __awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.app.INTERNAL.getToken()];case 1:return(e=t.sent())?[2,e.accessToken]:[2,void 0];case 2:return t.sent(),[2,void 0];case 3:return[2]}})})},e.prototype.getInstanceIdToken=function(){return __awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),this.app.messaging?[4,this.app.messaging().getToken()]:[2,void 0];case 1:return(e=t.sent())?[2,e]:[2,void 0];case 2:return t.sent(),[2,void 0];case 3:return[2]}})})},e.prototype.getContext=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(n){switch(n.label){case 0:return[4,this.getAuthToken()];case 1:return e=n.sent(),[4,this.getInstanceIdToken()];case 2:return t=n.sent(),[2,{authToken:e,instanceIdToken:t}]}})})},e}(),LONG_TYPE="type.googleapis.com/google.protobuf.Int64Value",UNSIGNED_LONG_TYPE="type.googleapis.com/google.protobuf.UInt64Value";function mapValues(e,t){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}var Serializer=function(){function e(){}return e.prototype.encode=function(e){var t=this;if(null===e||void 0===e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(Array.isArray(e))return e.map(function(e){return t.encode(e)});if("function"==typeof e||"object"==typeof e)return mapValues(e,function(e){return t.encode(e)});throw new Error("Data cannot be encoded in JSON: "+e)},e.prototype.decode=function(e){var t=this;if(null===e)return e;if(e["@type"])switch(e["@type"]){case LONG_TYPE:case UNSIGNED_LONG_TYPE:var n=parseFloat(e.value);if(isNaN(n))throw new Error("Data cannot be decoded from JSON: "+e);return n;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(function(e){return t.decode(e)}):"function"==typeof e||"object"==typeof e?mapValues(e,function(e){return t.decode(e)}):e},e}(),Service=function(){function e(e,t){void 0===t&&(t="us-central1"),this.app_=e,this.region_=t,this.serializer=new Serializer,this.emulatorOrigin=null,this.contextProvider=new ContextProvider(e)}return Object.defineProperty(e.prototype,"app",{get:function(){return this.app_},enumerable:!0,configurable:!0}),e.prototype._url=function(e){var t=this.app_.options.projectId,n=this.region_;return null!==this.emulatorOrigin?this.emulatorOrigin+"/"+t+"/"+n+"/"+e:"https://"+n+"-"+t+".cloudfunctions.net/"+e},e.prototype.useFunctionsEmulator=function(e){this.emulatorOrigin=e},e.prototype.httpsCallable=function(e){var t=this;return function(n){return t.call(e,n)}},e.prototype.postJSON=function(e,t,n){return __awaiter(this,void 0,void 0,function(){var r,i;return __generator(this,function(o){switch(o.label){case 0:n.append("Content-Type","application/json"),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(e,{method:"POST",body:JSON.stringify(t),headers:n})];case 2:return r=o.sent(),[3,4];case 3:return o.sent(),[2,{status:0,json:null}];case 4:i=null,o.label=5;case 5:return o.trys.push([5,7,,8]),[4,r.json()];case 6:return i=o.sent(),[3,8];case 7:return o.sent(),[3,8];case 8:return[2,{status:r.status,json:i}]}})})},e.prototype.call=function(e,t){return __awaiter(this,void 0,void 0,function(){var n,r,i,o,a,s,u;return __generator(this,function(c){switch(c.label){case 0:return n=this._url(e),t=this.serializer.encode(t),r={data:t},i=new Headers,[4,this.contextProvider.getContext()];case 1:return(o=c.sent()).authToken&&i.append("Authorization","Bearer "+o.authToken),o.instanceIdToken&&i.append("Firebase-Instance-ID-Token",o.instanceIdToken),[4,this.postJSON(n,r,i)];case 2:if(a=c.sent(),s=_errorForResponse(a.status,a.json,this.serializer))throw s;if(!a.json)throw new HttpsErrorImpl("internal","Response is not valid JSON object.");if(void 0===(u=a.json.data)&&(u=a.json.result),void 0===u)throw new HttpsErrorImpl("internal","Response is missing data field.");return[2,{data:this.serializer.decode(u)}]}})})},e}(),FUNCTIONS_TYPE="functions";function factory(e,t,n){return new Service(e,n)}function registerFunctions(e){var t={Functions:Service};e.INTERNAL.registerService(FUNCTIONS_TYPE,factory,t,void 0,!0)}registerFunctions(firebase);var ERROR_CODES={AVAILABLE_IN_WINDOW:"only-available-in-window",AVAILABLE_IN_SW:"only-available-in-sw",SHOULD_BE_INHERITED:"should-be-overriden",BAD_SENDER_ID:"bad-sender-id",INCORRECT_GCM_SENDER_ID:"incorrect-gcm-sender-id",PERMISSION_DEFAULT:"permission-default",PERMISSION_BLOCKED:"permission-blocked",UNSUPPORTED_BROWSER:"unsupported-browser",NOTIFICATIONS_BLOCKED:"notifications-blocked",FAILED_DEFAULT_REGISTRATION:"failed-serviceworker-registration",SW_REGISTRATION_EXPECTED:"sw-registration-expected",GET_SUBSCRIPTION_FAILED:"get-subscription-failed",INVALID_SAVED_TOKEN:"invalid-saved-token",SW_REG_REDUNDANT:"sw-reg-redundant",TOKEN_SUBSCRIBE_FAILED:"token-subscribe-failed",TOKEN_SUBSCRIBE_NO_TOKEN:"token-subscribe-no-token",TOKEN_SUBSCRIBE_NO_PUSH_SET:"token-subscribe-no-push-set",TOKEN_UNSUBSCRIBE_FAILED:"token-unsubscribe-failed",TOKEN_UPDATE_FAILED:"token-update-failed",TOKEN_UPDATE_NO_TOKEN:"token-update-no-token",USE_SW_BEFORE_GET_TOKEN:"use-sw-before-get-token",INVALID_DELETE_TOKEN:"invalid-delete-token",DELETE_TOKEN_NOT_FOUND:"delete-token-not-found",DELETE_SCOPE_NOT_FOUND:"delete-scope-not-found",BG_HANDLER_FUNCTION_EXPECTED:"bg-handler-function-expected",NO_WINDOW_CLIENT_TO_MSG:"no-window-client-to-msg",UNABLE_TO_RESUBSCRIBE:"unable-to-resubscribe",NO_FCM_TOKEN_FOR_RESUBSCRIBE:"no-fcm-token-for-resubscribe",FAILED_TO_DELETE_TOKEN:"failed-to-delete-token",NO_SW_IN_REG:"no-sw-in-reg",BAD_SCOPE:"bad-scope",BAD_VAPID_KEY:"bad-vapid-key",BAD_SUBSCRIPTION:"bad-subscription",BAD_TOKEN:"bad-token",BAD_PUSH_SET:"bad-push-set",FAILED_DELETE_VAPID_KEY:"failed-delete-vapid-key",INVALID_PUBLIC_VAPID_KEY:"invalid-public-vapid-key",USE_PUBLIC_KEY_BEFORE_GET_TOKEN:"use-public-key-before-get-token",PUBLIC_KEY_DECRYPTION_FAILED:"public-vapid-key-decryption-failed"},ERROR_MAP=(_a={},_a[ERROR_CODES.AVAILABLE_IN_WINDOW]="This method is available in a Window context.",_a[ERROR_CODES.AVAILABLE_IN_SW]="This method is available in a service worker context.",_a[ERROR_CODES.SHOULD_BE_INHERITED]="This method should be overriden by extended classes.",_a[ERROR_CODES.BAD_SENDER_ID]="Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp().",_a[ERROR_CODES.PERMISSION_DEFAULT]="The required permissions were not granted and dismissed instead.",_a[ERROR_CODES.PERMISSION_BLOCKED]="The required permissions were not granted and blocked instead.",_a[ERROR_CODES.UNSUPPORTED_BROWSER]="This browser doesn't support the API's required to use the firebase SDK.",_a[ERROR_CODES.NOTIFICATIONS_BLOCKED]="Notifications have been blocked.",_a[ERROR_CODES.FAILED_DEFAULT_REGISTRATION]="We are unable to register the default service worker. {$browserErrorMessage}",_a[ERROR_CODES.SW_REGISTRATION_EXPECTED]="A service worker registration was the expected input.",_a[ERROR_CODES.GET_SUBSCRIPTION_FAILED]="There was an error when trying to get any existing Push Subscriptions.",_a[ERROR_CODES.INVALID_SAVED_TOKEN]="Unable to access details of the saved token.",_a[ERROR_CODES.SW_REG_REDUNDANT]="The service worker being used for push was made redundant.",_a[ERROR_CODES.TOKEN_SUBSCRIBE_FAILED]="A problem occured while subscribing the user to FCM: {$message}",_a[ERROR_CODES.TOKEN_SUBSCRIBE_NO_TOKEN]="FCM returned no token when subscribing the user to push.",_a[ERROR_CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET]="FCM returned an invalid response when getting an FCM token.",_a[ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED]="A problem occured while unsubscribing the user from FCM: {$message}",_a[ERROR_CODES.TOKEN_UPDATE_FAILED]="A problem occured while updating the user from FCM: {$message}",_a[ERROR_CODES.TOKEN_UPDATE_NO_TOKEN]="FCM returned no token when updating the user to push.",_a[ERROR_CODES.USE_SW_BEFORE_GET_TOKEN]="The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.",_a[ERROR_CODES.INVALID_DELETE_TOKEN]="You must pass a valid token into deleteToken(), i.e. the token from getToken().",_a[ERROR_CODES.DELETE_TOKEN_NOT_FOUND]="The deletion attempt for token could not be performed as the token was not found.",_a[ERROR_CODES.DELETE_SCOPE_NOT_FOUND]="The deletion attempt for service worker scope could not be performed as the scope was not found.",_a[ERROR_CODES.BG_HANDLER_FUNCTION_EXPECTED]="The input to setBackgroundMessageHandler() must be a function.",_a[ERROR_CODES.NO_WINDOW_CLIENT_TO_MSG]="An attempt was made to message a non-existant window client.",_a[ERROR_CODES.UNABLE_TO_RESUBSCRIBE]="There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}",_a[ERROR_CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE]="Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit.",_a[ERROR_CODES.FAILED_TO_DELETE_TOKEN]="Unable to delete the currently saved token.",_a[ERROR_CODES.NO_SW_IN_REG]="Even though the service worker registration was successful, there was a problem accessing the service worker itself.",_a[ERROR_CODES.INCORRECT_GCM_SENDER_ID]="Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging.",_a[ERROR_CODES.BAD_SCOPE]="The service worker scope must be a string with at least one character.",_a[ERROR_CODES.BAD_VAPID_KEY]="The public VAPID key is not a Uint8Array with 65 bytes.",_a[ERROR_CODES.BAD_SUBSCRIPTION]="The subscription must be a valid PushSubscription.",_a[ERROR_CODES.BAD_TOKEN]="The FCM Token used for storage / lookup was not a valid token string.",_a[ERROR_CODES.BAD_PUSH_SET]="The FCM push set used for storage / lookup was not not a valid push set string.",_a[ERROR_CODES.FAILED_DELETE_VAPID_KEY]="The VAPID key could not be deleted.",_a[ERROR_CODES.INVALID_PUBLIC_VAPID_KEY]="The public VAPID key must be a string.",_a[ERROR_CODES.PUBLIC_KEY_DECRYPTION_FAILED]="The public VAPID key did not equal 65 bytes when decrypted.",_a),errorFactory=new ErrorFactory("messaging","Messaging",ERROR_MAP),_a,DEFAULT_PUBLIC_VAPID_KEY=new Uint8Array([4,51,148,247,223,161,235,177,220,3,162,94,21,113,219,72,211,46,237,237,178,52,219,183,71,58,12,143,196,204,225,111,60,140,132,223,171,182,102,62,242,12,212,139,254,227,249,118,47,20,28,99,8,106,111,45,177,26,149,176,206,55,192,156,110]),ENDPOINT="https://fcm.googleapis.com",MessageParameter,MessageType;function isArrayBufferEqual(e,t){if(null==e||null==t)return!1;if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(var n=new DataView(e),r=new DataView(t),i=0;i<e.byteLength;i++)if(n.getUint8(i)!==r.getUint8(i))return!1;return!0}function toBase64(e){var t=new Uint8Array(e);return btoa(String.fromCharCode.apply(null,t))}function arrayBufferToBase64(e){return toBase64(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}!function(e){e.TYPE_OF_MSG="firebase-messaging-msg-type",e.DATA="firebase-messaging-msg-data"}(MessageParameter||(MessageParameter={})),function(e){e.PUSH_MSG_RECEIVED="push-msg-received",e.NOTIFICATION_CLICKED="notification-clicked"}(MessageType||(MessageType={}));var IidModel=function(){function e(){}return e.prototype.getToken=function(e,t,n){return __awaiter(this,void 0,void 0,function(){var r,i,o,a,s,u,c,h;return __generator(this,function(l){switch(l.label){case 0:r=arrayBufferToBase64(t.getKey("p256dh")),i=arrayBufferToBase64(t.getKey("auth")),o="authorized_entity="+e+"&endpoint="+t.endpoint+"&encryption_key="+r+"&encryption_auth="+i,isArrayBufferEqual(n.buffer,DEFAULT_PUBLIC_VAPID_KEY.buffer)||(a=arrayBufferToBase64(n),o+="&application_pub_key="+a),(s=new Headers).append("Content-Type","application/x-www-form-urlencoded"),u={method:"POST",headers:s,body:o},l.label=1;case 1:return l.trys.push([1,4,,5]),[4,fetch(ENDPOINT+"/fcm/connect/subscribe",u)];case 2:return[4,l.sent().json()];case 3:return c=l.sent(),[3,5];case 4:throw l.sent(),errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_FAILED);case 5:if(c.error)throw h=c.error.message,errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_FAILED,{message:h});if(!c.token)throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_NO_TOKEN);if(!c.pushSet)throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET);return[2,{token:c.token,pushSet:c.pushSet}]}})})},e.prototype.updateToken=function(e,t,n,r,i){return __awaiter(this,void 0,void 0,function(){var o,a,s,u,c,h,l,d;return __generator(this,function(f){switch(f.label){case 0:o=arrayBufferToBase64(r.getKey("p256dh")),a=arrayBufferToBase64(r.getKey("auth")),s="push_set="+n+"&token="+t+"&authorized_entity="+e+"&endpoint="+r.endpoint+"&encryption_key="+o+"&encryption_auth="+a,isArrayBufferEqual(i.buffer,DEFAULT_PUBLIC_VAPID_KEY.buffer)||(u=arrayBufferToBase64(i),s+="&application_pub_key="+u),(c=new Headers).append("Content-Type","application/x-www-form-urlencoded"),h={method:"POST",headers:c,body:s},f.label=1;case 1:return f.trys.push([1,4,,5]),[4,fetch(ENDPOINT+"/fcm/connect/subscribe",h)];case 2:return[4,f.sent().json()];case 3:return l=f.sent(),[3,5];case 4:throw f.sent(),errorFactory.create(ERROR_CODES.TOKEN_UPDATE_FAILED);case 5:if(l.error)throw d=l.error.message,errorFactory.create(ERROR_CODES.TOKEN_UPDATE_FAILED,{message:d});if(!l.token)throw errorFactory.create(ERROR_CODES.TOKEN_UPDATE_NO_TOKEN);return[2,l.token]}})})},e.prototype.deleteToken=function(e,t,n){return __awaiter(this,void 0,void 0,function(){var r,i,o,a,s;return __generator(this,function(u){switch(u.label){case 0:r="authorized_entity="+e+"&token="+t+"&pushSet="+n,(i=new Headers).append("Content-Type","application/x-www-form-urlencoded"),o={method:"POST",headers:i,body:r},u.label=1;case 1:return u.trys.push([1,4,,5]),[4,fetch(ENDPOINT+"/fcm/connect/unsubscribe",o)];case 2:return[4,u.sent().json()];case 3:if((a=u.sent()).error)throw s=a.error.message,errorFactory.create(ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED,{message:s});return[3,5];case 4:throw u.sent(),errorFactory.create(ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED);case 5:return[2]}})})},e}();function base64ToArrayBuffer(e){for(var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length),i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}var OLD_DB_NAME="undefined",OLD_OBJECT_STORE_NAME="fcm_token_object_Store";function handleDb(e){if(e.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)){var t=e.transaction(OLD_OBJECT_STORE_NAME).objectStore(OLD_OBJECT_STORE_NAME),n=new IidModel,r=t.openCursor();r.onerror=function(e){console.warn("Unable to cleanup old IDB.",e)},r.onsuccess=function(){var t=r.result;if(t){var i=t.value;n.deleteToken(i.fcmSenderId,i.fcmToken,i.fcmPushSet),t.continue()}else e.close(),indexedDB.deleteDatabase(OLD_DB_NAME)}}}function cleanV1(){var e=indexedDB.open(OLD_DB_NAME);e.onerror=function(e){},e.onsuccess=function(t){handleDb(e.result)}}var DbInterface=function(){function e(){this.dbPromise=null}return e.prototype.get=function(e){return this.createTransaction(function(t){return t.get(e)})},e.prototype.getIndex=function(e,t){return this.createTransaction(function(n){return n.index(e).get(t)})},e.prototype.put=function(e){return this.createTransaction(function(t){return t.put(e)},"readwrite")},e.prototype.delete=function(e){return this.createTransaction(function(t){return t.delete(e)},"readwrite")},e.prototype.closeDatabase=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this.dbPromise?[4,this.dbPromise]:[3,2];case 1:e.sent().close(),this.dbPromise=null,e.label=2;case 2:return[2]}})})},e.prototype.createTransaction=function(e,t){return void 0===t&&(t="readonly"),__awaiter(this,void 0,void 0,function(){var n,r,i,o;return __generator(this,function(a){switch(a.label){case 0:return[4,this.getDb()];case 1:return n=a.sent(),r=n.transaction(this.objectStoreName,t),i=r.objectStore(this.objectStoreName),[4,promisify(e(i))];case 2:return o=a.sent(),[2,new Promise(function(e,t){r.oncomplete=function(){e(o)},r.onerror=function(){t(r.error)}})]}})})},e.prototype.getDb=function(){var e=this;return this.dbPromise||(this.dbPromise=new Promise(function(t,n){var r=indexedDB.open(e.dbName,e.dbVersion);r.onsuccess=function(){t(r.result)},r.onerror=function(){e.dbPromise=null,n(r.error)},r.onupgradeneeded=function(t){return e.onDbUpgrade(r,t)}})),this.dbPromise},e}();function promisify(e){return new Promise(function(t,n){e.onsuccess=function(){t(e.result)},e.onerror=function(){n(e.error)}})}var TokenDetailsModel=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.dbName="fcm_token_details_db",t.dbVersion=3,t.objectStoreName="fcm_token_object_Store",t}return __extends(t,e),t.prototype.onDbUpgrade=function(e,t){var n=e.result;switch(t.oldVersion){case 0:(r=n.createObjectStore(this.objectStoreName,{keyPath:"swScope"})).createIndex("fcmSenderId","fcmSenderId",{unique:!1}),r.createIndex("fcmToken","fcmToken",{unique:!0});case 1:cleanV1();case 2:var r,i=(r=e.transaction.objectStore(this.objectStoreName)).openCursor();i.onsuccess=function(){var e=i.result;if(e){var t=e.value,n=__assign({},t);t.createTime||(n.createTime=Date.now()),"string"==typeof t.vapidKey&&(n.vapidKey=base64ToArrayBuffer(t.vapidKey)),"string"==typeof t.auth&&(n.auth=base64ToArrayBuffer(t.auth).buffer),"string"==typeof t.auth&&(n.p256dh=base64ToArrayBuffer(t.p256dh).buffer),e.update(n),e.continue()}}}},t.prototype.getTokenDetailsFromToken=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){if(!e)throw errorFactory.create(ERROR_CODES.BAD_TOKEN);return validateInputs({fcmToken:e}),[2,this.getIndex("fcmToken",e)]})})},t.prototype.getTokenDetailsFromSWScope=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){if(!e)throw errorFactory.create(ERROR_CODES.BAD_SCOPE);return validateInputs({swScope:e}),[2,this.get(e)]})})},t.prototype.saveTokenDetails=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){if(!e.swScope)throw errorFactory.create(ERROR_CODES.BAD_SCOPE);if(!e.vapidKey)throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);if(!e.endpoint||!e.auth||!e.p256dh)throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);if(!e.fcmSenderId)throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);if(!e.fcmToken)throw errorFactory.create(ERROR_CODES.BAD_TOKEN);if(!e.fcmPushSet)throw errorFactory.create(ERROR_CODES.BAD_PUSH_SET);return validateInputs(e),[2,this.put(e)]})})},t.prototype.deleteToken=function(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(n){switch(n.label){case 0:return"string"!=typeof e||0===e.length?[2,Promise.reject(errorFactory.create(ERROR_CODES.INVALID_DELETE_TOKEN))]:[4,this.getTokenDetailsFromToken(e)];case 1:if(!(t=n.sent()))throw errorFactory.create(ERROR_CODES.DELETE_TOKEN_NOT_FOUND);return[4,this.delete(t.swScope)];case 2:return n.sent(),[2,t]}})})},t}(DbInterface);function validateInputs(e){if(e.fcmToken&&("string"!=typeof e.fcmToken||0===e.fcmToken.length))throw errorFactory.create(ERROR_CODES.BAD_TOKEN);if(e.swScope&&("string"!=typeof e.swScope||0===e.swScope.length))throw errorFactory.create(ERROR_CODES.BAD_SCOPE);if(e.vapidKey&&(!(e.vapidKey instanceof Uint8Array)||65!==e.vapidKey.length))throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);if(e.endpoint&&("string"!=typeof e.endpoint||0===e.endpoint.length))throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);if(e.auth&&!(e.auth instanceof ArrayBuffer))throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);if(e.p256dh&&!(e.p256dh instanceof ArrayBuffer))throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);if(e.fcmSenderId&&("string"!=typeof e.fcmSenderId||0===e.fcmSenderId.length))throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);if(e.fcmPushSet&&("string"!=typeof e.fcmPushSet||0===e.fcmPushSet.length))throw errorFactory.create(ERROR_CODES.BAD_PUSH_SET)}var UNCOMPRESSED_PUBLIC_KEY_SIZE=65,VapidDetailsModel=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.dbName="fcm_vapid_details_db",t.dbVersion=1,t.objectStoreName="fcm_vapid_object_Store",t}return __extends(t,e),t.prototype.onDbUpgrade=function(e){e.result.createObjectStore(this.objectStoreName,{keyPath:"swScope"})},t.prototype.getVapidFromSWScope=function(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(n){switch(n.label){case 0:if("string"!=typeof e||0===e.length)throw errorFactory.create(ERROR_CODES.BAD_SCOPE);return[4,this.get(e)];case 1:return[2,(t=n.sent())?t.vapidKey:void 0]}})})},t.prototype.saveVapidDetails=function(e,t){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(r){if("string"!=typeof e||0===e.length)throw errorFactory.create(ERROR_CODES.BAD_SCOPE);if(null===t||t.length!==UNCOMPRESSED_PUBLIC_KEY_SIZE)throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);return n={swScope:e,vapidKey:t},[2,this.put(n)]})})},t.prototype.deleteVapidDetails=function(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(n){switch(n.label){case 0:return[4,this.getVapidFromSWScope(e)];case 1:if(!(t=n.sent()))throw errorFactory.create(ERROR_CODES.DELETE_SCOPE_NOT_FOUND);return[4,this.delete(e)];case 2:return n.sent(),[2,t]}})})},t}(DbInterface),SENDER_ID_OPTION_NAME="messagingSenderId",TOKEN_EXPIRATION_MILLIS=6048e5,BaseController=function(){function e(e){var t=this;if(!e.options[SENDER_ID_OPTION_NAME]||"string"!=typeof e.options[SENDER_ID_OPTION_NAME])throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);this.messagingSenderId=e.options[SENDER_ID_OPTION_NAME],this.tokenDetailsModel=new TokenDetailsModel,this.vapidDetailsModel=new VapidDetailsModel,this.iidModel=new IidModel,this.app=e,this.INTERNAL={delete:function(){return t.delete()}}}return e.prototype.getToken=function(){return __awaiter(this,void 0,void 0,function(){var e,t,n,r,i;return __generator(this,function(o){switch(o.label){case 0:if("denied"===(e=this.getNotificationPermission_()))throw errorFactory.create(ERROR_CODES.NOTIFICATIONS_BLOCKED);return"granted"!==e?[2,null]:[4,this.getSWRegistration_()];case 1:return t=o.sent(),[4,this.getPublicVapidKey_()];case 2:return n=o.sent(),[4,this.getPushSubscription(t,n)];case 3:return r=o.sent(),[4,this.tokenDetailsModel.getTokenDetailsFromSWScope(t.scope)];case 4:return(i=o.sent())?[2,this.manageExistingToken(t,r,n,i)]:[2,this.getNewToken(t,r,n)]}})})},e.prototype.manageExistingToken=function(e,t,n,r){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(i){switch(i.label){case 0:return isTokenStillValid(t,n,r)?Date.now()<r.createTime+TOKEN_EXPIRATION_MILLIS?[2,r.fcmToken]:[2,this.updateToken(e,t,n,r)]:[4,this.deleteTokenFromDB(r.fcmToken)];case 1:return i.sent(),[2,this.getNewToken(e,t,n)]}})})},e.prototype.updateToken=function(e,t,n,r){return __awaiter(this,void 0,void 0,function(){var i,o,a;return __generator(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,6]),[4,this.iidModel.updateToken(this.messagingSenderId,r.fcmToken,r.fcmPushSet,t,n)];case 1:return i=s.sent(),o={swScope:e.scope,vapidKey:n,fcmSenderId:this.messagingSenderId,fcmToken:i,fcmPushSet:r.fcmPushSet,createTime:Date.now(),endpoint:t.endpoint,auth:t.getKey("auth"),p256dh:t.getKey("p256dh")},[4,this.tokenDetailsModel.saveTokenDetails(o)];case 2:return s.sent(),[4,this.vapidDetailsModel.saveVapidDetails(e.scope,n)];case 3:return s.sent(),[2,i];case 4:return a=s.sent(),[4,this.deleteToken(r.fcmToken)];case 5:throw s.sent(),a;case 6:return[2]}})})},e.prototype.getNewToken=function(e,t,n){return __awaiter(this,void 0,void 0,function(){var r,i;return __generator(this,function(o){switch(o.label){case 0:return[4,this.iidModel.getToken(this.messagingSenderId,t,n)];case 1:return r=o.sent(),i={swScope:e.scope,vapidKey:n,fcmSenderId:this.messagingSenderId,fcmToken:r.token,fcmPushSet:r.pushSet,createTime:Date.now(),endpoint:t.endpoint,auth:t.getKey("auth"),p256dh:t.getKey("p256dh")},[4,this.tokenDetailsModel.saveTokenDetails(i)];case 2:return o.sent(),[4,this.vapidDetailsModel.saveVapidDetails(e.scope,n)];case 3:return o.sent(),[2,r.token]}})})},e.prototype.deleteToken=function(e){return __awaiter(this,void 0,void 0,function(){var t,n;return __generator(this,function(r){switch(r.label){case 0:return[4,this.deleteTokenFromDB(e)];case 1:return r.sent(),[4,this.getSWRegistration_()];case 2:return(t=r.sent())?[4,t.pushManager.getSubscription()]:[3,4];case 3:if(n=r.sent())return[2,n.unsubscribe()];r.label=4;case 4:return[2,!0]}})})},e.prototype.deleteTokenFromDB=function(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(n){switch(n.label){case 0:return[4,this.tokenDetailsModel.deleteToken(e)];case 1:return t=n.sent(),[4,this.iidModel.deleteToken(t.fcmSenderId,t.fcmToken,t.fcmPushSet)];case 2:return n.sent(),[2]}})})},e.prototype.getPushSubscription=function(e,t){return e.pushManager.getSubscription().then(function(n){return n||e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t})})},e.prototype.requestPermission=function(){throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW)},e.prototype.useServiceWorker=function(e){throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW)},e.prototype.usePublicVapidKey=function(e){throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW)},e.prototype.onMessage=function(e,t,n){throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW)},e.prototype.onTokenRefresh=function(e,t,n){throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW)},e.prototype.setBackgroundMessageHandler=function(e){throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_SW)},e.prototype.delete=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,Promise.all([this.tokenDetailsModel.closeDatabase(),this.vapidDetailsModel.closeDatabase()])];case 1:return e.sent(),[2]}})})},e.prototype.getNotificationPermission_=function(){return Notification.permission},e.prototype.getTokenDetailsModel=function(){return this.tokenDetailsModel},e.prototype.getVapidDetailsModel=function(){return this.vapidDetailsModel},e.prototype.getIidModel=function(){return this.iidModel},e}();function isTokenStillValid(e,t,n){if(!n.vapidKey||!isArrayBufferEqual(t.buffer,n.vapidKey.buffer))return!1;var r=e.endpoint===n.endpoint,i=isArrayBufferEqual(e.getKey("auth"),n.auth),o=isArrayBufferEqual(e.getKey("p256dh"),n.p256dh);return r&&i&&o}var FCM_MSG="FCM_MSG",SwController=function(e){function t(t){var n=e.call(this,t)||this;return n.bgMessageHandler=null,self.addEventListener("push",function(e){n.onPush(e)}),self.addEventListener("pushsubscriptionchange",function(e){n.onSubChange(e)}),self.addEventListener("notificationclick",function(e){n.onNotificationClick(e)}),n}return __extends(t,e),t.prototype.onPush=function(e){e.waitUntil(this.onPush_(e))},t.prototype.onSubChange=function(e){e.waitUntil(this.onSubChange_(e))},t.prototype.onNotificationClick=function(e){e.waitUntil(this.onNotificationClick_(e))},t.prototype.onPush_=function(e){return __awaiter(this,void 0,void 0,function(){var t,n,r,i,o,a;return __generator(this,function(s){switch(s.label){case 0:if(!e.data)return[2];try{t=e.data.json()}catch(e){return[2]}return[4,this.hasVisibleClients_()];case 1:return s.sent()?[2,this.sendMessageToWindowClients_(t)]:(n=this.getNotificationData_(t))?(r=n.title||"",[4,this.getSWRegistration_()]):[3,3];case 2:return i=s.sent(),o=n.actions,a=Notification.maxActions,o&&a&&o.length>a&&console.warn("This browser only supports "+a+" actions.The remaining actions will not be displayed."),[2,i.showNotification(r,n)];case 3:return this.bgMessageHandler?[4,this.bgMessageHandler(t)]:[3,5];case 4:return s.sent(),[2];case 5:return[2]}})})},t.prototype.onSubChange_=function(e){return __awaiter(this,void 0,void 0,function(){var e,t,n,r;return __generator(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.getSWRegistration_()];case 1:return e=i.sent(),[3,3];case 2:throw t=i.sent(),errorFactory.create(ERROR_CODES.UNABLE_TO_RESUBSCRIBE,{message:t});case 3:return i.trys.push([3,5,,8]),[4,e.pushManager.getSubscription()];case 4:return i.sent(),[3,8];case 5:return n=i.sent(),[4,this.getTokenDetailsModel().getTokenDetailsFromSWScope(e.scope)];case 6:if(!(r=i.sent()))throw n;return[4,this.deleteToken(r.fcmToken)];case 7:throw i.sent(),n;case 8:return[2]}})})},t.prototype.onNotificationClick_=function(e){return __awaiter(this,void 0,void 0,function(){var t,n,r,i;return __generator(this,function(o){switch(o.label){case 0:return e.notification&&e.notification.data&&e.notification.data[FCM_MSG]?e.action?[2]:(e.stopImmediatePropagation(),e.notification.close(),(t=e.notification.data[FCM_MSG]).notification&&(n=t.fcmOptions&&t.fcmOptions.link||t.notification.click_action)?[4,this.getWindowClient_(n)]:[2]):[2];case 1:return(r=o.sent())?[3,3]:[4,self.clients.openWindow(n)];case 2:return r=o.sent(),[3,5];case 3:return[4,r.focus()];case 4:r=o.sent(),o.label=5;case 5:return r?(delete t.notification,delete t.fcmOptions,i=createNewMsg(MessageType.NOTIFICATION_CLICKED,t),[2,this.attemptToMessageClient_(r,i)]):[2]}})})},t.prototype.getNotificationData_=function(e){if(e&&"object"==typeof e.notification){var t,n=__assign({},e.notification);return n.data=__assign({},e.notification.data,((t={})[FCM_MSG]=e,t)),n}},t.prototype.setBackgroundMessageHandler=function(e){if(!e||"function"!=typeof e)throw errorFactory.create(ERROR_CODES.BG_HANDLER_FUNCTION_EXPECTED);this.bgMessageHandler=e},t.prototype.getWindowClient_=function(e){return __awaiter(this,void 0,void 0,function(){var t,n,r,i;return __generator(this,function(o){switch(o.label){case 0:return t=new URL(e,self.location.href).href,[4,getClientList()];case 1:for(n=o.sent(),r=null,i=0;i<n.length;i++)if(new URL(n[i].url,self.location.href).href===t){r=n[i];break}return[2,r]}})})},t.prototype.attemptToMessageClient_=function(e,t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(n){if(!e)throw errorFactory.create(ERROR_CODES.NO_WINDOW_CLIENT_TO_MSG);return e.postMessage(t),[2]})})},t.prototype.hasVisibleClients_=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,getClientList()];case 1:return[2,e.sent().some(function(e){return"visible"===e.visibilityState})]}})})},t.prototype.sendMessageToWindowClients_=function(e){return __awaiter(this,void 0,void 0,function(){var t,n,r=this;return __generator(this,function(i){switch(i.label){case 0:return[4,getClientList()];case 1:return t=i.sent(),n=createNewMsg(MessageType.PUSH_MSG_RECEIVED,e),[4,Promise.all(t.map(function(e){return r.attemptToMessageClient_(e,n)}))];case 2:return i.sent(),[2]}})})},t.prototype.getSWRegistration_=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,self.registration]})})},t.prototype.getPublicVapidKey_=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(n){switch(n.label){case 0:return[4,this.getSWRegistration_()];case 1:if(!(e=n.sent()))throw errorFactory.create(ERROR_CODES.SW_REGISTRATION_EXPECTED);return[4,this.getVapidDetailsModel().getVapidFromSWScope(e.scope)];case 2:return null==(t=n.sent())?[2,DEFAULT_PUBLIC_VAPID_KEY]:[2,t]}})})},t}(BaseController);function getClientList(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function createNewMsg(e,t){return(n={})[MessageParameter.TYPE_OF_MSG]=e,n[MessageParameter.DATA]=t,n;var n}var DEFAULT_SW_PATH="/firebase-messaging-sw.js",DEFAULT_SW_SCOPE="/firebase-cloud-messaging-push-scope",WindowController=function(e){function t(t){var n=e.call(this,t)||this;return n.registrationToUse=null,n.publicVapidKeyToUse=null,n.manifestCheckPromise=null,n.messageObserver=null,n.tokenRefreshObserver=null,n.onMessageInternal=createSubscribe(function(e){n.messageObserver=e}),n.onTokenRefreshInternal=createSubscribe(function(e){n.tokenRefreshObserver=e}),n.setupSWMessageListener_(),n}return __extends(t,e),t.prototype.getToken=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return this.manifestCheckPromise||(this.manifestCheckPromise=manifestCheck()),[4,this.manifestCheckPromise];case 1:return t.sent(),[2,e.prototype.getToken.call(this)]}})})},t.prototype.requestPermission=function(){return __awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(t){switch(t.label){case 0:return"granted"===this.getNotificationPermission_()?[2]:[4,Notification.requestPermission()];case 1:if("granted"===(e=t.sent()))return[2];throw"denied"===e?errorFactory.create(ERROR_CODES.PERMISSION_BLOCKED):errorFactory.create(ERROR_CODES.PERMISSION_DEFAULT)}})})},t.prototype.useServiceWorker=function(e){if(!(e instanceof ServiceWorkerRegistration))throw errorFactory.create(ERROR_CODES.SW_REGISTRATION_EXPECTED);if(null!=this.registrationToUse)throw errorFactory.create(ERROR_CODES.USE_SW_BEFORE_GET_TOKEN);this.registrationToUse=e},t.prototype.usePublicVapidKey=function(e){if("string"!=typeof e)throw errorFactory.create(ERROR_CODES.INVALID_PUBLIC_VAPID_KEY);if(null!=this.publicVapidKeyToUse)throw errorFactory.create(ERROR_CODES.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);var t=base64ToArrayBuffer(e);if(65!==t.length)throw errorFactory.create(ERROR_CODES.PUBLIC_KEY_DECRYPTION_FAILED);this.publicVapidKeyToUse=t},t.prototype.onMessage=function(e,t,n){return"function"==typeof e?this.onMessageInternal(e,t,n):this.onMessageInternal(e)},t.prototype.onTokenRefresh=function(e,t,n){return"function"==typeof e?this.onTokenRefreshInternal(e,t,n):this.onTokenRefreshInternal(e)},t.prototype.waitForRegistrationToActivate_=function(e){var t=e.installing||e.waiting||e.active;return new Promise(function(n,r){if(t)if("activated"!==t.state)if("redundant"!==t.state){var i=function(){if("activated"===t.state)n(e);else{if("redundant"!==t.state)return;r(errorFactory.create(ERROR_CODES.SW_REG_REDUNDANT))}t.removeEventListener("statechange",i)};t.addEventListener("statechange",i)}else r(errorFactory.create(ERROR_CODES.SW_REG_REDUNDANT));else n(e);else r(errorFactory.create(ERROR_CODES.NO_SW_IN_REG))})},t.prototype.getSWRegistration_=function(){var e=this;return this.registrationToUse?this.waitForRegistrationToActivate_(this.registrationToUse):(this.registrationToUse=null,navigator.serviceWorker.register(DEFAULT_SW_PATH,{scope:DEFAULT_SW_SCOPE}).catch(function(e){throw errorFactory.create(ERROR_CODES.FAILED_DEFAULT_REGISTRATION,{browserErrorMessage:e.message})}).then(function(t){return e.waitForRegistrationToActivate_(t).then(function(){return e.registrationToUse=t,t.update(),t})}))},t.prototype.getPublicVapidKey_=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.publicVapidKeyToUse?[2,this.publicVapidKeyToUse]:[2,DEFAULT_PUBLIC_VAPID_KEY]})})},t.prototype.setupSWMessageListener_=function(){var e=this;navigator.serviceWorker.addEventListener("message",function(t){if(t.data&&t.data[MessageParameter.TYPE_OF_MSG]){var n=t.data;switch(n[MessageParameter.TYPE_OF_MSG]){case MessageType.PUSH_MSG_RECEIVED:case MessageType.NOTIFICATION_CLICKED:var r=n[MessageParameter.DATA];e.messageObserver&&e.messageObserver.next(r)}}},!1)},t}(BaseController);function manifestCheck(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(n){switch(n.label){case 0:if(!(e=document.querySelector('link[rel="manifest"]')))return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(e.href)];case 2:return[4,n.sent().json()];case 3:return t=n.sent(),[3,5];case 4:return n.sent(),[2];case 5:if(!t||!t.gcm_sender_id)return[2];if("103953800507"!==t.gcm_sender_id)throw errorFactory.create(ERROR_CODES.INCORRECT_GCM_SENDER_ID);return[2]}})})}function registerMessaging(e){var t={isSupported:isSupported};e.INTERNAL.registerService("messaging",function(e){if(!isSupported())throw errorFactory.create(ERROR_CODES.UNSUPPORTED_BROWSER);return self&&"ServiceWorkerGlobalScope"in self?new SwController(e):new WindowController(e)},t)}function isSupported(){return self&&"ServiceWorkerGlobalScope"in self?isSWControllerSupported():isWindowControllerSupported()}function isWindowControllerSupported(){return navigator.cookieEnabled&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}function isSWControllerSupported(){return"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}registerMessaging(firebase);var domainBase="https://firebasestorage.googleapis.com",downloadBase="https://firebasestorage.googleapis.com",apiBaseUrl="/v0",apiUploadBaseUrl="/v0",configOption="storageBucket",defaultMaxOperationRetryTime=12e4,defaultMaxUploadRetryTime=6e4,minSafeInteger=-9007199254740991,FirebaseStorageError=function(){function e(e,t){this.code_=prependCode(e),this.message_="Firebase Storage: "+t,this.serverResponse_=null,this.name_="FirebaseError"}return e.prototype.codeProp=function(){return this.code},e.prototype.codeEquals=function(e){return prependCode(e)===this.codeProp()},e.prototype.serverResponseProp=function(){return this.serverResponse_},e.prototype.setServerResponseProp=function(e){this.serverResponse_=e},Object.defineProperty(e.prototype,"name",{get:function(){return this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"code",{get:function(){return this.code_},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"message",{get:function(){return this.message_},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"serverResponse",{get:function(){return this.serverResponse_},enumerable:!0,configurable:!0}),e}(),Code$1={UNKNOWN:"unknown",OBJECT_NOT_FOUND:"object-not-found",BUCKET_NOT_FOUND:"bucket-not-found",PROJECT_NOT_FOUND:"project-not-found",QUOTA_EXCEEDED:"quota-exceeded",UNAUTHENTICATED:"unauthenticated",UNAUTHORIZED:"unauthorized",RETRY_LIMIT_EXCEEDED:"retry-limit-exceeded",INVALID_CHECKSUM:"invalid-checksum",CANCELED:"canceled",INVALID_EVENT_NAME:"invalid-event-name",INVALID_URL:"invalid-url",INVALID_DEFAULT_BUCKET:"invalid-default-bucket",NO_DEFAULT_BUCKET:"no-default-bucket",CANNOT_SLICE_BLOB:"cannot-slice-blob",SERVER_FILE_WRONG_SIZE:"server-file-wrong-size",NO_DOWNLOAD_URL:"no-download-url",INVALID_ARGUMENT:"invalid-argument",INVALID_ARGUMENT_COUNT:"invalid-argument-count",APP_DELETED:"app-deleted",INVALID_ROOT_OPERATION:"invalid-root-operation",INVALID_FORMAT:"invalid-format",INTERNAL_ERROR:"internal-error"};function prependCode(e){return"storage/"+e}function unknown(){return new FirebaseStorageError(Code$1.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function objectNotFound(e){return new FirebaseStorageError(Code$1.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist.")}function quotaExceeded(e){return new FirebaseStorageError(Code$1.QUOTA_EXCEEDED,"Quota for bucket '"+e+"' exceeded, please view quota on https://firebase.google.com/pricing/.")}function unauthenticated(){return new FirebaseStorageError(Code$1.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again.")}function unauthorized(e){return new FirebaseStorageError(Code$1.UNAUTHORIZED,"User does not have permission to access '"+e+"'.")}function retryLimitExceeded(){return new FirebaseStorageError(Code$1.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function canceled(){return new FirebaseStorageError(Code$1.CANCELED,"User canceled the upload/download.")}function invalidUrl(e){return new FirebaseStorageError(Code$1.INVALID_URL,"Invalid URL '"+e+"'.")}function invalidDefaultBucket(e){return new FirebaseStorageError(Code$1.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}function cannotSliceBlob(){return new FirebaseStorageError(Code$1.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function serverFileWrongSize(){return new FirebaseStorageError(Code$1.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.")}function noDownloadURL(){return new FirebaseStorageError(Code$1.NO_DOWNLOAD_URL,"The given file does not have any download URLs.")}function invalidArgument(e,t,n){return new FirebaseStorageError(Code$1.INVALID_ARGUMENT,"Invalid argument in `"+t+"` at index "+e+": "+n)}function invalidArgumentCount(e,t,n,r){var i,o;return e===t?(i=e,o=1===e?"argument":"arguments"):(i="between "+e+" and "+t,o="arguments"),new FirebaseStorageError(Code$1.INVALID_ARGUMENT_COUNT,"Invalid argument count in `"+n+"`: Expected "+i+" "+o+", received "+r+".")}function appDeleted(){return new FirebaseStorageError(Code$1.APP_DELETED,"The Firebase app was deleted.")}function invalidRootOperation(e){return new FirebaseStorageError(Code$1.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function invalidFormat(e,t){return new FirebaseStorageError(Code$1.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function internalError(e){throw new FirebaseStorageError(Code$1.INTERNAL_ERROR,"Internal error: "+e)}var StringFormat={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};function formatValidator(e){switch(e){case StringFormat.RAW:case StringFormat.BASE64:case StringFormat.BASE64URL:case StringFormat.DATA_URL:return;default:throw"Expected one of the event types: ["+StringFormat.RAW+", "+StringFormat.BASE64+", "+StringFormat.BASE64URL+", "+StringFormat.DATA_URL+"]."}}var StringData=function(){return function(e,t){this.data=e,this.contentType=t||null}}();function dataFromString(e,t){switch(e){case StringFormat.RAW:return new StringData(utf8Bytes_(t));case StringFormat.BASE64:case StringFormat.BASE64URL:return new StringData(base64Bytes_(e,t));case StringFormat.DATA_URL:return new StringData(dataURLBytes_(t),dataURLContentType_(t))}throw unknown()}function utf8Bytes_(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(r);else if(r<=2047)t.push(192|r>>6,128|63&r);else if(55296==(64512&r))if(n<e.length-1&&56320==(64512&e.charCodeAt(n+1)))r=65536|(1023&r)<<10|1023&e.charCodeAt(++n),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r);else t.push(239,191,189);else 56320==(64512&r)?t.push(239,191,189):t.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(t)}function percentEncodedBytes_(e){var t;try{t=decodeURIComponent(e)}catch(e){throw invalidFormat(StringFormat.DATA_URL,"Malformed data URL.")}return utf8Bytes_(t)}function base64Bytes_(e,t){switch(e){case StringFormat.BASE64:var n=-1!==t.indexOf("-"),r=-1!==t.indexOf("_");if(n||r)throw invalidFormat(e,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case StringFormat.BASE64URL:var i=-1!==t.indexOf("+"),o=-1!==t.indexOf("/");if(i||o)throw invalidFormat(e,"Invalid character '"+(i?"+":"/")+"' found: is it base64 encoded?");t=t.replace(/-/g,"+").replace(/_/g,"/")}var a;try{a=atob(t)}catch(t){throw invalidFormat(e,"Invalid character found")}for(var s=new Uint8Array(a.length),u=0;u<a.length;u++)s[u]=a.charCodeAt(u);return s}var DataURLParts=function(){return function(e){this.base64=!1,this.contentType=null;var t=e.match(/^data:([^,]+)?,/);if(null===t)throw invalidFormat(StringFormat.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");var n=t[1]||null;null!=n&&(this.base64=endsWith(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-";base64".length):n),this.rest=e.substring(e.indexOf(",")+1)}}();function dataURLBytes_(e){var t=new DataURLParts(e);return t.base64?base64Bytes_(StringFormat.BASE64,t.rest):percentEncodedBytes_(t.rest)}function dataURLContentType_(e){return new DataURLParts(e).contentType}function endsWith(e,t){return!!(e.length>=t.length)&&e.substring(e.length-t.length)===t}var TaskEvent={STATE_CHANGED:"state_changed"},InternalTaskState={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},TaskState={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"},ErrorCode;function taskStateFromInternalTaskState(e){switch(e){case InternalTaskState.RUNNING:case InternalTaskState.PAUSING:case InternalTaskState.CANCELING:return TaskState.RUNNING;case InternalTaskState.PAUSED:return TaskState.PAUSED;case InternalTaskState.SUCCESS:return TaskState.SUCCESS;case InternalTaskState.CANCELED:return TaskState.CANCELED;case InternalTaskState.ERROR:default:return TaskState.ERROR}}function contains$3(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function forEach$2(e,t){for(var n in e)contains$3(e,n)&&t(n,e[n])}function clone$1(e){if(null==e)return{};var t={};return forEach$2(e,function(e,n){t[e]=n}),t}function make(e){return new Promise(e)}function resolve$1(e){return Promise.resolve(e)}function reject$1(e){return Promise.reject(e)}function isDef(e){return null!=e}function isJustDef(e){return void 0!==e}function isFunction(e){return"function"==typeof e}function isObject(e){return"object"==typeof e}function isNonNullObject$1(e){return isObject(e)&&null!==e}function isNonArrayObject(e){return isObject(e)&&!Array.isArray(e)}function isString(e){return"string"==typeof e||e instanceof String}function isNumber(e){return"number"==typeof e||e instanceof Number}function isNativeBlob(e){return isNativeBlobDefined()&&e instanceof Blob}function isNativeBlobDefined(){return"undefined"!=typeof Blob}!function(e){e[e.NO_ERROR=0]="NO_ERROR",e[e.NETWORK_ERROR=1]="NETWORK_ERROR",e[e.ABORT=2]="ABORT"}(ErrorCode||(ErrorCode={}));var NetworkXhrIo=function(){function e(){var e=this;this.sent_=!1,this.xhr_=new XMLHttpRequest,this.errorCode_=ErrorCode.NO_ERROR,this.sendPromise_=make(function(t,n){e.xhr_.addEventListener("abort",function(n){e.errorCode_=ErrorCode.ABORT,t(e)}),e.xhr_.addEventListener("error",function(n){e.errorCode_=ErrorCode.NETWORK_ERROR,t(e)}),e.xhr_.addEventListener("load",function(n){t(e)})})}return e.prototype.send=function(e,t,n,r){var i=this;if(this.sent_)throw internalError("cannot .send() more than once");(this.sent_=!0,this.xhr_.open(t,e,!0),isDef(r))&&forEach$2(r,function(e,t){i.xhr_.setRequestHeader(e,t.toString())});return isDef(n)?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_},e.prototype.getErrorCode=function(){if(!this.sent_)throw internalError("cannot .getErrorCode() before sending");return this.errorCode_},e.prototype.getStatus=function(){if(!this.sent_)throw internalError("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}},e.prototype.getResponseText=function(){if(!this.sent_)throw internalError("cannot .getResponseText() before sending");return this.xhr_.responseText},e.prototype.abort=function(){this.xhr_.abort()},e.prototype.getResponseHeader=function(e){return this.xhr_.getResponseHeader(e)},e.prototype.addUploadProgressListener=function(e){isDef(this.xhr_.upload)&&this.xhr_.upload.addEventListener("progress",e)},e.prototype.removeUploadProgressListener=function(e){isDef(this.xhr_.upload)&&this.xhr_.upload.removeEventListener("progress",e)},e}(),XhrIoPool=function(){function e(){}return e.prototype.createXhrIo=function(){return new NetworkXhrIo},e}();function jsonObjectOrNull(e){var t;try{t=JSON.parse(e)}catch(e){return null}return isNonArrayObject(t)?t:null}var Location=function(){function e(e,t){this.bucket=e,this.path_=t}return Object.defineProperty(e.prototype,"path",{get:function(){return this.path_},enumerable:!0,configurable:!0}),e.prototype.fullServerUrl=function(){var e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)},e.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},e.makeFromBucketSpec=function(t){var n;try{n=e.makeFromUrl(t)}catch(n){return new e(t,"")}if(""===n.path)return n;throw invalidDefaultBucket(t)},e.makeFromUrl=function(t){var n=null;for(var r=[{regex:new RegExp("^gs://([A-Za-z0-9.\\-]+)(/(.*))?$","i"),indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:new RegExp("^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/([A-Za-z0-9.\\-]+)/o(/([^?#]*).*)?$","i"),indices:{bucket:1,path:3},postModify:function(e){e.path_=decodeURIComponent(e.path)}}],i=0;i<r.length;i++){var o=r[i],a=o.regex.exec(t);if(a){var s=a[o.indices.bucket],u=a[o.indices.path];u||(u=""),n=new e(s,u),o.postModify(n);break}}if(null==n)throw invalidUrl(t);return n},e}();function parent(e){if(0==e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}function child(e,t){var n=t.split("/").filter(function(e){return e.length>0}).join("/");return 0===e.length?n:e+"/"+n}function lastComponent(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function makeNormalUrl(e){return domainBase+apiBaseUrl+e}function makeDownloadUrl(e){return downloadBase+apiBaseUrl+e}function makeUploadUrl(e){return domainBase+apiUploadBaseUrl+e}function makeQueryString(e){var t=encodeURIComponent,n="?";return forEach$2(e,function(e,r){var i=t(e)+"="+t(r);n=n+i+"&"}),n=n.slice(0,-1)}function noXform_(e,t){return t}var Mapping=function(){return function(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||noXform_}}(),mappings_=null;function xformPath(e){return!isString(e)||e.length<2?e:lastComponent(e=e)}function getMappings(){if(mappings_)return mappings_;var e=[];e.push(new Mapping("bucket")),e.push(new Mapping("generation")),e.push(new Mapping("metageneration")),e.push(new Mapping("name","fullPath",!0));var t=new Mapping("name");t.xform=function(e,t){return xformPath(t)},e.push(t);var n=new Mapping("size");return n.xform=function(e,t){return isDef(t)?+t:t},e.push(n),e.push(new Mapping("timeCreated")),e.push(new Mapping("updated")),e.push(new Mapping("md5Hash",null,!0)),e.push(new Mapping("cacheControl",null,!0)),e.push(new Mapping("contentDisposition",null,!0)),e.push(new Mapping("contentEncoding",null,!0)),e.push(new Mapping("contentLanguage",null,!0)),e.push(new Mapping("contentType",null,!0)),e.push(new Mapping("metadata","customMetadata",!0)),mappings_=e}function addRef(e,t){Object.defineProperty(e,"ref",{get:function(){var n=e.bucket,r=e.fullPath,i=new Location(n,r);return t.makeStorageReference(i)}})}function fromResource(e,t,n){for(var r={type:"file"},i=n.length,o=0;o<i;o++){var a=n[o];r[a.local]=a.xform(r,t[a.server])}return addRef(r,e),r}function fromResourceString(e,t,n){var r=jsonObjectOrNull(t);return null===r?null:fromResource(e,r,n)}function downloadUrlFromResourceString(e,t){var n=jsonObjectOrNull(t);if(null===n)return null;if(!isString(n.downloadTokens))return null;var r=n.downloadTokens;if(0===r.length)return null;var i=encodeURIComponent;return r.split(",").map(function(t){var n=e.bucket,r=e.fullPath;return makeDownloadUrl("/b/"+i(n)+"/o/"+i(r))+makeQueryString({alt:"media",token:t})})[0]}function toResourceString(e,t){for(var n={},r=t.length,i=0;i<r;i++){var o=t[i];o.writable&&(n[o.server]=e[o.local])}return JSON.stringify(n)}function metadataValidator(e){if(!(e&&isObject(e)))throw"Expected Metadata object.";for(var t in e){var n=e[t];if("customMetadata"===t){if(!isObject(n))throw"Expected object for 'customMetadata' mapping."}else if(isNonNullObject$1(n))throw"Mapping for '"+t+"' cannot be an object."}}function validate(e,t,n){for(var r=t.length,i=t.length,o=0;o<t.length;o++)if(t[o].optional){r=o;break}if(!(r<=n.length&&n.length<=i))throw invalidArgumentCount(r,i,e,n.length);for(o=0;o<n.length;o++)try{t[o].validator(n[o])}catch(t){throw t instanceof Error?invalidArgument(o,e,t.message):invalidArgument(o,e,t)}}var ArgSpec=function(){return function(e,t){var n=this;this.validator=function(t){n.optional&&!isJustDef(t)||e(t)},this.optional=!!t}}();function and_(e,t){return function(n){e(n),t(n)}}function stringSpec(e,t){function n(e){if(!isString(e))throw"Expected string."}var r;return r=e?and_(n,e):n,new ArgSpec(r,t)}function uploadDataSpec(){return new ArgSpec(function(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer||isNativeBlobDefined()&&e instanceof Blob))throw"Expected Blob or File."})}function metadataSpec(e){return new ArgSpec(metadataValidator,e)}function nonNegativeNumberSpec(){return new ArgSpec(function(e){if(!(isNumber(e)&&e>=0))throw"Expected a number 0 or greater."})}function looseObjectSpec(e,t){return new ArgSpec(function(t){if(!(null===t||isDef(t)&&t instanceof Object))throw"Expected an Object.";void 0!==e&&null!==e&&e(t)},t)}function nullFunctionSpec(e){return new ArgSpec(function(e){if(null!==e&&!isFunction(e))throw"Expected a Function."},e)}function getBlobBuilder(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function getBlob(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=getBlobBuilder();if(void 0!==n){for(var r=new n,i=0;i<e.length;i++)r.append(e[i]);return r.getBlob()}if(isNativeBlobDefined())return new Blob(e);throw Error("This browser doesn't seem to support creating Blobs")}function sliceBlob(e,t,n){return e.webkitSlice?e.webkitSlice(t,n):e.mozSlice?e.mozSlice(t,n):e.slice?e.slice(t,n):null}var FbsBlob=function(){function e(e,t){var n=0,r="";isNativeBlob(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}return e.prototype.size=function(){return this.size_},e.prototype.type=function(){return this.type_},e.prototype.slice=function(t,n){if(isNativeBlob(this.data_)){var r=sliceBlob(this.data_,t,n);return null===r?null:new e(r)}return new e(new Uint8Array(this.data_.buffer,t,n-t),!0)},e.getBlob=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];if(isNativeBlobDefined()){var r=t.map(function(t){return t instanceof e?t.data_:t});return new e(getBlob.apply(null,r))}var i=t.map(function(e){return isString(e)?dataFromString(StringFormat.RAW,e).data:e.data_}),o=0;i.forEach(function(e){o+=e.byteLength});var a=new Uint8Array(o),s=0;return i.forEach(function(e){for(var t=0;t<e.length;t++)a[s++]=e[t]}),new e(a,!0)},e.prototype.uploadData=function(){return this.data_},e}();function contains$1$1(e,t){return-1!==e.indexOf(t)}function clone$1$1(e){return Array.prototype.slice.call(e)}function remove(e,t){var n=e.indexOf(t);-1!==n&&e.splice(n,1)}var RequestInfo=function(){return function(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}();function handlerCheck(e){if(!e)throw unknown()}function metadataHandler(e,t){return function(n,r){var i=fromResourceString(e,r,t);return handlerCheck(null!==i),i}}function downloadUrlHandler(e,t){return function(n,r){var i=fromResourceString(e,r,t);return handlerCheck(null!==i),downloadUrlFromResourceString(i,r)}}function sharedErrorHandler(e){return function(t,n){var r;return(r=401===t.getStatus()?unauthenticated():402===t.getStatus()?quotaExceeded(e.bucket):403===t.getStatus()?unauthorized(e.path):n).setServerResponseProp(n.serverResponseProp()),r}}function objectErrorHandler(e){var t=sharedErrorHandler(e);return function(n,r){var i=t(n,r);return 404===n.getStatus()&&(i=objectNotFound(e.path)),i.setServerResponseProp(r.serverResponseProp()),i}}function getMetadata(e,t,n){var r=makeNormalUrl(t.fullServerUrl()),i=e.maxOperationRetryTime(),o=new RequestInfo(r,"GET",metadataHandler(e,n),i);return o.errorHandler=objectErrorHandler(t),o}function getDownloadUrl(e,t,n){var r=makeNormalUrl(t.fullServerUrl()),i=e.maxOperationRetryTime(),o=new RequestInfo(r,"GET",downloadUrlHandler(e,n),i);return o.errorHandler=objectErrorHandler(t),o}function updateMetadata(e,t,n,r){var i=makeNormalUrl(t.fullServerUrl()),o=toResourceString(n,r),a=e.maxOperationRetryTime(),s=new RequestInfo(i,"PATCH",metadataHandler(e,r),a);return s.headers={"Content-Type":"application/json; charset=utf-8"},s.body=o,s.errorHandler=objectErrorHandler(t),s}function deleteObject(e,t){var n=makeNormalUrl(t.fullServerUrl()),r=e.maxOperationRetryTime();var i=new RequestInfo(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=objectErrorHandler(t),i}function determineContentType_(e,t){return e&&e.contentType||t&&t.type()||"application/octet-stream"}function metadataForUpload_(e,t,n){var r=clone$1(n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=determineContentType_(null,t)),r}function multipartUpload(e,t,n,r,i){var o=t.bucketOnlyServerUrl(),a={"X-Goog-Upload-Protocol":"multipart"};var s=function(){for(var e="",t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();a["Content-Type"]="multipart/related; boundary="+s;var u=metadataForUpload_(t,r,i),c="--"+s+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+toResourceString(u,n)+"\r\n--"+s+"\r\nContent-Type: "+u.contentType+"\r\n\r\n",h="\r\n--"+s+"--",l=FbsBlob.getBlob(c,r,h);if(null===l)throw cannotSliceBlob();var d={name:u.fullPath},f=makeUploadUrl(o),p=e.maxUploadRetryTime(),m=new RequestInfo(f,"POST",metadataHandler(e,n),p);return m.urlParams=d,m.headers=a,m.body=l.uploadData(),m.errorHandler=sharedErrorHandler(t),m}var ResumableUploadStatus=function(){return function(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}();function checkResumeHeader_(e,t){var n;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){handlerCheck(!1)}return handlerCheck(contains$1$1(t||["active"],n)),n}function createResumableUpload(e,t,n,r,i){var o=t.bucketOnlyServerUrl(),a=metadataForUpload_(t,r,i),s={name:a.fullPath},u=makeUploadUrl(o),c={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":r.size(),"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},h=toResourceString(a,n),l=e.maxUploadRetryTime();var d=new RequestInfo(u,"POST",function(e,t){var n;checkResumeHeader_(e);try{n=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){handlerCheck(!1)}return handlerCheck(isString(n)),n},l);return d.urlParams=s,d.headers=c,d.body=h,d.errorHandler=sharedErrorHandler(t),d}function getResumableUploadStatus(e,t,n,r){var i=e.maxUploadRetryTime(),o=new RequestInfo(n,"POST",function(e,t){var n,i=checkResumeHeader_(e,["active","final"]);try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){handlerCheck(!1)}var o=parseInt(n,10);return handlerCheck(!isNaN(o)),new ResumableUploadStatus(o,r.size(),"final"===i)},i);return o.headers={"X-Goog-Upload-Command":"query"},o.errorHandler=sharedErrorHandler(t),o}var resumableUploadChunkSize=262144;function continueResumableUpload(e,t,n,r,i,o,a,s){var u=new ResumableUploadStatus(0,0);if(a?(u.current=a.current,u.total=a.total):(u.current=0,u.total=r.size()),r.size()!==u.total)throw serverFileWrongSize();var c=u.total-u.current,h=c;i>0&&(h=Math.min(h,i));var l=u.current,d=l+h,f={"X-Goog-Upload-Command":h===c?"upload, finalize":"upload","X-Goog-Upload-Offset":u.current},p=r.slice(l,d);if(null===p)throw cannotSliceBlob();var m=t.maxUploadRetryTime(),y=new RequestInfo(n,"POST",function(e,n){var i,a=checkResumeHeader_(e,["active","final"]),s=u.current+h,c=r.size();return i="final"===a?metadataHandler(t,o)(e,n):null,new ResumableUploadStatus(s,c,"final"===a,i)},m);return y.headers=f,y.body=p.uploadData(),y.progressCallback=s||null,y.errorHandler=sharedErrorHandler(e),y}var Observer=function(){return function(e,t,n){if(isFunction(e)||isDef(t)||isDef(n))this.next=e,this.error=t||null,this.complete=n||null;else{var r=e;this.next=r.next||null,this.error=r.error||null,this.complete=r.complete||null}}}(),UploadTaskSnapshot=function(){return function(e,t,n,r,i,o){this.bytesTransferred=e,this.totalBytes=t,this.state=n,this.metadata=r,this.task=i,this.ref=o}}();function async$1(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];resolve$1(!0).then(function(){e.apply(null,t)})}}var UploadTask=function(){function e(e,t,n,r,i,o){void 0===o&&(o=null);var a=this;this.transferred_=0,this.needToFetchStatus_=!1,this.needToFetchMetadata_=!1,this.observers_=[],this.error_=null,this.uploadUrl_=null,this.request_=null,this.chunkMultiplier_=1,this.resolve_=null,this.reject_=null,this.ref_=e,this.authWrapper_=t,this.location_=n,this.blob_=i,this.metadata_=o,this.mappings_=r,this.resumable_=this.shouldDoResumable_(this.blob_),this.state_=InternalTaskState.RUNNING,this.errorHandler_=function(e){a.request_=null,a.chunkMultiplier_=1,e.codeEquals(Code$1.CANCELED)?(a.needToFetchStatus_=!0,a.completeTransitions_()):(a.error_=e,a.transition_(InternalTaskState.ERROR))},this.metadataErrorHandler_=function(e){a.request_=null,e.codeEquals(Code$1.CANCELED)?a.completeTransitions_():(a.error_=e,a.transition_(InternalTaskState.ERROR))},this.promise_=make(function(e,t){a.resolve_=e,a.reject_=t,a.start_()}),this.promise_.then(null,function(){})}return e.prototype.makeProgressCallback_=function(){var e=this,t=this.transferred_;return function(n,r){e.updateProgress_(t+n)}},e.prototype.shouldDoResumable_=function(e){return e.size()>262144},e.prototype.start_=function(){this.state_===InternalTaskState.RUNNING&&null===this.request_&&(this.resumable_?null===this.uploadUrl_?this.createResumable_():this.needToFetchStatus_?this.fetchStatus_():this.needToFetchMetadata_?this.fetchMetadata_():this.continueUpload_():this.oneShotUpload_())},e.prototype.resolveToken_=function(e){var t=this;this.authWrapper_.getAuthToken().then(function(n){switch(t.state_){case InternalTaskState.RUNNING:e(n);break;case InternalTaskState.CANCELING:t.transition_(InternalTaskState.CANCELED);break;case InternalTaskState.PAUSING:t.transition_(InternalTaskState.PAUSED)}})},e.prototype.createResumable_=function(){var e=this;this.resolveToken_(function(t){var n=createResumableUpload(e.authWrapper_,e.location_,e.mappings_,e.blob_,e.metadata_),r=e.authWrapper_.makeRequest(n,t);e.request_=r,r.getPromise().then(function(t){e.request_=null,e.uploadUrl_=t,e.needToFetchStatus_=!1,e.completeTransitions_()},e.errorHandler_)})},e.prototype.fetchStatus_=function(){var e=this,t=this.uploadUrl_;this.resolveToken_(function(n){var r=getResumableUploadStatus(e.authWrapper_,e.location_,t,e.blob_),i=e.authWrapper_.makeRequest(r,n);e.request_=i,i.getPromise().then(function(t){t=t,e.request_=null,e.updateProgress_(t.current),e.needToFetchStatus_=!1,t.finalized&&(e.needToFetchMetadata_=!0),e.completeTransitions_()},e.errorHandler_)})},e.prototype.continueUpload_=function(){var e=this,t=resumableUploadChunkSize*this.chunkMultiplier_,n=new ResumableUploadStatus(this.transferred_,this.blob_.size()),r=this.uploadUrl_;this.resolveToken_(function(i){var o;try{o=continueResumableUpload(e.location_,e.authWrapper_,r,e.blob_,t,e.mappings_,n,e.makeProgressCallback_())}catch(t){return e.error_=t,void e.transition_(InternalTaskState.ERROR)}var a=e.authWrapper_.makeRequest(o,i);e.request_=a,a.getPromise().then(function(t){e.increaseMultiplier_(),e.request_=null,e.updateProgress_(t.current),t.finalized?(e.metadata_=t.metadata,e.transition_(InternalTaskState.SUCCESS)):e.completeTransitions_()},e.errorHandler_)})},e.prototype.increaseMultiplier_=function(){resumableUploadChunkSize*this.chunkMultiplier_<33554432&&(this.chunkMultiplier_*=2)},e.prototype.fetchMetadata_=function(){var e=this;this.resolveToken_(function(t){var n=getMetadata(e.authWrapper_,e.location_,e.mappings_),r=e.authWrapper_.makeRequest(n,t);e.request_=r,r.getPromise().then(function(t){e.request_=null,e.metadata_=t,e.transition_(InternalTaskState.SUCCESS)},e.metadataErrorHandler_)})},e.prototype.oneShotUpload_=function(){var e=this;this.resolveToken_(function(t){var n=multipartUpload(e.authWrapper_,e.location_,e.mappings_,e.blob_,e.metadata_),r=e.authWrapper_.makeRequest(n,t);e.request_=r,r.getPromise().then(function(t){e.request_=null,e.metadata_=t,e.updateProgress_(e.blob_.size()),e.transition_(InternalTaskState.SUCCESS)},e.errorHandler_)})},e.prototype.updateProgress_=function(e){var t=this.transferred_;this.transferred_=e,this.transferred_!==t&&this.notifyObservers_()},e.prototype.transition_=function(e){if(this.state_!==e)switch(e){case InternalTaskState.CANCELING:case InternalTaskState.PAUSING:this.state_=e,null!==this.request_&&this.request_.cancel();break;case InternalTaskState.RUNNING:var t=this.state_===InternalTaskState.PAUSED;this.state_=e,t&&(this.notifyObservers_(),this.start_());break;case InternalTaskState.PAUSED:this.state_=e,this.notifyObservers_();break;case InternalTaskState.CANCELED:this.error_=canceled(),this.state_=e,this.notifyObservers_();break;case InternalTaskState.ERROR:case InternalTaskState.SUCCESS:this.state_=e,this.notifyObservers_()}},e.prototype.completeTransitions_=function(){switch(this.state_){case InternalTaskState.PAUSING:this.transition_(InternalTaskState.PAUSED);break;case InternalTaskState.CANCELING:this.transition_(InternalTaskState.CANCELED);break;case InternalTaskState.RUNNING:this.start_()}},Object.defineProperty(e.prototype,"snapshot",{get:function(){var e=taskStateFromInternalTaskState(this.state_);return new UploadTaskSnapshot(this.transferred_,this.blob_.size(),e,this.metadata_,this,this.ref_)},enumerable:!0,configurable:!0}),e.prototype.on=function(e,t,n,r){void 0===t&&(t=void 0),void 0===n&&(n=void 0),void 0===r&&(r=void 0);var i="Expected a function or an Object with one of `next`, `error`, `complete` properties.",o=nullFunctionSpec(!0).validator,a=looseObjectSpec(null,!0).validator;function s(e){try{return void o(e)}catch(e){}try{if(a(e),!(isJustDef(e.next)||isJustDef(e.error)||isJustDef(e.complete)))throw"";return}catch(e){throw i}}validate("on",[stringSpec(function(t){if(e!==TaskEvent.STATE_CHANGED)throw"Expected one of the event types: ["+TaskEvent.STATE_CHANGED+"]."}),looseObjectSpec(s,!0),nullFunctionSpec(!0),nullFunctionSpec(!0)],arguments);var u=this;function c(e){return function(t,n,i){null!==e&&validate("on",e,arguments);var o=new Observer(t,n,r);return u.addObserver_(o),function(){u.removeObserver_(o)}}}var h=[looseObjectSpec(function(e){if(null===e)throw i;s(e)}),nullFunctionSpec(!0),nullFunctionSpec(!0)];return!(isJustDef(t)||isJustDef(n)||isJustDef(r))?c(h):c(null)(t,n,r)},e.prototype.then=function(e,t){return this.promise_.then(e,t)},e.prototype.catch=function(e){return this.then(null,e)},e.prototype.addObserver_=function(e){this.observers_.push(e),this.notifyObserver_(e)},e.prototype.removeObserver_=function(e){remove(this.observers_,e)},e.prototype.notifyObservers_=function(){var e=this;this.finishPromise_(),clone$1$1(this.observers_).forEach(function(t){e.notifyObserver_(t)})},e.prototype.finishPromise_=function(){if(null!==this.resolve_){var e=!0;switch(taskStateFromInternalTaskState(this.state_)){case TaskState.SUCCESS:async$1(this.resolve_.bind(null,this.snapshot))();break;case TaskState.CANCELED:case TaskState.ERROR:async$1(this.reject_.bind(null,this.error_))();break;default:e=!1}e&&(this.resolve_=null,this.reject_=null)}},e.prototype.notifyObserver_=function(e){switch(taskStateFromInternalTaskState(this.state_)){case TaskState.RUNNING:case TaskState.PAUSED:null!==e.next&&async$1(e.next.bind(e,this.snapshot))();break;case TaskState.SUCCESS:null!==e.complete&&async$1(e.complete.bind(e))();break;case TaskState.CANCELED:case TaskState.ERROR:null!==e.error&&async$1(e.error.bind(e,this.error_))();break;default:null!==e.error&&async$1(e.error.bind(e,this.error_))()}},e.prototype.resume=function(){validate("resume",[],arguments);var e=this.state_===InternalTaskState.PAUSED||this.state_===InternalTaskState.PAUSING;return e&&this.transition_(InternalTaskState.RUNNING),e},e.prototype.pause=function(){validate("pause",[],arguments);var e=this.state_===InternalTaskState.RUNNING;return e&&this.transition_(InternalTaskState.PAUSING),e},e.prototype.cancel=function(){validate("cancel",[],arguments);var e=this.state_===InternalTaskState.RUNNING||this.state_===InternalTaskState.PAUSING;return e&&this.transition_(InternalTaskState.CANCELING),e},e}(),Reference$1=function(){function e(e,t){this.authWrapper=e,this.location=t instanceof Location?t:Location.makeFromUrl(t)}return e.prototype.toString=function(){return validate("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},e.prototype.newRef=function(t,n){return new e(t,n)},e.prototype.mappings=function(){return getMappings()},e.prototype.child=function(e){validate("child",[stringSpec()],arguments);var t=child(this.location.path,e),n=new Location(this.location.bucket,t);return this.newRef(this.authWrapper,n)},Object.defineProperty(e.prototype,"parent",{get:function(){var e=parent(this.location.path);if(null===e)return null;var t=new Location(this.location.bucket,e);return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"root",{get:function(){var e=new Location(this.location.bucket,"");return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return lastComponent(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),e.prototype.put=function(e,t){return void 0===t&&(t=null),validate("put",[uploadDataSpec(),metadataSpec(!0)],arguments),this.throwIfRoot_("put"),new UploadTask(this,this.authWrapper,this.location,this.mappings(),new FbsBlob(e),t)},e.prototype.putString=function(e,t,n){void 0===t&&(t=StringFormat.RAW),validate("putString",[stringSpec(),stringSpec(formatValidator,!0),metadataSpec(!0)],arguments),this.throwIfRoot_("putString");var r=dataFromString(t,e),i=clone$1(n);return!isDef(i.contentType)&&isDef(r.contentType)&&(i.contentType=r.contentType),new UploadTask(this,this.authWrapper,this.location,this.mappings(),new FbsBlob(r.data,!0),i)},e.prototype.delete=function(){validate("delete",[],arguments),this.throwIfRoot_("delete");var e=this;return this.authWrapper.getAuthToken().then(function(t){var n=deleteObject(e.authWrapper,e.location);return e.authWrapper.makeRequest(n,t).getPromise()})},e.prototype.getMetadata=function(){validate("getMetadata",[],arguments),this.throwIfRoot_("getMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(t){var n=getMetadata(e.authWrapper,e.location,e.mappings());return e.authWrapper.makeRequest(n,t).getPromise()})},e.prototype.updateMetadata=function(e){validate("updateMetadata",[metadataSpec()],arguments),this.throwIfRoot_("updateMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(n){var r=updateMetadata(t.authWrapper,t.location,e,t.mappings());return t.authWrapper.makeRequest(r,n).getPromise()})},e.prototype.getDownloadURL=function(){validate("getDownloadURL",[],arguments),this.throwIfRoot_("getDownloadURL");var e=this;return this.authWrapper.getAuthToken().then(function(t){var n=getDownloadUrl(e.authWrapper,e.location,e.mappings());return e.authWrapper.makeRequest(n,t).getPromise().then(function(e){if(null===e)throw noDownloadURL();return e})})},e.prototype.throwIfRoot_=function(e){if(""===this.location.path)throw invalidRootOperation(e)},e}(),FailRequest=function(){function e(e){this.promise_=reject$1(e)}return e.prototype.getPromise=function(){return this.promise_},e.prototype.cancel=function(e){void 0===e&&(e=!1)},e}(),RequestMap=function(){function e(){this.map_={},this.id_=minSafeInteger}return e.prototype.addRequest=function(e){var t=this.id_;this.id_++,this.map_[t]=e;var n=this;function r(){delete n.map_[t]}e.getPromise().then(r,r)},e.prototype.clear=function(){forEach$2(this.map_,function(e,t){t&&t.cancel(!0)}),this.map_={}},e}(),AuthWrapper=function(){function e(t,n,r,i,o){if(this.bucket_=null,this.deleted_=!1,this.app_=t,null!==this.app_){var a=this.app_.options;isDef(a)&&(this.bucket_=e.extractBucket_(a))}this.storageRefMaker_=n,this.requestMaker_=r,this.pool_=o,this.service_=i,this.maxOperationRetryTime_=defaultMaxOperationRetryTime,this.maxUploadRetryTime_=defaultMaxUploadRetryTime,this.requestMap_=new RequestMap}return e.extractBucket_=function(e){var t=e[configOption]||null;return null==t?null:Location.makeFromBucketSpec(t).bucket},e.prototype.getAuthToken=function(){return null!==this.app_&&isDef(this.app_.INTERNAL)&&isDef(this.app_.INTERNAL.getToken)?this.app_.INTERNAL.getToken().then(function(e){return null!==e?e.accessToken:null},function(e){return null}):resolve$1(null)},e.prototype.bucket=function(){if(this.deleted_)throw appDeleted();return this.bucket_},e.prototype.service=function(){return this.service_},e.prototype.makeStorageReference=function(e){return this.storageRefMaker_(this,e)},e.prototype.makeRequest=function(e,t){if(this.deleted_)return new FailRequest(appDeleted());var n=this.requestMaker_(e,t,this.pool_);return this.requestMap_.addRequest(n),n},e.prototype.deleteApp=function(){this.deleted_=!0,this.app_=null,this.requestMap_.clear()},e.prototype.maxUploadRetryTime=function(){return this.maxUploadRetryTime_},e.prototype.setMaxUploadRetryTime=function(e){this.maxUploadRetryTime_=e},e.prototype.maxOperationRetryTime=function(){return this.maxOperationRetryTime_},e.prototype.setMaxOperationRetryTime=function(e){this.maxOperationRetryTime_=e},e}();function start(e,t,n){var r=1,i=null,o=!1,a=0;function s(){return 2===a}var u=!1;function c(){u||(u=!0,t.apply(null,arguments))}function h(t){i=setTimeout(function(){i=null,e(l,s())},t)}function l(e){for(var t,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];u||(e?c.apply(null,arguments):s()||o?c.apply(null,arguments):(r<64&&(r*=2),1===a?(a=2,t=0):t=1e3*(r+Math.random()),h(t)))}var d=!1;function f(e){d||(d=!0,u||(null!==i?(e||(a=2),clearTimeout(i),h(0)):e||(a=1)))}return h(0),setTimeout(function(){o=!0,f(!0)},n),f}function stop(e){e(!1)}var NetworkRequest=function(){function e(e,t,n,r,i,o,a,s,u,c,h){this.pendingXhr_=null,this.backoffId_=null,this.resolve_=null,this.reject_=null,this.canceled_=!1,this.appDelete_=!1,this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i.slice(),this.additionalRetryCodes_=o.slice(),this.callback_=a,this.errorCallback_=s,this.progressCallback_=c,this.timeout_=u,this.pool_=h;var l=this;this.promise_=make(function(e,t){l.resolve_=e,l.reject_=t,l.start_()})}return e.prototype.start_=function(){var e=this;function t(t,n){var r,i=e.resolve_,o=e.reject_,a=n.xhr;if(n.wasSuccessCode)try{var s=e.callback_(a,a.getResponseText());isJustDef(s)?i(s):i()}catch(e){o(e)}else null!==a?((r=unknown()).setServerResponseProp(a.getResponseText()),e.errorCallback_?o(e.errorCallback_(a,r)):o(r)):n.canceled?o(r=e.appDelete_?appDeleted():canceled()):o(r=retryLimitExceeded())}this.canceled_?t(0,new RequestEndStatus(!1,null,!0)):this.backoffId_=start(function(t,n){if(n)t(!1,new RequestEndStatus(!1,null,!0));else{var r=e.pool_.createXhrIo();e.pendingXhr_=r,null!==e.progressCallback_&&r.addUploadProgressListener(i),r.send(e.url_,e.method_,e.body_,e.headers_).then(function(n){null!==e.progressCallback_&&n.removeUploadProgressListener(i),e.pendingXhr_=null;var r=(n=n).getErrorCode()===ErrorCode.NO_ERROR,o=n.getStatus();if(r&&!e.isRetryStatusCode_(o)){var a=contains$1$1(e.successCodes_,o);t(!0,new RequestEndStatus(a,n))}else{var s=n.getErrorCode()===ErrorCode.ABORT;t(!1,new RequestEndStatus(!1,null,s))}})}function i(t){var n=t.loaded,r=t.lengthComputable?t.total:-1;null!==e.progressCallback_&&e.progressCallback_(n,r)}},t,this.timeout_)},e.prototype.getPromise=function(){return this.promise_},e.prototype.cancel=function(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&stop(this.backoffId_),null!==this.pendingXhr_&&this.pendingXhr_.abort()},e.prototype.isRetryStatusCode_=function(e){var t=e>=500&&e<600,n=contains$1$1([408,429],e),r=contains$1$1(this.additionalRetryCodes_,e);return t||n||r},e}(),RequestEndStatus=function(){return function(e,t,n){this.wasSuccessCode=e,this.xhr=t,this.canceled=!!n}}();function addAuthHeader_(e,t){null!==t&&t.length>0&&(e.Authorization="Firebase "+t)}function addVersionHeader_(e){var t=void 0!==firebase?firebase.SDK_VERSION:"AppManager";e["X-Firebase-Storage-Version"]="webjs/"+t}function makeRequest(e,t,n){var r=makeQueryString(e.urlParams),i=e.url+r,o=clone$1(e.headers);return addAuthHeader_(o,t),addVersionHeader_(o),new NetworkRequest(i,e.method,o,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,n)}var Service$1=function(){function e(e,t,n){if(this.bucket_=null,this.authWrapper_=new AuthWrapper(e,function(e,t){return new Reference$1(e,t)},makeRequest,this,t),this.app_=e,null!=n)this.bucket_=Location.makeFromBucketSpec(n);else{var r=this.authWrapper_.bucket();null!=r&&(this.bucket_=new Location(r,""))}this.internals_=new ServiceInternals(this)}return e.prototype.ref=function(e){if(validate("ref",[stringSpec(function(e){if(/^[A-Za-z]+:\/\//.test(e))throw"Expected child path but got a URL, use refFromURL instead."},!0)],arguments),null==this.bucket_)throw new Error("No Storage Bucket defined in Firebase Options.");var t=new Reference$1(this.authWrapper_,this.bucket_);return null!=e?t.child(e):t},e.prototype.refFromURL=function(e){return validate("refFromURL",[stringSpec(function(e){if(!/^[A-Za-z]+:\/\//.test(e))throw"Expected full URL but got a child path, use ref instead.";try{Location.makeFromUrl(e)}catch(e){throw"Expected valid full URL but got an invalid one."}},!1)],arguments),new Reference$1(this.authWrapper_,e)},Object.defineProperty(e.prototype,"maxUploadRetryTime",{get:function(){return this.authWrapper_.maxUploadRetryTime()},enumerable:!0,configurable:!0}),e.prototype.setMaxUploadRetryTime=function(e){validate("setMaxUploadRetryTime",[nonNegativeNumberSpec()],arguments),this.authWrapper_.setMaxUploadRetryTime(e)},Object.defineProperty(e.prototype,"maxOperationRetryTime",{get:function(){return this.authWrapper_.maxOperationRetryTime()},enumerable:!0,configurable:!0}),e.prototype.setMaxOperationRetryTime=function(e){validate("setMaxOperationRetryTime",[nonNegativeNumberSpec()],arguments),this.authWrapper_.setMaxOperationRetryTime(e)},Object.defineProperty(e.prototype,"app",{get:function(){return this.app_},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"INTERNAL",{get:function(){return this.internals_},enumerable:!0,configurable:!0}),e}(),ServiceInternals=function(){function e(e){this.service_=e}return e.prototype.delete=function(){return this.service_.authWrapper_.deleteApp(),resolve$1(void 0)},e}(),STORAGE_TYPE="storage";function factory$1(e,t,n){return new Service$1(e,new XhrIoPool,n)}function registerStorage(e){var t={TaskState:TaskState,TaskEvent:TaskEvent,StringFormat:StringFormat,Storage:Service$1,Reference:Reference$1};e.INTERNAL.registerService(STORAGE_TYPE,factory$1,t,void 0,!0)}return registerStorage(firebase),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),firebase});