2018-12-22 23:30:39 +01:00

2 lines
786 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.firebase=e()}(this,function(){"use strict";!function(t){if(!t.fetch){var e={searchParams:"URLSearchParams"in t,iterable:"Symbol"in t&&"iterator"in Symbol,blob:"FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in t,arrayBuffer:"ArrayBuffer"in t};if(e.arrayBuffer)var n=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],r=function(t){return t&&DataView.prototype.isPrototypeOf(t)},i=ArrayBuffer.isView||function(t){return t&&n.indexOf(Object.prototype.toString.call(t))>-1};h.prototype.append=function(t,e){t=a(t),e=u(e);var n=this.map[t];this.map[t]=n?n+","+e:e},h.prototype.delete=function(t){delete this.map[a(t)]},h.prototype.get=function(t){return t=a(t),this.has(t)?this.map[t]:null},h.prototype.has=function(t){return this.map.hasOwnProperty(a(t))},h.prototype.set=function(t,e){this.map[a(t)]=u(e)},h.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)},h.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),c(t)},h.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),c(t)},h.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),c(t)},e.iterable&&(h.prototype[Symbol.iterator]=h.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];m.prototype.clone=function(){return new m(this,{body:this._bodyInit})},y.call(m.prototype),y.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 t=new v(null,{status:0,statusText:""});return t.type="error",t};var s=[301,302,303,307,308];v.redirect=function(t,e){if(-1===s.indexOf(e))throw new RangeError("Invalid status code");return new v(null,{status:e,headers:{location:t}})},t.Headers=h,t.Request=m,t.Response=v,t.fetch=function(t,n){return new Promise(function(r,i){var o=new m(t,n),s=new XMLHttpRequest;s.onload=function(){var t,e,n={status:s.status,statusText:s.statusText,headers:(t=s.getAllResponseHeaders()||"",e=new h,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(t){var n=t.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();e.append(r,i)}}),e)};n.url="responseURL"in s?s.responseURL:n.headers.get("X-Request-URL");var i="response"in s?s.response:s.responseText;r(new v(i,n))},s.onerror=function(){i(new TypeError("Network request failed"))},s.ontimeout=function(){i(new TypeError("Network request failed"))},s.open(o.method,o.url,!0),"include"===o.credentials?s.withCredentials=!0:"omit"===o.credentials&&(s.withCredentials=!1),"responseType"in s&&e.blob&&(s.responseType="blob"),o.headers.forEach(function(t,e){s.setRequestHeader(e,t)}),s.send(void 0===o._bodyInit?null:o._bodyInit)})},t.fetch.polyfill=!0}function a(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function u(t){return"string"!=typeof t&&(t=String(t)),t}function c(t){var n={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return e.iterable&&(n[Symbol.iterator]=function(){return n}),n}function h(t){this.map={},t instanceof h?t.forEach(function(t,e){this.append(e,t)},this):Array.isArray(t)?t.forEach(function(t){this.append(t[0],t[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function l(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function f(t){return new Promise(function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}})}function p(t){var e=new FileReader,n=f(e);return e.readAsArrayBuffer(t),n}function d(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function y(){return this.bodyUsed=!1,this._initBody=function(t){if(this._bodyInit=t,t)if("string"==typeof t)this._bodyText=t;else if(e.blob&&Blob.prototype.isPrototypeOf(t))this._bodyBlob=t;else if(e.formData&&FormData.prototype.isPrototypeOf(t))this._bodyFormData=t;else if(e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t))this._bodyText=t.toString();else if(e.arrayBuffer&&e.blob&&r(t))this._bodyArrayBuffer=d(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!e.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(t)&&!i(t))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=d(t)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},e.blob&&(this.blob=function(){var t=l(this);if(t)return t;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(p)}),this.text=function(){var t,e,n,r=l(this);if(r)return r;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,n=f(e),e.readAsText(t),n;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r<e.length;r++)n[r]=String.fromCharCode(e[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},e.formData&&(this.formData=function(){return this.text().then(g)}),this.json=function(){return this.text().then(JSON.parse)},this}function m(t,e){var n,r,i=(e=e||{}).body;if(t instanceof m){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new h(t.headers)),this.method=t.method,this.mode=t.mode,i||null==t._bodyInit||(i=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new h(e.headers)),this.method=(n=e.method||this.method||"GET",r=n.toUpperCase(),o.indexOf(r)>-1?r:n),this.mode=e.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(t){var e=new FormData;return t.trim().split("&").forEach(function(t){if(t){var n=t.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(r),decodeURIComponent(i))}}),e}function v(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new h(e.headers),this.url=e.url||"",this._initBody(t)}}("undefined"!=typeof self?self:void 0);var t=setTimeout;function e(){}function n(t){if(!(this instanceof n))throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],a(t,this)}function r(t,e){for(;3===t._state;)t=t._value;0!==t._state?(t._handled=!0,n._immediateFn(function(){var n=1===t._state?e.onFulfilled:e.onRejected;if(null!==n){var r;try{r=n(t._value)}catch(t){return void o(e.promise,t)}i(e.promise,r)}else(1===t._state?i:o)(e.promise,t._value)})):t._deferreds.push(e)}function i(t,e){try{if(e===t)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"==typeof e||"function"==typeof e)){var r=e.then;if(e instanceof n)return t._state=3,t._value=e,void s(t);if("function"==typeof r)return void a((i=r,u=e,function(){i.apply(u,arguments)}),t)}t._state=1,t._value=e,s(t)}catch(e){o(t,e)}var i,u}function o(t,e){t._state=2,t._value=e,s(t)}function s(t){2===t._state&&0===t._deferreds.length&&n._immediateFn(function(){t._handled||n._unhandledRejectionFn(t._value)});for(var e=0,i=t._deferreds.length;e<i;e++)r(t,t._deferreds[e]);t._deferreds=null}function a(t,e){var n=!1;try{t(function(t){n||(n=!0,i(e,t))},function(t){n||(n=!0,o(e,t))})}catch(t){if(n)return;n=!0,o(e,t)}}n.prototype.catch=function(t){return this.then(null,t)},n.prototype.then=function(t,n){var i=new this.constructor(e);return r(this,new function(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}(t,n,i)),i},n.prototype.finally=function(t){var e=this.constructor;return this.then(function(n){return e.resolve(t()).then(function(){return n})},function(n){return e.resolve(t()).then(function(){return e.reject(n)})})},n.all=function(t){return new n(function(e,n){if(!t||void 0===t.length)throw new TypeError("Promise.all accepts an array");var r=Array.prototype.slice.call(t);if(0===r.length)return e([]);var i=r.length;function o(t,s){try{if(s&&("object"==typeof s||"function"==typeof s)){var a=s.then;if("function"==typeof a)return void a.call(s,function(e){o(t,e)},n)}r[t]=s,0==--i&&e(r)}catch(t){n(t)}}for(var s=0;s<r.length;s++)o(s,r[s])})},n.resolve=function(t){return t&&"object"==typeof t&&t.constructor===n?t:new n(function(e){e(t)})},n.reject=function(t){return new n(function(e,n){n(t)})},n.race=function(t){return new n(function(e,n){for(var r=0,i=t.length;r<i;r++)t[r].then(e,n)})},n._immediateFn="function"==typeof setImmediate&&function(t){setImmediate(t)}||function(e){t(e,0)},n._unhandledRejectionFn=function(t){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",t)};var u=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 c(t,e){return t(e={exports:{}},e.exports),e.exports}u.Promise||(u.Promise=n);var h=c(function(t){var e=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=e)}),l=c(function(t){var e=t.exports={version:"2.5.5"};"number"==typeof __e&&(__e=e)}),f=(l.version,function(t){return"object"==typeof t?null!==t:"function"==typeof t}),p=function(t){if(!f(t))throw TypeError(t+" is not an object!");return t},d=function(t){try{return!!t()}catch(t){return!0}},y=!d(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),m=h.document,g=f(m)&&f(m.createElement),v=function(t){return g?m.createElement(t):{}},b=!y&&!d(function(){return 7!=Object.defineProperty(v("div"),"a",{get:function(){return 7}}).a}),_=function(t,e){if(!f(t))return t;var n,r;if(e&&"function"==typeof(n=t.toString)&&!f(r=n.call(t)))return r;if("function"==typeof(n=t.valueOf)&&!f(r=n.call(t)))return r;if(!e&&"function"==typeof(n=t.toString)&&!f(r=n.call(t)))return r;throw TypeError("Can't convert object to primitive value")},w=Object.defineProperty,E={f:y?Object.defineProperty:function(t,e,n){if(p(t),e=_(e,!0),p(n),b)try{return w(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},T=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},S=y?function(t,e,n){return E.f(t,e,T(1,n))}:function(t,e,n){return t[e]=n,t},I={}.hasOwnProperty,C=function(t,e){return I.call(t,e)},N=0,D=Math.random(),A=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++N+D).toString(36))},k=c(function(t){var e=A("src"),n=Function.toString,r=(""+n).split("toString");l.inspectSource=function(t){return n.call(t)},(t.exports=function(t,n,i,o){var s="function"==typeof i;s&&(C(i,"name")||S(i,"name",n)),t[n]!==i&&(s&&(C(i,e)||S(i,e,t[n]?""+t[n]:r.join(String(n)))),t===h?t[n]=i:o?t[n]?t[n]=i:S(t,n,i):(delete t[n],S(t,n,i)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[e]||n.call(this)})}),R=function(t,e,n){if(function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!")}(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}},O=function(t,e,n){var r,i,o,s,a=t&O.F,u=t&O.G,c=t&O.S,f=t&O.P,p=t&O.B,d=u?h:c?h[e]||(h[e]={}):(h[e]||{}).prototype,y=u?l:l[e]||(l[e]={}),m=y.prototype||(y.prototype={});for(r in u&&(n=e),n)o=((i=!a&&d&&void 0!==d[r])?d:n)[r],s=p&&i?R(o,h):f&&"function"==typeof o?R(Function.call,o):o,d&&k(d,r,o,t&O.U),y[r]!=o&&S(y,r,s),f&&m[r]!=o&&(m[r]=o)};h.core=l,O.F=1,O.G=2,O.S=4,O.P=8,O.B=16,O.W=32,O.U=64,O.R=128;var P=O,L={}.toString,M=function(t){return L.call(t).slice(8,-1)},x=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==M(t)?t.split(""):Object(t)},F=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t},U=function(t){return Object(F(t))},q=Math.ceil,B=Math.floor,V=function(t){return isNaN(t=+t)?0:(t>0?B:q)(t)},W=Math.min,j=function(t){return t>0?W(V(t),9007199254740991):0},K=Array.isArray||function(t){return"Array"==M(t)},Q=h["__core-js_shared__"]||(h["__core-js_shared__"]={}),H=function(t){return Q[t]||(Q[t]={})},G=c(function(t){var e=H("wks"),n=h.Symbol,r="function"==typeof n;(t.exports=function(t){return e[t]||(e[t]=r&&n[t]||(r?n:A)("Symbol."+t))}).store=e}),z=G("species"),Y=function(t,e){return new(function(t){var e;return K(t)&&("function"!=typeof(e=t.constructor)||e!==Array&&!K(e.prototype)||(e=void 0),f(e)&&null===(e=e[z])&&(e=void 0)),void 0===e?Array:e}(t))(e)},X=function(t,e){var n=1==t,r=2==t,i=3==t,o=4==t,s=6==t,a=5==t||s,u=e||Y;return function(e,c,h){for(var l,f,p=U(e),d=x(p),y=R(c,h,3),m=j(d.length),g=0,v=n?u(e,m):r?u(e,0):void 0;m>g;g++)if((a||g in d)&&(f=y(l=d[g],g,p),t))if(n)v[g]=f;else if(f)switch(t){case 3:return!0;case 5:return l;case 6:return g;case 2:v.push(l)}else if(o)return!1;return s?-1:i||o?o:v}},J=G("unscopables"),$=Array.prototype;void 0==$[J]&&S($,J,{});var Z=function(t){$[J][t]=!0},tt=X(5),et=!0;"find"in[]&&Array(1).find(function(){et=!1}),P(P.P+P.F*et,"Array",{find:function(t){return tt(this,t,arguments.length>1?arguments[1]:void 0)}}),Z("find");l.Array.find;var nt=X(6),rt=!0;"findIndex"in[]&&Array(1).findIndex(function(){rt=!1}),P(P.P+P.F*rt,"Array",{findIndex:function(t){return nt(this,t,arguments.length>1?arguments[1]:void 0)}}),Z("findIndex");l.Array.findIndex;var it,ot=function(t){return x(F(t))},st=Math.max,at=Math.min,ut=H("keys"),ct=function(t){return ut[t]||(ut[t]=A(t))},ht=(it=!1,function(t,e,n){var r,i=ot(t),o=j(i.length),s=function(t,e){return(t=V(t))<0?st(t+e,0):at(t,e)}(n,o);if(it&&e!=e){for(;o>s;)if((r=i[s++])!=r)return!0}else for(;o>s;s++)if((it||s in i)&&i[s]===e)return it||s||0;return!it&&-1}),lt=ct("IE_PROTO"),ft=function(t,e){var n,r=ot(t),i=0,o=[];for(n in r)n!=lt&&C(r,n)&&o.push(n);for(;e.length>i;)C(r,n=e[i++])&&(~ht(o,n)||o.push(n));return o},pt="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),dt=Object.keys||function(t){return ft(t,pt)},yt={f:Object.getOwnPropertySymbols},mt={f:{}.propertyIsEnumerable},gt=Object.assign,vt=!gt||d(function(){var t={},e={},n=Symbol(),r="abcdefghijklmnopqrst";return t[n]=7,r.split("").forEach(function(t){e[t]=t}),7!=gt({},t)[n]||Object.keys(gt({},e)).join("")!=r})?function(t,e){for(var n=U(t),r=arguments.length,i=1,o=yt.f,s=mt.f;r>i;)for(var a,u=x(arguments[i++]),c=o?dt(u).concat(o(u)):dt(u),h=c.length,l=0;h>l;)s.call(u,a=c[l++])&&(n[a]=u[a]);return n}:gt;P(P.S+P.F,"Object",{assign:vt});l.Object.assign;var bt=G("match"),_t=function(t,e,n){if(f(r=e)&&(void 0!==(i=r[bt])?i:"RegExp"==M(r)))throw TypeError("String#"+n+" doesn't accept regex!");var r,i;return String(F(t))},wt=G("match"),Et="".startsWith;P(P.P+P.F*function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[wt]=!1,!"/./"[t](e)}catch(t){}}return!0}("startsWith"),"String",{startsWith:function(t){var e=_t(this,t,"startsWith"),n=j(Math.min(arguments.length>1?arguments[1]:void 0,e.length)),r=String(t);return Et?Et.call(e,r,n):e.slice(n,n+r.length)===r}});l.String.startsWith;P(P.P,"String",{repeat:function(t){var e=String(F(this)),n="",r=V(t);if(r<0||r==1/0)throw RangeError("Count can't be negative");for(;r>0;(r>>>=1)&&(e+=e))1&r&&(n+=e);return n}});l.String.repeat;var Tt=c(function(t){var e=A("meta"),n=E.f,r=0,i=Object.isExtensible||function(){return!0},o=!d(function(){return i(Object.preventExtensions({}))}),s=function(t){n(t,e,{value:{i:"O"+ ++r,w:{}}})},a=t.exports={KEY:e,NEED:!1,fastKey:function(t,n){if(!f(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!C(t,e)){if(!i(t))return"F";if(!n)return"E";s(t)}return t[e].i},getWeak:function(t,n){if(!C(t,e)){if(!i(t))return!0;if(!n)return!1;s(t)}return t[e].w},onFreeze:function(t){return o&&a.NEED&&i(t)&&!C(t,e)&&s(t),t}}}),St=(Tt.KEY,Tt.NEED,Tt.fastKey,Tt.getWeak,Tt.onFreeze,E.f),It=G("toStringTag"),Ct=function(t,e,n){t&&!C(t=n?t:t.prototype,It)&&St(t,It,{configurable:!0,value:e})},Nt={f:G},Dt=E.f,At=function(t){var e=l.Symbol||(l.Symbol=h.Symbol||{});"_"==t.charAt(0)||t in e||Dt(e,t,{value:Nt.f(t)})},kt=y?Object.defineProperties:function(t,e){p(t);for(var n,r=dt(e),i=r.length,o=0;i>o;)E.f(t,n=r[o++],e[n]);return t},Rt=h.document,Ot=Rt&&Rt.documentElement,Pt=ct("IE_PROTO"),Lt=function(){},Mt=function(){var t,e=v("iframe"),n=pt.length;for(e.style.display="none",Ot.appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),Mt=t.F;n--;)delete Mt.prototype[pt[n]];return Mt()},xt=Object.create||function(t,e){var n;return null!==t?(Lt.prototype=p(t),n=new Lt,Lt.prototype=null,n[Pt]=t):n=Mt(),void 0===e?n:kt(n,e)},Ft=pt.concat("length","prototype"),Ut={f:Object.getOwnPropertyNames||function(t){return ft(t,Ft)}},qt=Ut.f,Bt={}.toString,Vt="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],Wt={f:function(t){return Vt&&"[object Window]"==Bt.call(t)?function(t){try{return qt(t)}catch(t){return Vt.slice()}}(t):qt(ot(t))}},jt=Object.getOwnPropertyDescriptor,Kt={f:y?jt:function(t,e){if(t=ot(t),e=_(e,!0),b)try{return jt(t,e)}catch(t){}if(C(t,e))return T(!mt.f.call(t,e),t[e])}},Qt=Tt.KEY,Ht=Kt.f,Gt=E.f,zt=Wt.f,Yt=h.Symbol,Xt=h.JSON,Jt=Xt&&Xt.stringify,$t=G("_hidden"),Zt=G("toPrimitive"),te={}.propertyIsEnumerable,ee=H("symbol-registry"),ne=H("symbols"),re=H("op-symbols"),ie=Object.prototype,oe="function"==typeof Yt,se=h.QObject,ae=!se||!se.prototype||!se.prototype.findChild,ue=y&&d(function(){return 7!=xt(Gt({},"a",{get:function(){return Gt(this,"a",{value:7}).a}})).a})?function(t,e,n){var r=Ht(ie,e);r&&delete ie[e],Gt(t,e,n),r&&t!==ie&&Gt(ie,e,r)}:Gt,ce=function(t){var e=ne[t]=xt(Yt.prototype);return e._k=t,e},he=oe&&"symbol"==typeof Yt.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof Yt},le=function(t,e,n){return t===ie&&le(re,e,n),p(t),e=_(e,!0),p(n),C(ne,e)?(n.enumerable?(C(t,$t)&&t[$t][e]&&(t[$t][e]=!1),n=xt(n,{enumerable:T(0,!1)})):(C(t,$t)||Gt(t,$t,T(1,{})),t[$t][e]=!0),ue(t,e,n)):Gt(t,e,n)},fe=function(t,e){p(t);for(var n,r=function(t){var e=dt(t),n=yt.f;if(n)for(var r,i=n(t),o=mt.f,s=0;i.length>s;)o.call(t,r=i[s++])&&e.push(r);return e}(e=ot(e)),i=0,o=r.length;o>i;)le(t,n=r[i++],e[n]);return t},pe=function(t){var e=te.call(this,t=_(t,!0));return!(this===ie&&C(ne,t)&&!C(re,t))&&(!(e||!C(this,t)||!C(ne,t)||C(this,$t)&&this[$t][t])||e)},de=function(t,e){if(t=ot(t),e=_(e,!0),t!==ie||!C(ne,e)||C(re,e)){var n=Ht(t,e);return!n||!C(ne,e)||C(t,$t)&&t[$t][e]||(n.enumerable=!0),n}},ye=function(t){for(var e,n=zt(ot(t)),r=[],i=0;n.length>i;)C(ne,e=n[i++])||e==$t||e==Qt||r.push(e);return r},me=function(t){for(var e,n=t===ie,r=zt(n?re:ot(t)),i=[],o=0;r.length>o;)!C(ne,e=r[o++])||n&&!C(ie,e)||i.push(ne[e]);return i};oe||(k((Yt=function(){if(this instanceof Yt)throw TypeError("Symbol is not a constructor!");var t=A(arguments.length>0?arguments[0]:void 0),e=function(n){this===ie&&e.call(re,n),C(this,$t)&&C(this[$t],t)&&(this[$t][t]=!1),ue(this,t,T(1,n))};return y&&ae&&ue(ie,t,{configurable:!0,set:e}),ce(t)}).prototype,"toString",function(){return this._k}),Kt.f=de,E.f=le,Ut.f=Wt.f=ye,mt.f=pe,yt.f=me,y&&k(ie,"propertyIsEnumerable",pe,!0),Nt.f=function(t){return ce(G(t))}),P(P.G+P.W+P.F*!oe,{Symbol:Yt});for(var ge="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ve=0;ge.length>ve;)G(ge[ve++]);for(var be=dt(G.store),_e=0;be.length>_e;)At(be[_e++]);P(P.S+P.F*!oe,"Symbol",{for:function(t){return C(ee,t+="")?ee[t]:ee[t]=Yt(t)},keyFor:function(t){if(!he(t))throw TypeError(t+" is not a symbol!");for(var e in ee)if(ee[e]===t)return e},useSetter:function(){ae=!0},useSimple:function(){ae=!1}}),P(P.S+P.F*!oe,"Object",{create:function(t,e){return void 0===e?xt(t):fe(xt(t),e)},defineProperty:le,defineProperties:fe,getOwnPropertyDescriptor:de,getOwnPropertyNames:ye,getOwnPropertySymbols:me}),Xt&&P(P.S+P.F*(!oe||d(function(){var t=Yt();return"[null]"!=Jt([t])||"{}"!=Jt({a:t})||"{}"!=Jt(Object(t))})),"JSON",{stringify:function(t){for(var e,n,r=[t],i=1;arguments.length>i;)r.push(arguments[i++]);if(n=e=r[1],(f(e)||void 0!==t)&&!he(t))return K(e)||(e=function(t,e){if("function"==typeof n&&(e=n.call(this,t,e)),!he(e))return e}),r[1]=e,Jt.apply(Xt,r)}}),Yt.prototype[Zt]||S(Yt.prototype,Zt,Yt.prototype.valueOf),Ct(Yt,"Symbol"),Ct(Math,"Math",!0),Ct(h.JSON,"JSON",!0);var we=G("toStringTag"),Ee="Arguments"==M(function(){return arguments}()),Te={};Te[G("toStringTag")]="z",Te+""!="[object z]"&&k(Object.prototype,"toString",function(){return"[object "+(void 0===(t=this)?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),we))?n:Ee?M(e):"Object"==(r=M(e))&&"function"==typeof e.callee?"Arguments":r)+"]";var t,e,n,r},!0),At("asyncIterator"),At("observable");l.Symbol;var Se={},Ie={};S(Ie,G("iterator"),function(){return this});var Ce,Ne=function(t,e,n){t.prototype=xt(Ie,{next:T(1,n)}),Ct(t,e+" Iterator")},De=ct("IE_PROTO"),Ae=Object.prototype,ke=Object.getPrototypeOf||function(t){return t=U(t),C(t,De)?t[De]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?Ae:null},Re=G("iterator"),Oe=!([].keys&&"next"in[].keys()),Pe=function(){return this},Le=function(t,e,n,r,i,o,s){Ne(n,e,r);var a,u,c,h=function(t){if(!Oe&&t in d)return d[t];switch(t){case"keys":case"values":return function(){return new n(this,t)}}return function(){return new n(this,t)}},l=e+" Iterator",f="values"==i,p=!1,d=t.prototype,y=d[Re]||d["@@iterator"]||i&&d[i],m=y||h(i),g=i?f?h("entries"):m:void 0,v="Array"==e&&d.entries||y;if(v&&(c=ke(v.call(new t)))!==Object.prototype&&c.next&&(Ct(c,l,!0),"function"!=typeof c[Re]&&S(c,Re,Pe)),f&&y&&"values"!==y.name&&(p=!0,m=function(){return y.call(this)}),(Oe||p||!d[Re])&&S(d,Re,m),Se[e]=m,Se[l]=Pe,i)if(a={values:f?m:h("values"),keys:o?m:h("keys"),entries:g},s)for(u in a)u in d||k(d,u,a[u]);else P(P.P+P.F*(Oe||p),e,a);return a},Me=(Ce=!0,function(t,e){var n,r,i=String(F(t)),o=V(e),s=i.length;return o<0||o>=s?Ce?"":void 0:(n=i.charCodeAt(o))<55296||n>56319||o+1===s||(r=i.charCodeAt(o+1))<56320||r>57343?Ce?i.charAt(o):n:Ce?i.slice(o,o+2):r-56320+(n-55296<<10)+65536});Le(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=Me(e,n),this._i+=t.length,{value:t,done:!1})});var xe=function(t,e){return{value:e,done:!!t}},Fe=Le(Array,"Array",function(t,e){this._t=ot(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,xe(1)):xe(0,"keys"==e?n:"values"==e?t[n]:[n,t[n]])},"values");Se.Arguments=Se.Array,Z("keys"),Z("values"),Z("entries");for(var Ue=G("iterator"),qe=G("toStringTag"),Be=Se.Array,Ve={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},We=dt(Ve),je=0;je<We.length;je++){var Ke,Qe=We[je],He=Ve[Qe],Ge=h[Qe],ze=Ge&&Ge.prototype;if(ze&&(ze[Ue]||S(ze,Ue,Be),ze[qe]||S(ze,qe,Qe),Se[Qe]=Be,He))for(Ke in Fe)ze[Ke]||k(ze,Ke,Fe[Ke],!0)}Nt.f("iterator");var Ye=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};function Xe(t,e){function n(){this.constructor=t}Ye(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var Je=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t};function $e(t,e,n,r){return new(n||(n=Promise))(function(i,o){function s(t){try{u(r.next(t))}catch(t){o(t)}}function a(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(s,a)}u((r=r.apply(t,e||[])).next())})}function Ze(t,e){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)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 s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=(i=s.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=e.call(t,s)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}}var tn=!1,en=!1,nn="${JSCORE_VERSION}",rn=function(t,e){if(!t)throw on(e)},on=function(t){return new Error("Firebase Database ("+nn+") INTERNAL ASSERT FAILED: "+t)},sn=function(t){for(var e=[],n=0,r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=63&i|128):55296==(64512&i)&&r+1<t.length&&56320==(64512&t.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&t.charCodeAt(++r)),e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128)}return e},an={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(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[],i=0;i<t.length;i+=3){var o=t[i],s=i+1<t.length,a=s?t[i+1]:0,u=i+2<t.length,c=u?t[i+2]:0,h=o>>2,l=(3&o)<<4|a>>4,f=(15&a)<<2|c>>6,p=63&c;u||(p=64,s||(f=64)),r.push(n[h],n[l],n[f],n[p])}return r.join("")},encodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(sn(t),e)},decodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):function(t){for(var e=[],n=0,r=0;n<t.length;){var i=t[n++];if(i<128)e[r++]=String.fromCharCode(i);else if(i>191&&i<224){var o=t[n++];e[r++]=String.fromCharCode((31&i)<<6|63&o)}else if(i>239&&i<365){var s=((7&i)<<18|(63&(o=t[n++]))<<12|(63&(a=t[n++]))<<6|63&t[n++])-65536;e[r++]=String.fromCharCode(55296+(s>>10)),e[r++]=String.fromCharCode(56320+(1023&s))}else{o=t[n++];var a=t[n++];e[r++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&a)}}return e.join("")}(this.decodeStringToByteArray(t,e))},decodeStringToByteArray:function(t,e){this.init_();for(var n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[],i=0;i<t.length;){var o=n[t.charAt(i++)],s=i<t.length?n[t.charAt(i)]:0,a=++i<t.length?n[t.charAt(i)]:64,u=++i<t.length?n[t.charAt(i)]:64;if(++i,null==o||null==s||null==a||null==u)throw Error();var c=o<<2|s>>4;if(r.push(c),64!=a){var h=s<<4&240|a>>2;if(r.push(h),64!=u){var l=a<<6&192|u;r.push(l)}}}return r},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},un=function(t){try{return an.decodeString(t,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};function cn(t){return hn(void 0,t)}function hn(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return e}for(var n in e)e.hasOwnProperty(n)&&(t[n]=hn(t[n],e[n]));return t}function ln(t,e,n){t[e]=n}var fn=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t.prototype.wrapCallback=function(t){var e=this;return function(n,r){n?e.reject(n):e.resolve(r),"function"==typeof t&&(e.promise.catch(function(){}),1===t.length?t(n):t(n,r))}},t}(),pn=function(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")},dn=function(){return!0===tn||!0===en},yn="FirebaseError",mn=Error.captureStackTrace,gn=function(){return function(t,e){if(this.code=t,this.message=e,mn)mn(this,vn.prototype.create);else try{throw Error.apply(this,arguments)}catch(t){this.name=yn,Object.defineProperty(this,"stack",{get:function(){return t.stack}})}}}();gn.prototype=Object.create(Error.prototype),gn.prototype.constructor=gn,gn.prototype.name=yn;var vn=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n,this.pattern=/\{\$([^}]+)}/g}return t.prototype.create=function(t,e){void 0===e&&(e={});var n,r=this.errors[t],i=this.service+"/"+t;n=void 0===r?"Error":r.replace(this.pattern,function(t,n){var r=e[n];return void 0!==r?r.toString():"<"+n+"?>"}),n=this.serviceName+": "+n+" ("+i+").";var o=new gn(i,n);for(var s in e)e.hasOwnProperty(s)&&"_"!==s.slice(-1)&&(o[s]=e[s]);return o},t}();function bn(t){return JSON.parse(t)}function _n(t){return JSON.stringify(t)}var wn=function(t){var e={},n={},r={},i="";try{var o=t.split(".");e=bn(un(o[0])||""),n=bn(un(o[1])||""),i=o[2],r=n.d||{},delete n.d}catch(t){}return{header:e,claims:n,data:r,signature:i}},En=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},Tn=function(t,e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},Sn=function(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])},In=function(t){return e={},Sn(t,function(t,n){e[t]=n}),e;var e},Cn=function(t){for(var e in t)return!1;return!0},Nn=function(t){var e=0;for(var n in t)e++;return e},Dn=function(t,e,n){var r={};for(var i in t)r[i]=e.call(n,t[i],i,t);return r},An=function(t,e,n){for(var r in t)if(e.call(n,t[r],r,t))return r},kn=function(t){for(var e in t)return e},Rn=function(t){function e(){var e=t.call(this)||this;e.chain_=[],e.buf_=[],e.W_=[],e.pad_=[],e.inbuf_=0,e.total_=0,e.blockSize=64,e.pad_[0]=128;for(var n=1;n<e.blockSize;++n)e.pad_[n]=0;return e.reset(),e}return Xe(e,t),e.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},e.prototype.compress_=function(t,e){e||(e=0);var n=this.W_;if("string"==typeof t)for(var r=0;r<16;r++)n[r]=t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|t.charCodeAt(e+3),e+=4;else for(r=0;r<16;r++)n[r]=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3],e+=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,s,a=this.chain_[0],u=this.chain_[1],c=this.chain_[2],h=this.chain_[3],l=this.chain_[4];for(r=0;r<80;r++){r<40?r<20?(o=h^u&(c^h),s=1518500249):(o=u^c^h,s=1859775393):r<60?(o=u&c|h&(u|c),s=2400959708):(o=u^c^h,s=3395469782);i=(a<<5|a>>>27)+o+l+s+n[r]&4294967295;l=h,h=c,c=4294967295&(u<<30|u>>>2),u=a,a=i}this.chain_[0]=this.chain_[0]+a&4294967295,this.chain_[1]=this.chain_[1]+u&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+h&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295},e.prototype.update=function(t,e){if(null!=t){void 0===e&&(e=t.length);for(var n=e-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r<e;){if(0==o)for(;r<=n;)this.compress_(t,r),r+=this.blockSize;if("string"==typeof t){for(;r<e;)if(i[o]=t.charCodeAt(r),++r,++o==this.blockSize){this.compress_(i),o=0;break}}else for(;r<e;)if(i[o]=t[r],++r,++o==this.blockSize){this.compress_(i),o=0;break}}this.inbuf_=o,this.total_+=e}},e.prototype.digest=function(){var t=[],e=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&e,e/=256;this.compress_(this.buf_);var r=0;for(n=0;n<5;n++)for(var i=24;i>=0;i-=8)t[r]=this.chain_[n]>>i&255,++r;return t},e}(function(){return function(){this.blockSize=-1}}());function On(t,e){var n=new Pn(t,e);return n.subscribe.bind(n)}var Pn=function(){function t(t,e){var n=this;this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then(function(){t(n)}).catch(function(t){n.error(t)})}return t.prototype.next=function(t){this.forEachObserver(function(e){e.next(t)})},t.prototype.error=function(t){this.forEachObserver(function(e){e.error(t)}),this.close(t)},t.prototype.complete=function(){this.forEachObserver(function(t){t.complete()}),this.close()},t.prototype.subscribe=function(t,e,n){var r,i=this;if(void 0===t&&void 0===e&&void 0===n)throw new Error("Missing Observer.");void 0===(r=function(t,e){if("object"!=typeof t||null===t)return!1;for(var n=0,r=e;n<r.length;n++){var i=r[n];if(i in t&&"function"==typeof t[i])return!0}return!1}(t,["next","error","complete"])?t:{next:t,error:e,complete:n}).next&&(r.next=Ln),void 0===r.error&&(r.error=Ln),void 0===r.complete&&(r.complete=Ln);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(t){}}),this.observers.push(r),o},t.prototype.unsubscribeOne=function(t){void 0!==this.observers&&void 0!==this.observers[t]&&(delete this.observers[t],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))},t.prototype.forEachObserver=function(t){if(!this.finalized)for(var e=0;e<this.observers.length;e++)this.sendOne(e,t)},t.prototype.sendOne=function(t,e){var n=this;this.task.then(function(){if(void 0!==n.observers&&void 0!==n.observers[t])try{e(n.observers[t])}catch(t){"undefined"!=typeof console&&console.error&&console.error(t)}})},t.prototype.close=function(t){var e=this;this.finalized||(this.finalized=!0,void 0!==t&&(this.finalError=t),this.task.then(function(){e.observers=void 0,e.onNoObservers=void 0}))},t}();function Ln(){}var Mn=function(t,e,n,r){var i;if(r<e?i="at least "+e:r>n&&(i=0===n?"none":"no more than "+n),i)throw new Error(t+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")};function xn(t,e,n){var r="";switch(e){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=t+" failed: ";return i+=r+" argument "}function Fn(t,e,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(xn(t,e,r)+"must be a valid function.")}function Un(t,e,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(xn(t,e,r)+"must be a valid context object.")}var qn=function(t){for(var e=0,n=0;n<t.length;n++){var r=t.charCodeAt(n);r<128?e++:r<2048?e+=2:r>=55296&&r<=56319?(e+=4,n++):e+=3}return e},Bn=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},Vn="[DEFAULT]",Wn=[],jn=function(){function t(t,e,n){this.firebase_=n,this.isDeleted_=!1,this.services_={},this.name_=e.name,this._automaticDataCollectionEnabled=e.automaticDataCollectionEnabled||!1,this.options_=cn(t),this.INTERNAL={getUid:function(){return null},getToken:function(){return Promise.resolve(null)},addAuthTokenListener:function(t){Wn.push(t),setTimeout(function(){return t(null)},0)},removeAuthTokenListener:function(t){Wn=Wn.filter(function(e){return e!==t})}}}return Object.defineProperty(t.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed_(),this._automaticDataCollectionEnabled},set:function(t){this.checkDestroyed_(),this._automaticDataCollectionEnabled=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return this.checkDestroyed_(),this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this.checkDestroyed_(),this.options_},enumerable:!0,configurable:!0}),t.prototype.delete=function(){var t=this;return new Promise(function(e){t.checkDestroyed_(),e()}).then(function(){t.firebase_.INTERNAL.removeApp(t.name_);var e=[];return Object.keys(t.services_).forEach(function(n){Object.keys(t.services_[n]).forEach(function(r){e.push(t.services_[n][r])})}),Promise.all(e.map(function(t){return t.INTERNAL.delete()}))}).then(function(){t.isDeleted_=!0,t.services_={}})},t.prototype._getService=function(t,e){if(void 0===e&&(e=Vn),this.checkDestroyed_(),this.services_[t]||(this.services_[t]={}),!this.services_[t][e]){var n=e!==Vn?e:void 0,r=this.firebase_.INTERNAL.factories[t](this,this.extendApp.bind(this),n);this.services_[t][e]=r}return this.services_[t][e]},t.prototype.extendApp=function(t){var e=this;hn(this,t),t.INTERNAL&&t.INTERNAL.addAuthTokenListener&&(Wn.forEach(function(t){e.INTERNAL.addAuthTokenListener(t)}),Wn=[])},t.prototype.checkDestroyed_=function(){this.isDeleted_&&Kn("app-deleted",{name:this.name_})},t}();function Kn(t,e){throw Hn.create(t,e)}jn.prototype.name&&jn.prototype.options||jn.prototype.delete||console.log("dc");var Qn,Hn=new vn("app","Firebase",{"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."}),Gn=function t(){var e={},n={},r={},i={__esModule:!0,initializeApp:function(t,n){if(void 0===n&&(n={}),"object"!=typeof n||null===n){var r=n;n={name:r}}var o=n;void 0===o.name&&(o.name=Vn);var s=o.name;"string"==typeof s&&s||Kn("bad-app-name",{name:s+""}),Bn(e,s)&&Kn("duplicate-app",{name:s});var u=new jn(t,o,i);return e[s]=u,a(u,"create"),u},app:o,apps:null,Promise:Promise,SDK_VERSION:"5.7.0",INTERNAL:{registerService:function(t,e,a,u,c){n[t]&&Kn("duplicate-service",{name:t}),n[t]=e,u&&(r[t]=u,s().forEach(function(t){u("create",t)}));var h=function(e){return void 0===e&&(e=o()),"function"!=typeof e[t]&&Kn("invalid-app-argument",{name:t}),e[t]()};return void 0!==a&&hn(h,a),i[t]=h,jn.prototype[t]=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return this._getService.bind(this,t).apply(this,c?e:[])},h},createFirebaseNamespace:t,extendNamespace:function(t){hn(i,t)},createSubscribe:On,ErrorFactory:vn,removeApp:function(t){a(e[t],"delete"),delete e[t]},factories:n,useAsService:u,Promise:Promise,deepExtend:hn}};function o(t){return Bn(e,t=t||Vn)||Kn("no-app",{name:t}),e[t]}function s(){return Object.keys(e).map(function(t){return e[t]})}function a(t,e){Object.keys(n).forEach(function(n){var i=u(t,n);null!==i&&r[i]&&r[i](e,t)})}function u(t,e){if("serverAuth"===e)return null;var n=e;return t.options,n}return ln(i,"default",i),Object.defineProperty(i,"apps",{get:s}),ln(o,"App",jn),i}();(function(){var t,e=e||{},n=this;function r(t){return"string"==typeof t}function i(t){return"boolean"==typeof t}function o(){}function s(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function a(t){return null===t}function u(t){return"array"==s(t)}function c(t){var e=s(t);return"array"==e||"object"==e&&"number"==typeof t.length}function h(t){return"function"==s(t)}function l(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var f="closure_uid_"+(1e9*Math.random()>>>0),p=0;function d(t,e,n){return t.call.apply(t.bind,arguments)}function y(t,e,n){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),t.apply(e,n)}}return function(){return t.apply(e,arguments)}}function m(t,e,n){return(m=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?d:y).apply(null,arguments)}function g(t,e){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}var v=Date.now||function(){return+new Date};function b(t,e){function n(){}n.prototype=e.prototype,t.ob=e.prototype,t.prototype=new n,t.prototype.constructor=t,t.ed=function(t,n,r){for(var i=Array(arguments.length-2),o=2;o<arguments.length;o++)i[o-2]=arguments[o];return e.prototype[n].apply(t,i)}}function _(t){t.prototype.then=t.prototype.then,t.prototype.$goog_Thenable=!0}function w(t){if(!t)return!1;try{return!!t.$goog_Thenable}catch(t){return!1}}function E(t){if(Error.captureStackTrace)Error.captureStackTrace(this,E);else{var e=Error().stack;e&&(this.stack=e)}t&&(this.message=String(t))}function T(t,e){for(var n="",r=(t=t.split("%s")).length-1,i=0;i<r;i++)n+=t[i]+(i<e.length?e[i]:"%s");E.call(this,n+t[r])}function S(t,e){throw new T("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function I(t,e){this.c=t,this.f=e,this.b=0,this.a=null}function C(t,e){t.f(e),100>t.b&&(t.b++,e.next=t.a,t.a=e)}function N(){this.b=this.a=null}b(E,Error),E.prototype.name="CustomError",b(T,E),T.prototype.name="AssertionError",I.prototype.get=function(){if(0<this.b){this.b--;var t=this.a;this.a=t.next,t.next=null}else t=this.c();return t};var D=new I(function(){return new k},function(t){t.reset()});function A(){var t=ft,e=null;return t.a&&(e=t.a,t.a=t.a.next,t.a||(t.b=null),e.next=null),e}function k(){this.next=this.b=this.a=null}N.prototype.add=function(t,e){var n=D.get();n.set(t,e),this.b?this.b.next=n:this.a=n,this.b=n},k.prototype.set=function(t,e){this.a=t,this.b=e,this.next=null},k.prototype.reset=function(){this.next=this.b=this.a=null};var R=Array.prototype.indexOf?function(t,e){return Array.prototype.indexOf.call(t,e,void 0)}:function(t,e){if(r(t))return r(e)&&1==e.length?t.indexOf(e,0):-1;for(var n=0;n<t.length;n++)if(n in t&&t[n]===e)return n;return-1},O=Array.prototype.forEach?function(t,e,n){Array.prototype.forEach.call(t,e,n)}:function(t,e,n){for(var i=t.length,o=r(t)?t.split(""):t,s=0;s<i;s++)s in o&&e.call(n,o[s],s,t)};var P=Array.prototype.map?function(t,e){return Array.prototype.map.call(t,e,void 0)}:function(t,e){for(var n=t.length,i=Array(n),o=r(t)?t.split(""):t,s=0;s<n;s++)s in o&&(i[s]=e.call(void 0,o[s],s,t));return i},L=Array.prototype.some?function(t,e){return Array.prototype.some.call(t,e,void 0)}:function(t,e){for(var n=t.length,i=r(t)?t.split(""):t,o=0;o<n;o++)if(o in i&&e.call(void 0,i[o],o,t))return!0;return!1};function M(t,e){return 0<=R(t,e)}function x(t,e){var n;return(n=0<=(e=R(t,e)))&&Array.prototype.splice.call(t,e,1),n}function F(t,e){!function(t,e){var n=t.length,i=r(t)?t.split(""):t;for(--n;0<=n;--n)n in i&&e.call(void 0,i[n],n,t)}(t,function(n,r){e.call(void 0,n,r,t)&&1==Array.prototype.splice.call(t,r,1).length&&0})}function U(t){return Array.prototype.concat.apply([],arguments)}function q(t){var e=t.length;if(0<e){for(var n=Array(e),r=0;r<e;r++)n[r]=t[r];return n}return[]}function B(t,e){for(var n=t.split("%s"),r="",i=Array.prototype.slice.call(arguments,1);i.length&&1<n.length;)r+=n.shift()+i.shift();return r+n.join("%s")}var V=String.prototype.trim?function(t){return t.trim()}:function(t){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(t)[1]};function W(t){return X.test(t)?(-1!=t.indexOf("&")&&(t=t.replace(K,"&amp;")),-1!=t.indexOf("<")&&(t=t.replace(Q,"&lt;")),-1!=t.indexOf(">")&&(t=t.replace(H,"&gt;")),-1!=t.indexOf('"')&&(t=t.replace(G,"&quot;")),-1!=t.indexOf("'")&&(t=t.replace(z,"&#39;")),-1!=t.indexOf("\0")&&(t=t.replace(Y,"&#0;")),t):t}var j,K=/&/g,Q=/</g,H=/>/g,G=/"/g,z=/'/g,Y=/\x00/g,X=/[\x00&<>"']/;function J(t,e){return-1!=t.indexOf(e)}function $(t,e){return t<e?-1:t>e?1:0}t:{var Z=n.navigator;if(Z){var tt=Z.userAgent;if(tt){j=tt;break t}}j=""}function et(t){return J(j,t)}function nt(t,e){for(var n in t)e.call(void 0,t[n],n,t)}function rt(t){for(var e in t)return!1;return!0}function it(t){var e,n={};for(e in t)n[e]=t[e];return n}var ot,st,at="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ut(t,e){for(var n,r,i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(var o=0;o<at.length;o++)n=at[o],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function ct(t){n.setTimeout(function(){throw t},0)}function ht(t,e){st||function(){if(n.Promise&&n.Promise.resolve){var t=n.Promise.resolve(void 0);st=function(){t.then(pt)}}else st=function(){var t=pt;!h(n.setImmediate)||n.Window&&n.Window.prototype&&!et("Edge")&&n.Window.prototype.setImmediate==n.setImmediate?(ot||(ot=function(){var t=n.MessageChannel;if(void 0===t&&"undefined"!=typeof window&&window.postMessage&&window.addEventListener&&!et("Presto")&&(t=function(){var t=document.createElement("IFRAME");t.style.display="none",t.src="",document.documentElement.appendChild(t);var e=t.contentWindow;(t=e.document).open(),t.write(""),t.close();var n="callImmediate"+Math.random(),r="file:"==e.location.protocol?"*":e.location.protocol+"//"+e.location.host;t=m(function(t){"*"!=r&&t.origin!=r||t.data!=n||this.port1.onmessage()},this),e.addEventListener("message",t,!1),this.port1={},this.port2={postMessage:function(){e.postMessage(n,r)}}}),void 0!==t&&!et("Trident")&&!et("MSIE")){var e=new t,r={},i=r;return e.port1.onmessage=function(){if(void 0!==r.next){var t=(r=r.next).wb;r.wb=null,t()}},function(t){i.next={wb:t},i=i.next,e.port2.postMessage(0)}}return"undefined"!=typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(t){var e=document.createElement("SCRIPT");e.onreadystatechange=function(){e.onreadystatechange=null,e.parentNode.removeChild(e),e=null,t(),t=null},document.documentElement.appendChild(e)}:function(t){n.setTimeout(t,0)}}()),ot(t)):n.setImmediate(t)}}(),lt||(st(),lt=!0),ft.add(t,e)}var lt=!1,ft=new N;function pt(){for(var t;t=A();){try{t.a.call(t.b)}catch(t){ct(t)}C(D,t)}lt=!1}function dt(t,e){if(this.a=yt,this.i=void 0,this.f=this.b=this.c=null,this.g=this.h=!1,t!=o)try{var n=this;t.call(e,function(t){Nt(n,mt,t)},function(t){if(!(t instanceof Lt))try{if(t instanceof Error)throw t;throw Error("Promise rejected.")}catch(t){}Nt(n,gt,t)})}catch(t){Nt(this,gt,t)}}var yt=0,mt=2,gt=3;function vt(){this.next=this.f=this.b=this.g=this.a=null,this.c=!1}vt.prototype.reset=function(){this.f=this.b=this.g=this.a=null,this.c=!1};var bt=new I(function(){return new vt},function(t){t.reset()});function _t(t,e,n){var r=bt.get();return r.g=t,r.b=e,r.f=n,r}function wt(t){if(t instanceof dt)return t;var e=new dt(o);return Nt(e,mt,t),e}function Et(t){return new dt(function(e,n){n(t)})}function Tt(t,e,n){Dt(t,e,n,null)||ht(g(e,t))}function St(t){return new dt(function(e){var n=t.length,r=[];if(n)for(var i=function(t,i,o){n--,r[t]=i?{Db:!0,value:o}:{Db:!1,reason:o},0==n&&e(r)},o=0;o<t.length;o++)Tt(t[o],g(i,o,!0),g(i,o,!1));else e(r)})}function It(t,e){t.b||t.a!=mt&&t.a!=gt||At(t),t.f?t.f.next=e:t.b=e,t.f=e}function Ct(t,e,n,r){var i=_t(null,null,null);return i.a=new dt(function(t,o){i.g=e?function(n){try{var i=e.call(r,n);t(i)}catch(t){o(t)}}:t,i.b=n?function(e){try{var i=n.call(r,e);void 0===i&&e instanceof Lt?o(e):t(i)}catch(t){o(t)}}:o}),i.a.c=t,It(t,i),i.a}function Nt(t,e,n){t.a==yt&&(t===n&&(e=gt,n=new TypeError("Promise cannot resolve to itself")),t.a=1,Dt(n,t.Nc,t.Oc,t)||(t.i=n,t.a=e,t.c=null,At(t),e!=gt||n instanceof Lt||function(t,e){t.g=!0,ht(function(){t.g&&Pt.call(null,e)})}(t,n)))}function Dt(t,e,n,r){if(t instanceof dt)return It(t,_t(e||o,n||null,r)),!0;if(w(t))return t.then(e,n,r),!0;if(l(t))try{var i=t.then;if(h(i))return function(t,e,n,r,i){function o(t){s||(s=!0,r.call(i,t))}var s=!1;try{e.call(t,function(t){s||(s=!0,n.call(i,t))},o)}catch(t){o(t)}}(t,i,e,n,r),!0}catch(t){return n.call(r,t),!0}return!1}function At(t){t.h||(t.h=!0,ht(t.Yb,t))}function kt(t){var e=null;return t.b&&(e=t.b,t.b=e.next,e.next=null),t.b||(t.f=null),e}function Rt(t,e,n,r){if(n==gt&&e.b&&!e.c)for(;t&&t.g;t=t.c)t.g=!1;if(e.a)e.a.c=null,Ot(e,n,r);else try{e.c?e.g.call(e.f):Ot(e,n,r)}catch(t){Pt.call(null,t)}C(bt,e)}function Ot(t,e,n){e==mt?t.g.call(t.f,n):t.b&&t.b.call(t.f,n)}dt.prototype.then=function(t,e,n){return Ct(this,h(t)?t:null,h(e)?e:null,n)},_(dt),(t=dt.prototype).ia=function(t,e){return(t=_t(t,t,e)).c=!0,It(this,t),this},t.s=function(t,e){return Ct(this,null,t,e)},t.cancel=function(t){this.a==yt&&ht(function(){!function t(e,n){if(e.a==yt)if(e.c){var r=e.c;if(r.b){for(var i=0,o=null,s=null,a=r.b;a&&(a.c||(i++,a.a==e&&(o=a),!(o&&1<i)));a=a.next)o||(s=a);o&&(r.a==yt&&1==i?t(r,n):(s?((i=s).next==r.f&&(r.f=i),i.next=i.next.next):kt(r),Rt(r,o,gt,n)))}e.c=null}else Nt(e,gt,n)}(this,new Lt(t))},this)},t.Nc=function(t){this.a=yt,Nt(this,mt,t)},t.Oc=function(t){this.a=yt,Nt(this,gt,t)},t.Yb=function(){for(var t;t=kt(this);)Rt(this,t,this.a,this.i);this.h=!1};var Pt=ct;function Lt(t){E.call(this,t)}function Mt(){0!=xt&&(Ft[this[f]||(this[f]=++p)]=this),this.qa=this.qa,this.ja=this.ja}b(Lt,E),Lt.prototype.name="cancel";var xt=0,Ft={};function Ut(t){if(!t.qa&&(t.qa=!0,t.va(),0!=xt)){var e=t[f]||(t[f]=++p);if(0!=xt&&t.ja&&0<t.ja.length)throw Error(t+" did not empty its onDisposeCallbacks queue. This probably means it overrode dispose() or disposeInternal() without calling the superclass' method.");delete Ft[e]}}function qt(t){return qt[" "](t),t}Mt.prototype.qa=!1,Mt.prototype.va=function(){if(this.ja)for(;this.ja.length;)this.ja.shift()()},qt[" "]=o;var Bt,Vt,Wt=et("Opera"),jt=et("Trident")||et("MSIE"),Kt=et("Edge"),Qt=Kt||jt,Ht=et("Gecko")&&!(J(j.toLowerCase(),"webkit")&&!et("Edge"))&&!(et("Trident")||et("MSIE"))&&!et("Edge"),Gt=J(j.toLowerCase(),"webkit")&&!et("Edge");function zt(){var t=n.document;return t?t.documentMode:void 0}t:{var Yt="",Xt=(Vt=j,Ht?/rv:([^\);]+)(\)|;)/.exec(Vt):Kt?/Edge\/([\d\.]+)/.exec(Vt):jt?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Vt):Gt?/WebKit\/(\S+)/.exec(Vt):Wt?/(?:Version)[ \/]?(\S+)/.exec(Vt):void 0);if(Xt&&(Yt=Xt?Xt[1]:""),jt){var Jt=zt();if(null!=Jt&&Jt>parseFloat(Yt)){Bt=String(Jt);break t}}Bt=Yt}var $t,Zt={};function te(t){return function(t,e){var n=Zt;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=e(t)}(t,function(){for(var e=0,n=V(String(Bt)).split("."),r=V(String(t)).split("."),i=Math.max(n.length,r.length),o=0;0==e&&o<i;o++){var s=n[o]||"",a=r[o]||"";do{if(s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],a=/(\d*)(\D*)(.*)/.exec(a)||["","","",""],0==s[0].length&&0==a[0].length)break;e=$(0==s[1].length?0:parseInt(s[1],10),0==a[1].length?0:parseInt(a[1],10))||$(0==s[2].length,0==a[2].length)||$(s[2],a[2]),s=s[3],a=a[3]}while(0==e)}return 0<=e})}var ee=n.document;$t=ee&&jt?zt()||("CSS1Compat"==ee.compatMode?parseInt(Bt,10):5):void 0;var ne=Object.freeze||function(t){return t},re=!jt||9<=Number($t),ie=jt&&!te("9"),oe=function(){if(!n.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return n.addEventListener("test",o,e),n.removeEventListener("test",o,e),t}();function se(t,e){this.type=t,this.b=this.target=e,this.Kb=!0}function ae(t,e){if(se.call(this,t?t.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,t){var n=this.type=t.type,i=t.changedTouches?t.changedTouches[0]:null;if(this.target=t.target||t.srcElement,this.b=e,e=t.relatedTarget){if(Ht){t:{try{qt(e.nodeName);var o=!0;break t}catch(t){}o=!1}o||(e=null)}}else"mouseover"==n?e=t.fromElement:"mouseout"==n&&(e=t.toElement);this.relatedTarget=e,null===i?(this.clientX=void 0!==t.clientX?t.clientX:t.pageX,this.clientY=void 0!==t.clientY?t.clientY:t.pageY,this.screenX=t.screenX||0,this.screenY=t.screenY||0):(this.clientX=void 0!==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=t.button,this.key=t.key||"",this.ctrlKey=t.ctrlKey,this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.metaKey=t.metaKey,this.pointerId=t.pointerId||0,this.pointerType=r(t.pointerType)?t.pointerType:ue[t.pointerType]||"",this.a=t,t.defaultPrevented&&this.preventDefault()}}se.prototype.preventDefault=function(){this.Kb=!1},b(ae,se);var ue=ne({2:"touch",3:"pen",4:"mouse"});ae.prototype.preventDefault=function(){ae.ob.preventDefault.call(this);var t=this.a;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,ie)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}},ae.prototype.f=function(){return this.a};var ce="closure_listenable_"+(1e6*Math.random()|0),he=0;function le(t){t.oa=!0,t.listener=null,t.proxy=null,t.src=null,t.La=null}function fe(t){this.src=t,this.a={},this.b=0}function pe(t,e){var n=e.type;n in t.a&&x(t.a[n],e)&&(le(e),0==t.a[n].length&&(delete t.a[n],t.b--))}function de(t,e,n,r){for(var i=0;i<t.length;++i){var o=t[i];if(!o.oa&&o.listener==e&&o.capture==!!n&&o.La==r)return i}return-1}fe.prototype.add=function(t,e,n,r,i){var o=t.toString();(t=this.a[o])||(t=this.a[o]=[],this.b++);var s=de(t,e,r,i);return-1<s?(e=t[s],n||(e.Ia=!1)):((e=new function(t,e,n,r,i){this.listener=t,this.proxy=null,this.src=e,this.type=n,this.capture=!!r,this.La=i,this.key=++he,this.oa=this.Ia=!1}(e,this.src,o,!!r,i)).Ia=n,t.push(e)),e};var ye="closure_lm_"+(1e6*Math.random()|0),me={};function ge(t,e,n,r,i){if(r&&r.once)be(t,e,n,r,i);else if(u(e))for(var o=0;o<e.length;o++)ge(t,e[o],n,r,i);else n=De(n),t&&t[ce]?ke(t,e,n,l(r)?!!r.capture:!!r,i):ve(t,e,n,!1,r,i)}function ve(t,e,n,r,i,o){if(!e)throw Error("Invalid event type");var s=l(i)?!!i.capture:!!i,a=Ce(t);if(a||(t[ye]=a=new fe(t)),!(n=a.add(e,n,r,s,o)).proxy)if(r=function(){var t=Ie,e=re?function(n){return t.call(e.src,e.listener,n)}:function(n){if(!(n=t.call(e.src,e.listener,n)))return n};return e}(),n.proxy=r,r.src=t,r.listener=n,t.addEventListener)oe||(i=s),void 0===i&&(i=!1),t.addEventListener(e.toString(),r,i);else if(t.attachEvent)t.attachEvent(Ee(e.toString()),r);else{if(!t.addListener||!t.removeListener)throw Error("addEventListener and attachEvent are unavailable.");t.addListener(r)}}function be(t,e,n,r,i){if(u(e))for(var o=0;o<e.length;o++)be(t,e[o],n,r,i);else n=De(n),t&&t[ce]?Re(t,e,n,l(r)?!!r.capture:!!r,i):ve(t,e,n,!0,r,i)}function _e(t,e,n,r,i){if(u(e))for(var o=0;o<e.length;o++)_e(t,e[o],n,r,i);else r=l(r)?!!r.capture:!!r,n=De(n),t&&t[ce]?(t=t.l,(e=String(e).toString())in t.a&&(-1<(n=de(o=t.a[e],n,r,i))&&(le(o[n]),Array.prototype.splice.call(o,n,1),0==o.length&&(delete t.a[e],t.b--)))):t&&(t=Ce(t))&&(e=t.a[e.toString()],t=-1,e&&(t=de(e,n,r,i)),(n=-1<t?e[t]:null)&&we(n))}function we(t){if("number"!=typeof t&&t&&!t.oa){var e=t.src;if(e&&e[ce])pe(e.l,t);else{var n=t.type,r=t.proxy;e.removeEventListener?e.removeEventListener(n,r,t.capture):e.detachEvent?e.detachEvent(Ee(n),r):e.addListener&&e.removeListener&&e.removeListener(r),(n=Ce(e))?(pe(n,t),0==n.b&&(n.src=null,e[ye]=null)):le(t)}}}function Ee(t){return t in me?me[t]:me[t]="on"+t}function Te(t,e,n,r){var i=!0;if((t=Ce(t))&&(e=t.a[e.toString()]))for(e=e.concat(),t=0;t<e.length;t++){var o=e[t];o&&o.capture==n&&!o.oa&&(o=Se(o,r),i=i&&!1!==o)}return i}function Se(t,e){var n=t.listener,r=t.La||t.src;return t.Ia&&we(t),n.call(r,e)}function Ie(t,e){if(t.oa)return!0;if(!re){if(!e)t:{e=["window","event"];for(var r=n,i=0;i<e.length;i++)if(null==(r=r[e[i]])){e=null;break t}e=r}if(e=new ae(i=e,this),r=!0,!(0>i.keyCode||void 0!=i.returnValue)){t:{var o=!1;if(0==i.keyCode)try{i.keyCode=-1;break t}catch(t){o=!0}(o||void 0==i.returnValue)&&(i.returnValue=!0)}for(i=[],o=e.b;o;o=o.parentNode)i.push(o);for(t=t.type,o=i.length-1;0<=o;o--){e.b=i[o];var s=Te(i[o],t,!0,e);r=r&&s}for(o=0;o<i.length;o++)e.b=i[o],s=Te(i[o],t,!1,e),r=r&&s}return r}return Se(t,new ae(e,this))}function Ce(t){return(t=t[ye])instanceof fe?t:null}var Ne="__closure_events_fn_"+(1e9*Math.random()>>>0);function De(t){return h(t)?t:(t[Ne]||(t[Ne]=function(e){return t.handleEvent(e)}),t[Ne])}function Ae(){Mt.call(this),this.l=new fe(this),this.Rb=this,this.Va=null}function ke(t,e,n,r,i){t.l.add(String(e),n,!1,r,i)}function Re(t,e,n,r,i){t.l.add(String(e),n,!0,r,i)}function Oe(t,e,n,r){if(!(e=t.l.a[String(e)]))return!0;e=e.concat();for(var i=!0,o=0;o<e.length;++o){var s=e[o];if(s&&!s.oa&&s.capture==n){var a=s.listener,u=s.La||s.src;s.Ia&&pe(t.l,s),i=!1!==a.call(u,r)&&i}}return i&&0!=r.Kb}function Pe(t,e,r){if(h(t))r&&(t=m(t,r));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=m(t.handleEvent,t)}return 2147483647<Number(e)?-1:n.setTimeout(t,e||0)}function Le(t){var e=null;return new dt(function(n,r){-1==(e=Pe(function(){n(void 0)},t))&&r(Error("Failed to schedule timer."))}).s(function(t){throw n.clearTimeout(e),t})}function Me(t){if(t.S&&"function"==typeof t.S)return t.S();if(r(t))return t.split("");if(c(t)){for(var e=[],n=t.length,i=0;i<n;i++)e.push(t[i]);return e}for(i in e=[],n=0,t)e[n++]=t[i];return e}function xe(t){if(t.U&&"function"==typeof t.U)return t.U();if(!t.S||"function"!=typeof t.S){if(c(t)||r(t)){var e=[];t=t.length;for(var n=0;n<t;n++)e.push(n);return e}for(var i in e=[],n=0,t)e[n++]=i;return e}}function Fe(t,e){this.b={},this.a=[],this.c=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(t)if(t instanceof Fe)for(n=t.U(),r=0;r<n.length;r++)this.set(n[r],t.get(n[r]));else for(r in t)this.set(r,t[r])}function Ue(t){if(t.c!=t.a.length){for(var e=0,n=0;e<t.a.length;){var r=t.a[e];qe(t.b,r)&&(t.a[n++]=r),e++}t.a.length=n}if(t.c!=t.a.length){var i={};for(n=e=0;e<t.a.length;)qe(i,r=t.a[e])||(t.a[n++]=r,i[r]=1),e++;t.a.length=n}}function qe(t,e){return Object.prototype.hasOwnProperty.call(t,e)}b(Ae,Mt),Ae.prototype[ce]=!0,Ae.prototype.addEventListener=function(t,e,n,r){ge(this,t,e,n,r)},Ae.prototype.removeEventListener=function(t,e,n,r){_e(this,t,e,n,r)},Ae.prototype.dispatchEvent=function(t){var e,n=this.Va;if(n)for(e=[];n;n=n.Va)e.push(n);n=this.Rb;var i=t.type||t;if(r(t))t=new se(t,n);else if(t instanceof se)t.target=t.target||n;else{var o=t;ut(t=new se(i,n),o)}if(o=!0,e)for(var s=e.length-1;0<=s;s--){var a=t.b=e[s];o=Oe(a,i,!0,t)&&o}if(o=Oe(a=t.b=n,i,!0,t)&&o,o=Oe(a,i,!1,t)&&o,e)for(s=0;s<e.length;s++)o=Oe(a=t.b=e[s],i,!1,t)&&o;return o},Ae.prototype.va=function(){if(Ae.ob.va.call(this),this.l){var t,e=this.l;for(t in e.a){for(var n=e.a[t],r=0;r<n.length;r++)le(n[r]);delete e.a[t],e.b--}}this.Va=null},(t=Fe.prototype).S=function(){Ue(this);for(var t=[],e=0;e<this.a.length;e++)t.push(this.b[this.a[e]]);return t},t.U=function(){return Ue(this),this.a.concat()},t.clear=function(){this.b={},this.c=this.a.length=0},t.get=function(t,e){return qe(this.b,t)?this.b[t]:e},t.set=function(t,e){qe(this.b,t)||(this.c++,this.a.push(t)),this.b[t]=e},t.forEach=function(t,e){for(var n=this.U(),r=0;r<n.length;r++){var i=n[r],o=this.get(i);t.call(e,o,i,this)}};var Be=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Ve(t,e){if(this.b=this.l=this.c="",this.i=null,this.h=this.g="",this.f=!1,t instanceof Ve){this.f=void 0!==e?e:t.f,We(this,t.c),this.l=t.l,this.b=t.b,je(this,t.i),this.g=t.g,e=t.a;var n=new rn;n.c=e.c,e.a&&(n.a=new Fe(e.a),n.b=e.b),Ke(this,n),this.h=t.h}else t&&(n=String(t).match(Be))?(this.f=!!e,We(this,n[1]||"",!0),this.l=Ye(n[2]||""),this.b=Ye(n[3]||"",!0),je(this,n[4]),this.g=Ye(n[5]||"",!0),Ke(this,n[6]||"",!0),this.h=Ye(n[7]||"")):(this.f=!!e,this.a=new rn(null,this.f))}function We(t,e,n){t.c=n?Ye(e,!0):e,t.c&&(t.c=t.c.replace(/:$/,""))}function je(t,e){if(e){if(e=Number(e),isNaN(e)||0>e)throw Error("Bad port number "+e);t.i=e}else t.i=null}function Ke(t,e,n){e instanceof rn?(t.a=e,function(t,e){e&&!t.f&&(on(t),t.c=null,t.a.forEach(function(t,e){var n=e.toLowerCase();e!=n&&(an(this,e),cn(this,n,t))},t)),t.f=e}(t.a,t.f)):(n||(e=Xe(e,en)),t.a=new rn(e,t.f))}function Qe(t,e,n){t.a.set(e,n)}function He(t,e){return t.a.get(e)}function Ge(t){return t instanceof Ve?new Ve(t):new Ve(t,void 0)}function ze(t,e){var n=new Ve(null,void 0);return We(n,"https"),t&&(n.b=t),e&&(n.g=e),n}function Ye(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function Xe(t,e,n){return r(t)?(t=encodeURI(t).replace(e,Je),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function Je(t){return"%"+((t=t.charCodeAt(0))>>4&15).toString(16)+(15&t).toString(16)}Ve.prototype.toString=function(){var t=[],e=this.c;e&&t.push(Xe(e,$e,!0),":");var n=this.b;return(n||"file"==e)&&(t.push("//"),(e=this.l)&&t.push(Xe(e,$e,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.i)&&t.push(":",String(n))),(n=this.g)&&(this.b&&"/"!=n.charAt(0)&&t.push("/"),t.push(Xe(n,"/"==n.charAt(0)?tn:Ze,!0))),(n=this.a.toString())&&t.push("?",n),(n=this.h)&&t.push("#",Xe(n,nn)),t.join("")};var $e=/[#\/\?@]/g,Ze=/[#\?:]/g,tn=/[#\?]/g,en=/[#\?@]/g,nn=/#/g;function rn(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function on(t){t.a||(t.a=new Fe,t.b=0,t.c&&function(t,e){if(t){t=t.split("&");for(var n=0;n<t.length;n++){var r=t[n].indexOf("="),i=null;if(0<=r){var o=t[n].substring(0,r);i=t[n].substring(r+1)}else o=t[n];e(o,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(t.c,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)}))}function sn(t){var e=xe(t);if(void 0===e)throw Error("Keys are undefined");var n=new rn(null,void 0);t=Me(t);for(var r=0;r<e.length;r++){var i=e[r],o=t[r];u(o)?cn(n,i,o):n.add(i,o)}return n}function an(t,e){on(t),e=hn(t,e),qe(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,qe((t=t.a).b,e)&&(delete t.b[e],t.c--,t.a.length>2*t.c&&Ue(t)))}function un(t,e){return on(t),e=hn(t,e),qe(t.a.b,e)}function cn(t,e,n){an(t,e),0<n.length&&(t.c=null,t.a.set(hn(t,e),q(n)),t.b+=n.length)}function hn(t,e){return e=String(e),t.f&&(e=e.toLowerCase()),e}(t=rn.prototype).add=function(t,e){on(this),this.c=null,t=hn(this,t);var n=this.a.get(t);return n||this.a.set(t,n=[]),n.push(e),this.b+=1,this},t.clear=function(){this.a=this.c=null,this.b=0},t.forEach=function(t,e){on(this),this.a.forEach(function(n,r){O(n,function(n){t.call(e,n,r,this)},this)},this)},t.U=function(){on(this);for(var t=this.a.S(),e=this.a.U(),n=[],r=0;r<e.length;r++)for(var i=t[r],o=0;o<i.length;o++)n.push(e[r]);return n},t.S=function(t){on(this);var e=[];if(r(t))un(this,t)&&(e=U(e,this.a.get(hn(this,t))));else{t=this.a.S();for(var n=0;n<t.length;n++)e=U(e,t[n])}return e},t.set=function(t,e){return on(this),this.c=null,un(this,t=hn(this,t))&&(this.b-=this.a.get(t).length),this.a.set(t,[e]),this.b+=1,this},t.get=function(t,e){return 0<(t=t?this.S(t):[]).length?String(t[0]):e},t.toString=function(){if(this.c)return this.c;if(!this.a)return"";for(var t=[],e=this.a.U(),n=0;n<e.length;n++){var r=e[n],i=encodeURIComponent(String(r));r=this.S(r);for(var o=0;o<r.length;o++){var s=i;""!==r[o]&&(s+="="+encodeURIComponent(String(r[o]))),t.push(s)}}return this.c=t.join("&")};var ln=!jt||9<=Number($t);function fn(){this.a="",this.b=dn}function pn(t){return t instanceof fn&&t.constructor===fn&&t.b===dn?t.a:(S("expected object of type Const, got '"+t+"'"),"type_error:Const")}fn.prototype.na=!0,fn.prototype.ma=function(){return this.a},fn.prototype.toString=function(){return"Const{"+this.a+"}"};var dn={};function yn(t){var e=new fn;return e.a=t,e}function mn(){this.a="",this.b=wn}function gn(t){return t instanceof mn&&t.constructor===mn&&t.b===wn?t.a:(S("expected object of type TrustedResourceUrl, got '"+t+"' of type "+s(t)),"type_error:TrustedResourceUrl")}function vn(t,e){var n=pn(t);if(!_n.test(n))throw Error("Invalid TrustedResourceUrl format: "+n);return function(t){var e=new mn;return e.a=t,e}(t=n.replace(bn,function(t,r){if(!Object.prototype.hasOwnProperty.call(e,r))throw Error('Found marker, "'+r+'", in format string, "'+n+'", but no valid label mapping found in args: '+JSON.stringify(e));return(t=e[r])instanceof fn?pn(t):encodeURIComponent(String(t))}))}yn(""),mn.prototype.na=!0,mn.prototype.ma=function(){return this.a},mn.prototype.toString=function(){return"TrustedResourceUrl{"+this.a+"}"};var bn=/%{(\w+)}/g,_n=/^(?:https:)?\/\/[0-9a-z.:[\]-]+\/|^\/[^\/\\]|^about:blank#/i,wn={};function En(){this.a="",this.b=Cn}function Tn(t){return t instanceof En&&t.constructor===En&&t.b===Cn?t.a:(S("expected object of type SafeUrl, got '"+t+"' of type "+s(t)),"type_error:SafeUrl")}En.prototype.na=!0,En.prototype.ma=function(){return this.a},En.prototype.toString=function(){return"SafeUrl{"+this.a+"}"};var Sn=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i;function In(t){return t instanceof En?t:(t=t.na?t.ma():String(t),Sn.test(t)||(t="about:invalid#zClosurez"),Nn(t))}var Cn={};function Nn(t){var e=new En;return e.a=t,e}function Dn(){this.a="",this.b=An}Nn("about:blank"),Dn.prototype.na=!0,Dn.prototype.ma=function(){return this.a},Dn.prototype.toString=function(){return"SafeHtml{"+this.a+"}"};var An={};function kn(t){var e=new Dn;return e.a=t,e}function Rn(t){var e=document;return r(t)?e.getElementById(t):t}function On(t,e){nt(e,function(e,n){e&&e.na&&(e=e.ma()),"style"==n?t.style.cssText=e:"class"==n?t.className=e:"for"==n?t.htmlFor=e:Pn.hasOwnProperty(n)?t.setAttribute(Pn[n],e):0==n.lastIndexOf("aria-",0)||0==n.lastIndexOf("data-",0)?t.setAttribute(n,e):t[n]=e})}kn("<!DOCTYPE html>"),kn(""),kn("<br>");var Pn={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(t,e,n){var i=arguments,o=document,s=String(i[0]),a=i[1];if(!ln&&a&&(a.name||a.type)){if(s=["<",s],a.name&&s.push(' name="',W(a.name),'"'),a.type){s.push(' type="',W(a.type),'"');var h={};ut(h,a),delete h.type,a=h}s.push(">"),s=s.join("")}return s=o.createElement(s),a&&(r(a)?s.className=a:u(a)?s.className=a.join(" "):On(s,a)),2<i.length&&function(t,e,n){function i(n){n&&e.appendChild(r(n)?t.createTextNode(n):n)}for(var o=2;o<n.length;o++){var s=n[o];!c(s)||l(s)&&0<s.nodeType?i(s):O(Mn(s)?q(s):s,i)}}(o,s,i),s}function Mn(t){if(t&&"number"==typeof t.length){if(l(t))return"function"==typeof t.item||"string"==typeof t.item;if(h(t))return"function"==typeof t.item}return!1}function xn(t){var e=[];return function t(e,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="",s=0;s<n;s++)r.push(o),t(e,i[s],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(s=n[i])&&(r.push(o),qn(i,r),r.push(":"),t(e,s,r),o=","));return void r.push("}")}n=n.valueOf()}switch(typeof n){case"string":qn(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(){},t,e),e.join("")}var Fn={'"':'\\"',"\\":"\\\\","/":"\\/","\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 qn(t,e){e.push('"',t.replace(Un,function(t){var e=Fn[t];return e||(e="\\u"+(65536|t.charCodeAt(0)).toString(16).substr(1),Fn[t]=e),e}),'"')}function Bn(){var t=or();return jt&&!!$t&&11==$t||/Edge\/\d+/.test(t)}function Vn(){return n.window&&n.window.location.href||self&&self.location&&self.location.href||""}function Wn(t,e){e=e||n.window;var r="about:blank";t&&(r=Tn(In(t))),e.location.href=r}function jn(t){return!!((t=(t||or()).toLowerCase()).match(/android/)||t.match(/webos/)||t.match(/iphone|ipad|ipod/)||t.match(/blackberry/)||t.match(/windows phone/)||t.match(/iemobile/))}function Kn(t){t=t||n.window;try{t.close()}catch(t){}}function Qn(t,e,n){var r=Math.floor(1e9*Math.random()).toString();e=e||500,n=n||600;var i=(window.screen.availHeight-n)/2,o=(window.screen.availWidth-e)/2;for(a in e={width:e,height:n,top:0<i?i:0,left:0<o?o:0,location:!0,resizable:!0,statusbar:!0,toolbar:!1},n=or().toLowerCase(),r&&(e.target=r,J(n,"crios/")&&(e.target="_blank")),nr(or())==tr&&(t=t||"http://localhost",e.scrollbars=!0),n=t||"",(t=e)||(t={}),r=window,e=n instanceof En?n:In(void 0!==n.href?n.href:String(n)),n=t.target||n.target,i=[],t)switch(a){case"width":case"height":case"top":case"left":i.push(a+"="+t[a]);break;case"target":case"noopener":case"noreferrer":break;default:i.push(a+"="+(t[a]?1:0))}var a=i.join(",");if((et("iPhone")&&!et("iPod")&&!et("iPad")||et("iPad")||et("iPod"))&&r.navigator&&r.navigator.standalone&&n&&"_self"!=n?(a=r.document.createElement("A"),e instanceof En||e instanceof En||(e=e.na?e.ma():String(e),Sn.test(e)||(e="about:invalid#zClosurez"),e=Nn(e)),a.href=Tn(e),a.setAttribute("target",n),t.noreferrer&&a.setAttribute("rel","noreferrer"),(t=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,r,1),a.dispatchEvent(t),a={}):t.noreferrer?(a=r.open("",n,a),t=Tn(e),a&&(Qt&&J(t,";")&&(t="'"+t.replace(/'/g,"%27")+"'"),a.opener=null,yn("b/12014412, meta tag with sanitized URL"),t=kn(t='<meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0; url='+W(t)+'">'),a.document.write(function(t){return t instanceof Dn&&t.constructor===Dn&&t.b===An?t.a:(S("expected object of type SafeHtml, got '"+t+"' of type "+s(t)),"type_error:SafeHtml")}(t)),a.document.close())):(a=r.open(Tn(e),n,a))&&t.noopener&&(a.opener=null),a)try{a.focus()}catch(t){}return a}var Hn=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;function zn(){var t=null;return new dt(function(e){"complete"==n.document.readyState?e():(t=function(){e()},be(window,"load",t))}).s(function(e){throw _e(window,"load",t),e})}function Yn(t){return t=t||or(),!("file:"!==hr()||!t.toLowerCase().match(/iphone|ipad|ipod|android/))}function Xn(){var t=n.window;try{return!(!t||t==t.top)}catch(t){return!1}}function Jn(){return"object"!=typeof n.window&&"function"==typeof n.importScripts}function $n(){return Gn.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":Gn.INTERNAL.hasOwnProperty("node")?"Node":Jn()?"Worker":"Browser"}function Zn(){var t=$n();return"ReactNative"===t||"Node"===t}var tr="Firefox",er="Chrome";function nr(t){var e=t.toLowerCase();return J(e,"opera/")||J(e,"opr/")||J(e,"opios/")?"Opera":J(e,"iemobile")?"IEMobile":J(e,"msie")||J(e,"trident/")?"IE":J(e,"edge/")?"Edge":J(e,"firefox/")?tr:J(e,"silk/")?"Silk":J(e,"blackberry")?"Blackberry":J(e,"webos")?"Webos":!J(e,"safari/")||J(e,"chrome/")||J(e,"crios/")||J(e,"android")?!J(e,"chrome/")&&!J(e,"crios/")||J(e,"edge/")?J(e,"android")?"Android":(t=t.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==t.length?t[1]:"Other":er:"Safari"}var rr={Uc:"FirebaseCore-web",Wc:"FirebaseUI-web"};function ir(t,e){e=e||[];var n,r=[],i={};for(n in rr)i[rr[n]]=!0;for(n=0;n<e.length;n++)void 0!==i[e[n]]&&(delete i[e[n]],r.push(e[n]));return r.sort(),(e=r).length||(e=["FirebaseCore-web"]),"Browser"===(r=$n())?r=nr(i=or()):"Worker"===r&&(r=nr(i=or())+"-"+r),r+"/JsCore/"+t+"/"+e.join(",")}function or(){return n.navigator&&n.navigator.userAgent||""}function sr(t,e){t=t.split("."),e=e||n;for(var r=0;r<t.length&&"object"==typeof e&&null!=e;r++)e=e[t[r]];return r!=t.length&&(e=void 0),e}function ar(){try{var t=n.localStorage,e=yr();if(t)return t.setItem(e,"1"),t.removeItem(e),!Bn()||!!n.indexedDB}catch(t){return Jn()&&!!n.indexedDB}return!1}function ur(){return(cr()||"chrome-extension:"===hr()||Yn())&&!Zn()&&ar()&&!Jn()}function cr(){return"http:"===hr()||"https:"===hr()}function hr(){return n.location&&n.location.protocol||null}function lr(t){return!jn(t=t||or())&&nr(t)!=tr}function fr(t){return void 0===t?null:xn(t)}function pr(t){var e,n={};for(e in t)t.hasOwnProperty(e)&&null!==t[e]&&void 0!==t[e]&&(n[e]=t[e]);return n}function dr(t){if(null!==t)return JSON.parse(t)}function yr(t){return t||Math.floor(1e9*Math.random()).toString()}function mr(t){return"Safari"!=nr(t=t||or())&&!t.toLowerCase().match(/iphone|ipad|ipod/)}function gr(){var t=n.___jsl;if(t&&t.H)for(var e in t.H)if(t.H[e].r=t.H[e].r||[],t.H[e].L=t.H[e].L||[],t.H[e].r=t.H[e].L.concat(),t.CP)for(var r=0;r<t.CP.length;r++)t.CP[r]=null}function vr(t,e){if(t>e)throw Error("Short delay should be less than long delay!");this.a=t,this.c=e,t=or(),e=$n(),this.b=jn(t)||"ReactNative"===e}function br(){var t=n.document;return!t||void 0===t.visibilityState||"visible"==t.visibilityState}function _r(t){try{var e=new Date(parseInt(t,10));if(!isNaN(e.getTime())&&!/[^0-9]/.test(t))return e.toUTCString()}catch(t){}return null}function wr(){return!(!sr("fireauth.oauthhelper",n)&&!sr("fireauth.iframe",n))}vr.prototype.get=function(){var t=n.navigator;return!t||"boolean"!=typeof t.onLine||!cr()&&"chrome-extension:"!==hr()&&void 0===t.connection||t.onLine?this.b?this.c:this.a:Math.min(5e3,this.a)};var Er,Tr={};function Sr(t){Tr[t]||(Tr[t]=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(t))}try{var Ir={};Object.defineProperty(Ir,"abcd",{configurable:!0,enumerable:!0,value:1}),Object.defineProperty(Ir,"abcd",{configurable:!0,enumerable:!0,value:2}),Er=2==Ir.abcd}catch(Vt){Er=!1}function Cr(t,e,n){Er?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n}):t[e]=n}function Nr(t,e){if(e)for(var n in e)e.hasOwnProperty(n)&&Cr(t,n,e[n])}function Dr(t){var e={};return Nr(e,t),e}function Ar(t){var e=t;if("object"==typeof t&&null!=t)for(var n in e="length"in t?[]:{},t)Cr(e,n,Ar(t[n]));return e}var kr="EMAIL_SIGNIN",Rr="email",Or="newEmail",Pr="requestType",Lr="email",Mr="fromEmail",xr="data",Fr="operation";function Ur(t,e){this.code=Br+t,this.message=e||Vr[t]||""}function qr(t){var e=t&&t.code;return e?new Ur(e.substring(Br.length),t.message):null}b(Ur,Error),Ur.prototype.C=function(){return{code:this.code,message:this.message}},Ur.prototype.toJSON=function(){return this.C()};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-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","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-or-invalid-nonce":"The OIDC ID token requires a valid unhashed nonce.","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 Wr(t){var e=t[Gr];if(void 0===e)throw new Ur("missing-continue-uri");if("string"!=typeof e||"string"==typeof e&&!e.length)throw new Ur("invalid-continue-uri");this.h=e,this.b=this.a=null,this.g=!1;var n=t[jr];if(n&&"object"==typeof n){e=n[Xr];var r=n[zr];if(n=n[Yr],"string"==typeof e&&e.length){if(this.a=e,void 0!==r&&"boolean"!=typeof r)throw new Ur("argument-error",zr+" property must be a boolean when specified.");if(this.g=!!r,void 0!==n&&("string"!=typeof n||"string"==typeof n&&!n.length))throw new Ur("argument-error",Yr+" property must be a non empty string when specified.");this.b=n||null}else{if(void 0!==e)throw new Ur("argument-error",Xr+" property must be a non empty string when specified.");if(void 0!==r||void 0!==n)throw new Ur("missing-android-pkg-name")}}else if(void 0!==n)throw new Ur("argument-error",jr+" property must be a non null object when specified.");if(this.f=null,(e=t[Hr])&&"object"==typeof e){if("string"==typeof(e=e[Jr])&&e.length)this.f=e;else if(void 0!==e)throw new Ur("argument-error",Jr+" property must be a non empty string when specified.")}else if(void 0!==e)throw new Ur("argument-error",Hr+" property must be a non null object when specified.");if(void 0!==(e=t[Qr])&&"boolean"!=typeof e)throw new Ur("argument-error",Qr+" property must be a boolean when specified.");if(this.c=!!e,void 0!==(t=t[Kr])&&("string"!=typeof t||"string"==typeof t&&!t.length))throw new Ur("argument-error",Kr+" property must be a non empty string when specified.");this.i=t||null}var jr="android",Kr="dynamicLinkDomain",Qr="handleCodeInApp",Hr="iOS",Gr="url",zr="installApp",Yr="minimumVersion",Xr="packageName",Jr="bundleId";function $r(t){var e={};for(var n in e.continueUrl=t.h,e.canHandleCodeInApp=t.c,(e.androidPackageName=t.a)&&(e.androidMinimumVersion=t.b,e.androidInstallApp=t.g),e.iOSBundleId=t.f,e.dynamicLinkDomain=t.i,e)null===e[n]&&delete e[n];return e}var Zr=null,ti=null;function ei(t){var e="";return function(t,e){function n(e){for(;r<t.length;){var n=t.charAt(r++),i=ti[n];if(null!=i)return i;if(!/^[\s\xa0]*$/.test(n))throw Error("Unknown base64 encoding at char: "+n)}return e}!function(){if(!Zr){Zr={},ti={};for(var t=0;65>t;t++)Zr[t]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(t),ti[Zr[t]]=t,62<=t&&(ti["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(t)]=t)}}();for(var r=0;;){var i=n(-1),o=n(0),s=n(64),a=n(64);if(64===a&&-1===i)break;e(i<<2|o>>4),64!=s&&(e(o<<4&240|s>>2),64!=a&&e(s<<6&192|a))}}(t,function(t){e+=String.fromCharCode(t)}),e}function ni(t){this.c=t.sub,this.a=t.provider_id||t.firebase&&t.firebase.sign_in_provider||null,this.b=!!t.is_anonymous||"anonymous"==this.a}function ri(t){return(t=ii(t))&&t.sub&&t.iss&&t.aud&&t.exp?new ni(t):null}function ii(t){if(!t)return null;if(3!=(t=t.split(".")).length)return null;for(var e=(4-(t=t[1]).length%4)%4,n=0;n<e;n++)t+=".";try{return JSON.parse(ei(t))}catch(t){}return null}ni.prototype.f=function(){return this.b};var oi,si={$c:{ab:"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",ib:"https://securetoken.googleapis.com/v1/token",id:"p"},bd:{ab:"https://staging-www.sandbox.googleapis.com/identitytoolkit/v3/relyingparty/",ib:"https://staging-securetoken.sandbox.googleapis.com/v1/token",id:"s"},cd:{ab:"https://www-googleapis-test.sandbox.google.com/identitytoolkit/v3/relyingparty/",ib:"https://test-securetoken.sandbox.googleapis.com/v1/token",id:"t"}};function ai(t){for(var e in si)if(si[e].id===t)return{firebaseEndpoint:(t=si[e]).ab,secureTokenEndpoint:t.ib};return null}oi=ai("__EID__")?"__EID__":void 0;var ui="oauth_consumer_key oauth_nonce oauth_signature oauth_signature_method oauth_timestamp oauth_token oauth_version".split(" "),ci=["client_id","response_type","scope","redirect_uri","state"],hi={Vc:{Ma:"locale",Ba:500,Aa:600,Na:"facebook.com",hb:ci},Xc:{Ma:null,Ba:500,Aa:620,Na:"github.com",hb:ci},Yc:{Ma:"hl",Ba:515,Aa:680,Na:"google.com",hb:ci},dd:{Ma:"lang",Ba:485,Aa:705,Na:"twitter.com",hb:ui}};function li(t){for(var e in hi)if(hi[e].Na==t)return hi[e];return null}function fi(t){var e={};e["facebook.com"]=gi,e["google.com"]=bi,e["github.com"]=vi,e["twitter.com"]=_i;var n=t&&t[di];try{if(n)return e[n]?new e[n](t):new mi(t);if(void 0!==t[pi])return new yi(t)}catch(t){}return null}var pi="idToken",di="providerId";function yi(t){var e=t[di];if(!e&&t[pi]){var n=ri(t[pi]);n&&n.a&&(e=n.a)}if(!e)throw Error("Invalid additional user info!");"anonymous"!=e&&"custom"!=e||(e=null),n=!1,void 0!==t.isNewUser?n=!!t.isNewUser:"identitytoolkit#SignupNewUserResponse"===t.kind&&(n=!0),Cr(this,"providerId",e),Cr(this,"isNewUser",n)}function mi(t){yi.call(this,t),Cr(this,"profile",Ar((t=dr(t.rawUserInfo||"{}"))||{}))}function gi(t){if(mi.call(this,t),"facebook.com"!=this.providerId)throw Error("Invalid provider ID!")}function vi(t){if(mi.call(this,t),"github.com"!=this.providerId)throw Error("Invalid provider ID!");Cr(this,"username",this.profile&&this.profile.login||null)}function bi(t){if(mi.call(this,t),"google.com"!=this.providerId)throw Error("Invalid provider ID!")}function _i(t){if(mi.call(this,t),"twitter.com"!=this.providerId)throw Error("Invalid provider ID!");Cr(this,"username",t.screenName||null)}function wi(t){var e=Ge(t),n=He(e,"link"),r=He(Ge(n),"link");return He(Ge(e=He(e,"deep_link_id")),"link")||e||r||n||t}function Ei(t,e){return t.then(function(t){if(t[os]){var n=ri(t[os]);if(!n||e!=n.c)throw new Ur("user-mismatch");return t}throw new Ur("user-mismatch")}).s(function(t){throw t&&t.code&&t.code==Br+"user-not-found"?new Ur("user-mismatch"):t})}function Ti(t,e){if(!e)throw new Ur("internal-error","failed to construct a credential");this.a=e,Cr(this,"providerId",t),Cr(this,"signInMethod",t)}function Si(t){return{pendingToken:t.a,requestUri:"http://localhost"}}function Ii(t,e,n){if(this.a=null,e.idToken||e.accessToken)e.idToken&&Cr(this,"idToken",e.idToken),e.accessToken&&Cr(this,"accessToken",e.accessToken),e.nonce&&!e.pendingToken&&Cr(this,"nonce",e.nonce),e.pendingToken&&(this.a=e.pendingToken);else{if(!e.oauthToken||!e.oauthTokenSecret)throw new Ur("internal-error","failed to construct a credential");Cr(this,"accessToken",e.oauthToken),Cr(this,"secret",e.oauthTokenSecret)}Cr(this,"providerId",t),Cr(this,"signInMethod",n)}function Ci(t){var e={};return t.idToken&&(e.id_token=t.idToken),t.accessToken&&(e.access_token=t.accessToken),t.secret&&(e.oauth_token_secret=t.secret),e.providerId=t.providerId,t.nonce&&!t.a&&(e.nonce=t.nonce),e={postBody:sn(e).toString(),requestUri:"http://localhost"},t.a&&(delete e.postBody,e.pendingToken=t.a),e}function Ni(t,e){this.Dc=e||[],Nr(this,{providerId:t,isOAuthProvider:!0}),this.yb={},this.cb=(li(t)||{}).Ma||null,this.$a=null}function Di(t){if("string"!=typeof t||0!=t.indexOf("saml."))throw new Ur("argument-error",'SAML provider IDs must be prefixed with "saml."');Ni.call(this,t,[])}function Ai(t){Ni.call(this,t,ci),this.a=[]}function ki(){Ai.call(this,"facebook.com")}function Ri(t){if(!t)throw new Ur("argument-error","credential failed: expected 1 argument (the OAuth access token).");var e=t;return l(t)&&(e=t.accessToken),(new ki).credential(null,e)}function Oi(){Ai.call(this,"github.com")}function Pi(t){if(!t)throw new Ur("argument-error","credential failed: expected 1 argument (the OAuth access token).");var e=t;return l(t)&&(e=t.accessToken),(new Oi).credential(null,e)}function Li(){Ai.call(this,"google.com"),this.ua("profile")}function Mi(t,e){var n=t;return l(t)&&(n=t.idToken,e=t.accessToken),(new Li).credential(n,e)}function xi(){Ni.call(this,"twitter.com",ui)}function Fi(t,e){var n=t;if(l(n)||(n={oauthToken:t,oauthTokenSecret:e}),!n.oauthToken||!n.oauthTokenSecret)throw new Ur("argument-error","credential failed: expected 2 arguments (the OAuth access token and secret).");return new Ii("twitter.com",n,"twitter.com")}function Ui(t,e,n){this.a=t,this.c=e,Cr(this,"providerId","password"),Cr(this,"signInMethod",n===qi.EMAIL_LINK_SIGN_IN_METHOD?qi.EMAIL_LINK_SIGN_IN_METHOD:qi.EMAIL_PASSWORD_SIGN_IN_METHOD)}function qi(){Nr(this,{providerId:"password",isOAuthProvider:!1})}function Bi(t,e){if(!(e=Vi(e)))throw new Ur("argument-error","Invalid email link!");return new Ui(t,e,qi.EMAIL_LINK_SIGN_IN_METHOD)}function Vi(t){var e=He((t=new function(t){this.a=Ge(t)}(t=wi(t))).a,"oobCode")||null;return"signIn"===(He(t.a,"mode")||null)&&e?e:null}function Wi(t){if(!(t.Ta&&t.Sa||t.Fa&&t.$))throw new Ur("internal-error");this.a=t,Cr(this,"providerId","phone"),Cr(this,"signInMethod","phone")}function ji(t){return t.a.Fa&&t.a.$?{temporaryProof:t.a.Fa,phoneNumber:t.a.$}:{sessionInfo:t.a.Ta,code:t.a.Sa}}function Ki(t){try{this.a=t||Gn.auth()}catch(t){throw new Ur("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().")}Nr(this,{providerId:"phone",isOAuthProvider:!1})}function Qi(t,e){if(!t)throw new Ur("missing-verification-id");if(!e)throw new Ur("missing-verification-code");return new Wi({Ta:t,Sa:e})}function Hi(t){if(t.temporaryProof&&t.phoneNumber)return new Wi({Fa:t.temporaryProof,$:t.phoneNumber});var e=t&&t.providerId;if(!e||"password"===e)return null;var n=t&&t.oauthAccessToken,r=t&&t.oauthTokenSecret,i=t&&t.nonce,o=t&&t.oauthIdToken,s=t&&t.pendingToken;try{switch(e){case"google.com":return Mi(o,n);case"facebook.com":return Ri(n);case"github.com":return Pi(n);case"twitter.com":return Fi(n,r);default:return n||r||o||s?s?0==e.indexOf("saml.")?new Ti(e,s):new Ii(e,{pendingToken:s,idToken:t.oauthIdToken,accessToken:t.oauthAccessToken},e):new Ai(e).credential(o,n,i):null}}catch(t){return null}}function Gi(t){if(!t.isOAuthProvider)throw new Ur("invalid-oauth-provider")}function zi(t,e,n,r,i,o){if(this.b=t,this.c=e||null,this.f=n||null,this.g=r||null,this.h=o||null,this.a=i||null,!this.f&&!this.a)throw new Ur("invalid-auth-event");if(this.f&&this.a)throw new Ur("invalid-auth-event");if(this.f&&!this.g)throw new Ur("invalid-auth-event")}function Yi(t){return(t=t||{}).type?new zi(t.type,t.eventId,t.urlResponse,t.sessionId,t.error&&qr(t.error),t.postBody):null}function Xi(){this.b=null,this.a=[]}b(mi,yi),b(gi,mi),b(vi,mi),b(bi,mi),b(_i,mi),Ti.prototype.la=function(t){return Ts(t,Si(this))},Ti.prototype.b=function(t,e){var n=Si(this);return n.idToken=e,Ss(t,n)},Ti.prototype.f=function(t,e){return Ei(Is(t,Si(this)),e)},Ti.prototype.C=function(){return{providerId:this.providerId,signInMethod:this.signInMethod,pendingToken:this.a}},Ii.prototype.la=function(t){return Ts(t,Ci(this))},Ii.prototype.b=function(t,e){var n=Ci(this);return n.idToken=e,Ss(t,n)},Ii.prototype.f=function(t,e){return Ei(Is(t,Ci(this)),e)},Ii.prototype.C=function(){var t={providerId:this.providerId,signInMethod:this.signInMethod};return this.idToken&&(t.oauthIdToken=this.idToken),this.accessToken&&(t.oauthAccessToken=this.accessToken),this.secret&&(t.oauthTokenSecret=this.secret),this.nonce&&(t.nonce=this.nonce),this.a&&(t.pendingToken=this.a),t},Ni.prototype.Da=function(t){return this.yb=it(t),this},b(Di,Ni),b(Ai,Ni),Ai.prototype.ua=function(t){return M(this.a,t)||this.a.push(t),this},Ai.prototype.Eb=function(){return q(this.a)},Ai.prototype.credential=function(t,e,n){if(!t&&!e)throw new Ur("argument-error","credential failed: must provide the ID token and/or the access token.");return new Ii(this.providerId,{idToken:t||null,accessToken:e||null,nonce:n||null},this.providerId)},b(ki,Ai),Cr(ki,"PROVIDER_ID","facebook.com"),Cr(ki,"FACEBOOK_SIGN_IN_METHOD","facebook.com"),b(Oi,Ai),Cr(Oi,"PROVIDER_ID","github.com"),Cr(Oi,"GITHUB_SIGN_IN_METHOD","github.com"),b(Li,Ai),Cr(Li,"PROVIDER_ID","google.com"),Cr(Li,"GOOGLE_SIGN_IN_METHOD","google.com"),b(xi,Ni),Cr(xi,"PROVIDER_ID","twitter.com"),Cr(xi,"TWITTER_SIGN_IN_METHOD","twitter.com"),Ui.prototype.la=function(t){return this.signInMethod==qi.EMAIL_LINK_SIGN_IN_METHOD?ta(t,Ps,{email:this.a,oobCode:this.c}):ta(t,Xs,{email:this.a,password:this.c})},Ui.prototype.b=function(t,e){return this.signInMethod==qi.EMAIL_LINK_SIGN_IN_METHOD?ta(t,Ls,{idToken:e,email:this.a,oobCode:this.c}):ta(t,Ks,{idToken:e,email:this.a,password:this.c})},Ui.prototype.f=function(t,e){return Ei(this.la(t),e)},Ui.prototype.C=function(){return{email:this.a,password:this.c,signInMethod:this.signInMethod}},Nr(qi,{PROVIDER_ID:"password"}),Nr(qi,{EMAIL_LINK_SIGN_IN_METHOD:"emailLink"}),Nr(qi,{EMAIL_PASSWORD_SIGN_IN_METHOD:"password"}),Wi.prototype.la=function(t){return t.Ua(ji(this))},Wi.prototype.b=function(t,e){var n=ji(this);return n.idToken=e,ta(t,$s,n)},Wi.prototype.f=function(t,e){var n=ji(this);return n.operation="REAUTH",Ei(t=ta(t,Zs,n),e)},Wi.prototype.C=function(){var t={providerId:"phone"};return this.a.Ta&&(t.verificationId=this.a.Ta),this.a.Sa&&(t.verificationCode=this.a.Sa),this.a.Fa&&(t.temporaryProof=this.a.Fa),this.a.$&&(t.phoneNumber=this.a.$),t},Ki.prototype.Ua=function(t,e){var n=this.a.b;return wt(e.verify()).then(function(i){if(!r(i))throw new Ur("argument-error","An implementation of firebase.auth.ApplicationVerifier.prototype.verify() must return a firebase.Promise that resolves with a string.");switch(e.type){case"recaptcha":return function(t,e){return ta(t,Ws,e)}(n,{phoneNumber:t,recaptchaToken:i}).then(function(t){return"function"==typeof e.reset&&e.reset(),t},function(t){throw"function"==typeof e.reset&&e.reset(),t});default:throw new Ur("argument-error",'Only firebase.auth.ApplicationVerifiers with type="recaptcha" are currently supported.')}})},Nr(Ki,{PROVIDER_ID:"phone"}),Nr(Ki,{PHONE_SIGN_IN_METHOD:"phone"}),zi.prototype.C=function(){return{type:this.b,eventId:this.c,urlResponse:this.f,sessionId:this.g,postBody:this.h,error:this.a&&this.a.C()}};var Ji=null;function $i(t){var e="unauthorized-domain",n=void 0,r=Ge(t);t=r.b,"chrome-extension"==(r=r.c)?n=B("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.",t):"http"==r||"https"==r?n=B("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.",t):e="operation-not-supported-in-this-environment",Ur.call(this,e,n)}function Zi(t,e,n){Ur.call(this,t,n),(t=e||{}).zb&&Cr(this,"email",t.zb),t.$&&Cr(this,"phoneNumber",t.$),t.credential&&Cr(this,"credential",t.credential)}function to(t){if(t.code){var e=t.code||"";0==e.indexOf(Br)&&(e=e.substring(Br.length));var n={credential:Hi(t)};if(t.email)n.zb=t.email;else if(t.phoneNumber)n.$=t.phoneNumber;else if(!n.credential)return new Ur(e,t.message||void 0);return new Zi(e,n,t.message)}return null}Xi.prototype.subscribe=function(t){var e=this;this.a.push(t),this.b||(this.b=function(t){for(var n=0;n<e.a.length;n++)e.a[n](t)},"function"==typeof(t=sr("universalLinks.subscribe",n))&&t(null,this.b))},Xi.prototype.unsubscribe=function(t){F(this.a,function(e){return e==t})},b($i,Ur),b(Zi,Ur),Zi.prototype.C=function(){var t={code:this.code,message:this.message};this.email&&(t.email=this.email),this.phoneNumber&&(t.phoneNumber=this.phoneNumber);var e=this.credential&&this.credential.C();return e&&ut(t,e),t},Zi.prototype.toJSON=function(){return this.C()};var eo,no=/^[+a-zA-Z0-9_.!#$%&'*\/=?^`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{2,63}$/;function ro(){}function io(t){return t.c||(t.c=t.b())}function oo(){}function so(t){if(!t.f&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],n=0;n<e.length;n++){var r=e[n];try{return new ActiveXObject(r),t.f=r}catch(t){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed")}return t.f}function ao(){}function uo(){this.a=new XDomainRequest,this.readyState=0,this.onreadystatechange=null,this.responseText="",this.status=-1,this.statusText="",this.a.onload=m(this.ec,this),this.a.onerror=m(this.Fb,this),this.a.onprogress=m(this.fc,this),this.a.ontimeout=m(this.ic,this)}function co(t,e){t.readyState=e,t.onreadystatechange&&t.onreadystatechange()}function ho(t,e,n){this.reset(t,e,n,void 0,void 0)}function lo(t){this.f=t,this.b=this.c=this.a=null}function fo(t,e){this.name=t,this.value=e}ro.prototype.c=null,b(oo,ro),oo.prototype.a=function(){var t=so(this);return t?new ActiveXObject(t):new XMLHttpRequest},oo.prototype.b=function(){var t={};return so(this)&&(t[0]=!0,t[1]=!0),t},eo=new oo,b(ao,ro),ao.prototype.a=function(){var t=new XMLHttpRequest;if("withCredentials"in t)return t;if("undefined"!=typeof XDomainRequest)return new uo;throw Error("Unsupported browser")},ao.prototype.b=function(){return{}},(t=uo.prototype).open=function(t,e,n){if(null!=n&&!n)throw Error("Only async requests are supported.");this.a.open(t,e)},t.send=function(t){if(t){if("string"!=typeof t)throw Error("Only string data is supported");this.a.send(t)}else this.a.send()},t.abort=function(){this.a.abort()},t.setRequestHeader=function(){},t.getResponseHeader=function(t){return"content-type"==t.toLowerCase()?this.a.contentType:""},t.ec=function(){this.status=200,this.responseText=this.a.responseText,co(this,4)},t.Fb=function(){this.status=500,this.responseText="",co(this,4)},t.ic=function(){this.Fb()},t.fc=function(){this.status=200,co(this,1)},t.getAllResponseHeaders=function(){return"content-type: "+this.a.contentType},ho.prototype.a=null,ho.prototype.reset=function(t,e,n,r,i){delete this.a},fo.prototype.toString=function(){return this.name};var po=new fo("SEVERE",1e3),yo=new fo("WARNING",900),mo=new fo("CONFIG",700),go=new fo("FINE",500);lo.prototype.log=function(t,e,n){if(t.value>=function t(e){return e.c?e.c:e.a?t(e.a):(S("Root logger has no level set."),null)}(this).value)for(h(e)&&(e=e()),t=new ho(t,String(e),this.f),n&&(t.a=n),n=this;n;)n=n.a};var vo={},bo=null;function _o(t){var e;if(bo||(bo=new lo(""),vo[""]=bo,bo.c=mo),!(e=vo[t])){e=new lo(t);var n=t.lastIndexOf("."),r=t.substr(n+1);(n=_o(t.substr(0,n))).b||(n.b={}),n.b[r]=e,e.a=n,vo[t]=e}return e}function wo(t,e){t&&t.log(go,e,void 0)}function Eo(t){this.f=t}function To(t){Ae.call(this),this.i=t,this.readyState=So,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=_o("goog.net.FetchXmlHttp")}b(Eo,ro),Eo.prototype.a=function(){return new To(this.f)},Eo.prototype.b=function(t){return function(){return t}}({}),b(To,Ae);var So=0;function Io(t){t.onreadystatechange&&t.onreadystatechange.call(t)}function Co(t){Ae.call(this),this.headers=new Fe,this.D=t||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=No,this.v=this.O=!1}(t=To.prototype).open=function(t,e){if(this.readyState!=So)throw this.abort(),Error("Error reopening a connection");this.h=t,this.c=e,this.readyState=1,Io(this)},t.send=function(t){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.a=!0;var e={headers:this.g,method:this.h,credentials:void 0,cache:void 0};t&&(e.body=t),this.i.fetch(new Request(this.c,e)).then(this.hc.bind(this),this.Gb.bind(this))},t.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,Io(this)),this.readyState=So},t.hc=function(t){this.a&&(this.b||(this.b=t.headers,this.readyState=2,Io(this)),this.a&&(this.readyState=3,Io(this),this.a&&t.text().then(this.gc.bind(this,t),this.Gb.bind(this))))},t.gc=function(t,e){this.a&&(this.status=t.status,this.statusText=t.statusText,this.responseText=e,this.readyState=4,Io(this))},t.Gb=function(t){var e=this.f;e&&e.log(yo,"Failed to fetch url "+this.c,t instanceof Error?t:Error(t)),this.a&&(this.readyState=4,Io(this))},t.setRequestHeader=function(t,e){this.g.append(t,e)},t.getResponseHeader=function(t){return this.b?this.b.get(t.toLowerCase())||"":((t=this.f)&&t.log(yo,"Attempting to get response header but no headers have been received for url: "+this.c,void 0),"")},t.getAllResponseHeaders=function(){if(!this.b){var t=this.f;return t&&t.log(yo,"Attempting to get all response headers but no headers have been received for url: "+this.c,void 0),""}t=[];for(var e=this.b.entries(),n=e.next();!n.done;)n=n.value,t.push(n[0]+": "+n[1]),n=e.next();return t.join("\r\n")},b(Co,Ae);var No="";Co.prototype.b=_o("goog.net.XhrIo");var Do=/^https?$/i,Ao=["POST","PUT"];function ko(t,e,i,o,s){if(t.a)throw Error("[goog.net.XhrIo] Object is active with another request="+t.m+"; newUri="+e);i=i?i.toUpperCase():"GET",t.m=e,t.h="",t.N=i,t.G=!1,t.c=!0,t.a=t.D?t.D.a():eo.a(),t.w=t.D?io(t.D):io(eo),t.a.onreadystatechange=m(t.Jb,t);try{wo(t.b,qo(t,"Opening Xhr")),t.I=!0,t.a.open(i,String(e),!0),t.I=!1}catch(e){return wo(t.b,qo(t,"Error opening Xhr: "+e.message)),void Oo(t,e)}e=o||"";var a=new Fe(t.headers);s&&function(t,e){if(t.forEach&&"function"==typeof t.forEach)t.forEach(e,void 0);else if(c(t)||r(t))O(t,e,void 0);else for(var n=xe(t),i=Me(t),o=i.length,s=0;s<o;s++)e.call(void 0,i[s],n&&n[s],t)}(s,function(t,e){a.set(e,t)}),s=function(t){t:{for(var e=Ro,n=t.length,i=r(t)?t.split(""):t,o=0;o<n;o++)if(o in i&&e.call(void 0,i[o],o,t)){e=o;break t}e=-1}return 0>e?null:r(t)?t.charAt(e):t[e]}(a.U()),o=n.FormData&&e instanceof n.FormData,!M(Ao,i)||s||o||a.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),a.forEach(function(t,e){this.a.setRequestHeader(e,t)},t),t.o&&(t.a.responseType=t.o),"withCredentials"in t.a&&t.a.withCredentials!==t.O&&(t.a.withCredentials=t.O);try{xo(t),0<t.g&&(t.v=function(t){return jt&&te(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}(t.a),wo(t.b,qo(t,"Will abort after "+t.g+"ms if incomplete, xhr2 "+t.v)),t.v?(t.a.timeout=t.g,t.a.ontimeout=m(t.Ga,t)):t.u=Pe(t.Ga,t.g,t)),wo(t.b,qo(t,"Sending request")),t.i=!0,t.a.send(e),t.i=!1}catch(e){wo(t.b,qo(t,"Send error: "+e.message)),Oo(t,e)}}function Ro(t){return"content-type"==t.toLowerCase()}function Oo(t,e){t.c=!1,t.a&&(t.f=!0,t.a.abort(),t.f=!1),t.h=e,Po(t),Mo(t)}function Po(t){t.G||(t.G=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function Lo(t){if(t.c&&void 0!==e)if(t.w[1]&&4==Fo(t)&&2==Uo(t))wo(t.b,qo(t,"Local request error detected and ignored"));else if(t.i&&4==Fo(t))Pe(t.Jb,0,t);else if(t.dispatchEvent("readystatechange"),4==Fo(t)){wo(t.b,qo(t,"Request complete")),t.c=!1;try{var r,i=Uo(t);t:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var o=!0;break t;default:o=!1}if(!(r=o)){var s;if(s=0===i){var a=String(t.m).match(Be)[1]||null;if(!a&&n.self&&n.self.location){var u=n.self.location.protocol;a=u.substr(0,u.length-1)}s=!Do.test(a?a.toLowerCase():"")}r=s}if(r)t.dispatchEvent("complete"),t.dispatchEvent("success");else{try{var c=2<Fo(t)?t.a.statusText:""}catch(e){wo(t.b,"Can not get status: "+e.message),c=""}t.h=c+" ["+Uo(t)+"]",Po(t)}}finally{Mo(t)}}}function Mo(t,e){if(t.a){xo(t);var n=t.a,r=t.w[0]?o:null;t.a=null,t.w=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(e){(t=t.b)&&t.log(po,"Problem encountered resetting onreadystatechange: "+e.message,void 0)}}}function xo(t){t.a&&t.v&&(t.a.ontimeout=null),t.u&&(n.clearTimeout(t.u),t.u=null)}function Fo(t){return t.a?t.a.readyState:0}function Uo(t){try{return 2<Fo(t)?t.a.status:-1}catch(t){return-1}}function qo(t,e){return e+" ["+t.N+" "+t.m+" "+Uo(t)+"]"}function Bo(t,e){this.g=[],this.v=t,this.u=e||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 Vo(t,e,n){t.a=!0,t.c=n,t.f=!e,Qo(t)}function Wo(t){if(t.a){if(!t.m)throw new Ho(t);t.m=!1}}function jo(t,e,n,r){t.g.push([e,n,r]),t.a&&Qo(t)}function Ko(t){return L(t.g,function(t){return h(t[1])})}function Qo(t){if(t.h&&t.a&&Ko(t)){var e=t.h,r=Yo[e];r&&(n.clearTimeout(r.a),delete Yo[e]),t.h=0}t.b&&(t.b.l--,delete t.b),e=t.c;for(var i=r=!1;t.g.length&&!t.i;){var o=t.g.shift(),s=o[0],a=o[1];if(o=o[2],s=t.f?a:s)try{var u=s.call(o||t.u,e);void 0!==u&&(t.f=t.f&&(u==e||u instanceof Error),t.c=e=u),(w(e)||"function"==typeof n.Promise&&e instanceof n.Promise)&&(i=!0,t.i=!0)}catch(n){e=n,t.f=!0,Ko(t)||(r=!0)}}t.c=e,i&&(u=m(t.o,t,!0),i=m(t.o,t,!1),e instanceof Bo?(jo(e,u,i),e.w=!0):e.then(u,i)),r&&(e=new zo(e),Yo[e.a]=e,t.h=e.a)}function Ho(){E.call(this)}function Go(){E.call(this)}function zo(t){this.a=n.setTimeout(m(this.c,this),0),this.b=t}(t=Co.prototype).Ga=function(){void 0!==e&&this.a&&(this.h="Timed out after "+this.g+"ms, aborting",wo(this.b,qo(this,this.h)),this.dispatchEvent("timeout"),this.abort(8))},t.abort=function(){this.a&&this.c&&(wo(this.b,qo(this,"Aborting")),this.c=!1,this.f=!0,this.a.abort(),this.f=!1,this.dispatchEvent("complete"),this.dispatchEvent("abort"),Mo(this))},t.va=function(){this.a&&(this.c&&(this.c=!1,this.f=!0,this.a.abort(),this.f=!1),Mo(this,!0)),Co.ob.va.call(this)},t.Jb=function(){this.qa||(this.I||this.i||this.f?Lo(this):this.wc())},t.wc=function(){Lo(this)},t.getResponse=function(){try{if(!this.a)return null;if("response"in this.a)return this.a.response;switch(this.o){case No:case"text":return this.a.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in this.a)return this.a.mozResponseArrayBuffer}var t=this.b;return t&&t.log(po,"Response type "+this.o+" is not supported on this browser",void 0),null}catch(t){return wo(this.b,"Can not get response: "+t.message),null}},Bo.prototype.cancel=function(t){if(this.a)this.c instanceof Bo&&this.c.cancel();else{if(this.b){var e=this.b;delete this.b,t?e.cancel(t):(e.l--,0>=e.l&&e.cancel())}this.v?this.v.call(this.u,this):this.m=!0,this.a||(t=new Go(this),Wo(this),Vo(this,!1,t))}},Bo.prototype.o=function(t,e){this.i=!1,Vo(this,t,e)},Bo.prototype.D=function(){Wo(this),Vo(this,!0,null)},Bo.prototype.then=function(t,e,n){var r,i,o=new dt(function(t,e){r=t,i=e});return jo(this,r,function(t){t instanceof Go?o.cancel():i(t)}),o.then(t,e,n)},_(Bo),b(Ho,E),Ho.prototype.message="Deferred has already fired",Ho.prototype.name="AlreadyCalledError",b(Go,E),Go.prototype.message="Deferred was canceled",Go.prototype.name="CanceledError",zo.prototype.c=function(){throw delete Yo[this.a],this.b};var Yo={};function Xo(t){var e={},n=e.document||document,r=gn(t),i=document.createElement("SCRIPT"),o={Lb:i,Ga:void 0},s=new Bo(Jo,o),a=null,u=null!=e.timeout?e.timeout:5e3;return 0<u&&(a=window.setTimeout(function(){$o(i,!0);var t=new es(ts,"Timeout reached for loading script "+r);Wo(s),Vo(s,!1,t)},u),o.Ga=a),i.onload=i.onreadystatechange=function(){i.readyState&&"loaded"!=i.readyState&&"complete"!=i.readyState||($o(i,e.fd||!1,a),s.D())},i.onerror=function(){$o(i,!0,a);var t=new es(Zo,"Error while loading script "+r);Wo(s),Vo(s,!1,t)},ut(o=e.attributes||{},{type:"text/javascript",charset:"UTF-8"}),On(i,o),i.src=gn(t),function(t){var e;return(e=(t||document).getElementsByTagName("HEAD"))&&0!=e.length?e[0]:t.documentElement}(n).appendChild(i),s}function Jo(){if(this&&this.Lb){var t=this.Lb;t&&"SCRIPT"==t.tagName&&$o(t,!0,this.Ga)}}function $o(t,e,r){null!=r&&n.clearTimeout(r),t.onload=o,t.onerror=o,t.onreadystatechange=o,e&&window.setTimeout(function(){t&&t.parentNode&&t.parentNode.removeChild(t)},0)}var Zo=0,ts=1;function es(t,e){var n="Jsloader error (code #"+t+")";e&&(n+=": "+e),E.call(this,n),this.code=t}function ns(t){this.f=t}function rs(t,e,r){if(this.b=t,t=e||{},this.i=t.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token",this.l=t.secureTokenTimeout||ss,this.f=it(t.secureTokenHeaders||as),this.g=t.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",this.h=t.firebaseTimeout||us,this.a=it(t.firebaseHeaders||cs),r&&(this.a["X-Client-Version"]=r,this.f["X-Client-Version"]=r),r="Node"==$n(),!(r=n.XMLHttpRequest||r&&Gn.INTERNAL.node&&Gn.INTERNAL.node.XMLHttpRequest)&&!Jn())throw new Ur("internal-error","The XMLHttpRequest compatibility library was not found.");this.c=void 0,Jn()?this.c=new Eo(self):Zn()?this.c=new ns(r):this.c=new ao}b(es,E),b(ns,ro),ns.prototype.a=function(){return new this.f},ns.prototype.b=function(){return{}};var is,os="idToken",ss=new vr(3e4,6e4),as={"Content-Type":"application/x-www-form-urlencoded"},us=new vr(3e4,6e4),cs={"Content-Type":"application/json"};function hs(t,e){e?t.a["X-Firebase-Locale"]=e:delete t.a["X-Firebase-Locale"]}function ls(t,e){e?(t.a["X-Client-Version"]=e,t.f["X-Client-Version"]=e):(delete t.a["X-Client-Version"],delete t.f["X-Client-Version"])}function fs(t,e,r,i,o,s,a){(function(){var t=or();return!((t=nr(t)!=er?null:(t=t.match(/\sChrome\/(\d+)/i))&&2==t.length?parseInt(t[1],10):null)&&30>t||jt&&$t&&!(9<$t))})()||Jn()?t=m(t.o,t):(is||(is=new dt(function(t,e){!function(t,e){if(((window.gapi||{}).client||{}).request)t();else{n[ds]=function(){((window.gapi||{}).client||{}).request?t():e(Error("CORS_UNSUPPORTED"))};var r=vn(ps,{onload:ds});!function(t,e){jo(t,null,e,void 0)}(Xo(r),function(){e(Error("CORS_UNSUPPORTED"))})}}(t,e)})),t=m(t.m,t)),t(e,r,i,o,s,a)}rs.prototype.o=function(t,e,r,i,o,s){if(Jn()&&(void 0===n.fetch||void 0===n.Headers||void 0===n.Request))throw new Ur("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 a=new Co(this.c);if(s){a.g=Math.max(0,s);var u=setTimeout(function(){a.dispatchEvent("timeout")},s)}ke(a,"complete",function(){u&&clearTimeout(u);var t=null;try{t=JSON.parse(function(t){try{return t.a?t.a.responseText:""}catch(e){return wo(t.b,"Can not get responseText: "+e.message),""}}(this))||null}catch(e){t=null}e&&e(t)}),Re(a,"ready",function(){u&&clearTimeout(u),Ut(this)}),Re(a,"timeout",function(){u&&clearTimeout(u),Ut(this),e&&e(null)}),ko(a,t,r,i,o)};var ps=yn("https://apis.google.com/js/client.js?onload=%{onload}"),ds="__fcb"+Math.floor(1e6*Math.random()).toString();function ys(t){if(!no.test(t.email))throw new Ur("invalid-email")}function ms(t){"email"in t&&ys(t)}function gs(t){if(!t[os])throw new Ur("internal-error")}function vs(t){if(t.phoneNumber||t.temporaryProof){if(!t.phoneNumber||!t.temporaryProof)throw new Ur("internal-error")}else{if(!t.sessionInfo)throw new Ur("missing-verification-id");if(!t.code)throw new Ur("missing-verification-code")}}rs.prototype.m=function(t,e,n,r,i){var o=this;is.then(function(){window.gapi.client.setApiKey(o.b);var s=window.gapi.auth.getToken();window.gapi.auth.setToken(null),window.gapi.client.request({path:t,method:n,body:r,headers:i,authType:"none",callback:function(t){window.gapi.auth.setToken(s),e&&e(t)}})}).s(function(t){e&&e({error:{message:t&&t.message||"CORS_UNSUPPORTED"}})})},rs.prototype.Qa=function(){return ta(this,Qs,{})},rs.prototype.pb=function(t,e){return ta(this,js,{idToken:t,email:e})},rs.prototype.qb=function(t,e){return ta(this,Ks,{idToken:t,password:e})};var bs={displayName:"DISPLAY_NAME",photoUrl:"PHOTO_URL"};function _s(t){if(!t.requestUri||!t.sessionId&&!t.postBody&&!t.pendingToken)throw new Ur("internal-error")}function ws(t,e){return e.oauthIdToken&&e.providerId&&0==e.providerId.indexOf("oidc.")&&!e.pendingToken&&(t.sessionId?e.nonce=t.sessionId:t.postBody&&(un(t=new rn(t.postBody),"nonce")&&(e.nonce=t.get("nonce")))),e}function Es(t){var e=null;if(t.needConfirmation?(t.code="account-exists-with-different-credential",e=to(t)):"FEDERATED_USER_ID_ALREADY_LINKED"==t.errorMessage?(t.code="credential-already-in-use",e=to(t)):"EMAIL_EXISTS"==t.errorMessage?(t.code="email-already-in-use",e=to(t)):t.errorMessage&&(e=ea(t.errorMessage)),e)throw e;if(!t[os])throw new Ur("internal-error")}function Ts(t,e){return e.returnIdpCredential=!0,ta(t,Hs,e)}function Ss(t,e){return e.returnIdpCredential=!0,ta(t,zs,e)}function Is(t,e){return e.returnIdpCredential=!0,e.autoCreate=!1,ta(t,Gs,e)}function Cs(t){if(!t.oobCode)throw new Ur("invalid-action-code")}(t=rs.prototype).rb=function(t,e){var n={idToken:t},r=[];return nt(bs,function(t,i){var o=e[i];null===o?r.push(t):i in e&&(n[i]=o)}),r.length&&(n.deleteAttribute=r),ta(this,js,n)},t.kb=function(t,e){return ut(t={requestType:"PASSWORD_RESET",email:t},e),ta(this,Us,t)},t.lb=function(t,e){return ut(t={requestType:"EMAIL_SIGNIN",email:t},e),ta(this,xs,t)},t.jb=function(t,e){return ut(t={requestType:"VERIFY_EMAIL",idToken:t},e),ta(this,Fs,t)},t.Ua=function(t){return ta(this,Js,t)},t.Za=function(t,e){return ta(this,Vs,{oobCode:t,newPassword:e})},t.Ja=function(t){return ta(this,Ds,{oobCode:t})},t.Wa=function(t){return ta(this,Ns,{oobCode:t})};var Ns={endpoint:"setAccountInfo",B:Cs,da:"email"},Ds={endpoint:"resetPassword",B:Cs,J:function(t){var e=t.requestType;if(!e||!t.email&&"EMAIL_SIGNIN"!=e)throw new Ur("internal-error")}},As={endpoint:"signupNewUser",B:function(t){if(ys(t),!t.password)throw new Ur("weak-password")},J:gs,R:!0},ks={endpoint:"createAuthUri"},Rs={endpoint:"deleteAccount",T:["idToken"]},Os={endpoint:"setAccountInfo",T:["idToken","deleteProvider"],B:function(t){if(!u(t.deleteProvider))throw new Ur("internal-error")}},Ps={endpoint:"emailLinkSignin",T:["email","oobCode"],B:ys,J:gs,R:!0},Ls={endpoint:"emailLinkSignin",T:["idToken","email","oobCode"],B:ys,J:gs,R:!0},Ms={endpoint:"getAccountInfo"},xs={endpoint:"getOobConfirmationCode",T:["requestType"],B:function(t){if("EMAIL_SIGNIN"!=t.requestType)throw new Ur("internal-error");ys(t)},da:"email"},Fs={endpoint:"getOobConfirmationCode",T:["idToken","requestType"],B:function(t){if("VERIFY_EMAIL"!=t.requestType)throw new Ur("internal-error")},da:"email"},Us={endpoint:"getOobConfirmationCode",T:["requestType"],B:function(t){if("PASSWORD_RESET"!=t.requestType)throw new Ur("internal-error");ys(t)},da:"email"},qs={ub:!0,endpoint:"getProjectConfig",Ib:"GET"},Bs={ub:!0,endpoint:"getRecaptchaParam",Ib:"GET",J:function(t){if(!t.recaptchaSiteKey)throw new Ur("internal-error")}},Vs={endpoint:"resetPassword",B:Cs,da:"email"},Ws={endpoint:"sendVerificationCode",T:["phoneNumber","recaptchaToken"],da:"sessionInfo"},js={endpoint:"setAccountInfo",T:["idToken"],B:ms,R:!0},Ks={endpoint:"setAccountInfo",T:["idToken"],B:function(t){if(ms(t),!t.password)throw new Ur("weak-password")},J:gs,R:!0},Qs={endpoint:"signupNewUser",J:gs,R:!0},Hs={endpoint:"verifyAssertion",B:_s,Oa:ws,J:Es,R:!0},Gs={endpoint:"verifyAssertion",B:_s,Oa:ws,J:function(t){if(t.errorMessage&&"USER_NOT_FOUND"==t.errorMessage)throw new Ur("user-not-found");if(t.errorMessage)throw ea(t.errorMessage);if(!t[os])throw new Ur("internal-error")},R:!0},zs={endpoint:"verifyAssertion",B:function(t){if(_s(t),!t.idToken)throw new Ur("internal-error")},Oa:ws,J:Es,R:!0},Ys={endpoint:"verifyCustomToken",B:function(t){if(!t.token)throw new Ur("invalid-custom-token")},J:gs,R:!0},Xs={endpoint:"verifyPassword",B:function(t){if(ys(t),!t.password)throw new Ur("wrong-password")},J:gs,R:!0},Js={endpoint:"verifyPhoneNumber",B:vs,J:gs},$s={endpoint:"verifyPhoneNumber",B:function(t){if(!t.idToken)throw new Ur("internal-error");vs(t)},J:function(t){if(t.temporaryProof)throw t.code="credential-already-in-use",to(t);gs(t)}},Zs={Xb:{USER_NOT_FOUND:"user-not-found"},endpoint:"verifyPhoneNumber",B:vs,J:gs};function ta(t,e,n){if(!function(t,e){if(!e||!e.length)return!0;if(!t)return!1;for(var n=0;n<e.length;n++){var r=t[e[n]];if(void 0===r||null===r||""===r)return!1}return!0}(n,e.T))return Et(new Ur("internal-error"));var r,i=e.Ib||"POST";return wt(n).then(e.B).then(function(){return e.R&&(n.returnSecureToken=!0),function(t,e,n,r,i,o){var s=Ge(t.g+e);Qe(s,"key",t.b),o&&Qe(s,"cb",v().toString());var a="GET"==n;if(a)for(var u in r)r.hasOwnProperty(u)&&Qe(s,u,r[u]);return new dt(function(e,o){fs(t,s.toString(),function(t){t?t.error?o(na(t,i||{})):e(t):o(new Ur("network-request-failed"))},n,a?void 0:xn(pr(r)),t.a,t.h.get())})}(t,e.endpoint,i,n,e.Xb,e.ub||!1)}).then(function(t){return r=t,e.Oa?e.Oa(n,r):r}).then(e.J).then(function(){if(!e.da)return r;if(!(e.da in r))throw new Ur("internal-error");return r[e.da]})}function ea(t){return na({error:{errors:[{message:t}],code:400,message:t}})}function na(t,e){var n=(t.error&&t.error.errors&&t.error.errors[0]||{}).reason||"",r={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(n=r[n]?new Ur(r[n]):null)return n;for(var i in n=t.error&&t.error.message||"",ut(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",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_OR_INVALID_NONCE:"missing-or-invalid-nonce",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_DYNAMIC_LINK_DOMAIN:"invalid-dynamic-link-domain",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",INVALID_CERT_HASH:"invalid-cert-hash"},e||{}),e=(e=n.match(/^[^\s]+\s*:\s*(.*)$/))&&1<e.length?e[1]:void 0,r)if(0===n.indexOf(i))return new Ur(r[i],e);return!e&&t&&(e=fr(t)),new Ur("internal-error",e)}function ra(t){this.b=t,this.a=null,this.fb=function(t){return(aa||(aa=new dt(function(t,e){function r(){gr(),sr("gapi.load")("gapi.iframes",{callback:t,ontimeout:function(){gr(),e(Error("Network Error"))},timeout:oa.get()})}if(sr("gapi.iframes.Iframe"))t();else if(sr("gapi.load"))r();else{var i="__iframefcb"+Math.floor(1e6*Math.random()).toString();n[i]=function(){sr("gapi.load")?r():e(Error("Network Error"))},wt(Xo(i=vn(ia,{onload:i}))).s(function(){e(Error("Network Error"))})}}).s(function(t){throw aa=null,t}))).then(function(){return new dt(function(e,n){sr("gapi.iframes.getContext")().open({where:document.body,url:t.b,messageHandlersFilter:sr("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"),attributes:{style:{position:"absolute",top:"-100px",width:"1px",height:"1px"}},dontclear:!0},function(r){function i(){clearTimeout(o),e()}t.a=r,t.a.restyle({setHideOnLeave:!1});var o=setTimeout(function(){n(Error("Network Error"))},sa.get());r.ping(i).then(i,function(){n(Error("Network Error"))})})})})}(this)}var ia=yn("https://apis.google.com/js/api.js?onload=%{onload}"),oa=new vr(3e4,6e4),sa=new vr(5e3,15e3),aa=null;function ua(t,e,n){this.i=t,this.g=e,this.h=n,this.f=null,this.a=ze(this.i,"/__/auth/iframe"),Qe(this.a,"apiKey",this.g),Qe(this.a,"appName",this.h),this.b=null,this.c=[]}function ca(t,e,n,r,i){this.o=t,this.m=e,this.c=n,this.l=r,this.h=this.g=this.i=null,this.a=i,this.f=null}function ha(t){try{return Gn.app(t).auth().ya()}catch(t){return[]}}function la(t,e,n,r,i){this.m=t,this.f=e,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 fa(t){var e=Vn();return function(t){return ta(t,qs,{}).then(function(t){return t.authorizedDomains||[]})}(t).then(function(t){t:{var n=Ge(e),r=n.c;n=n.b;for(var i=0;i<t.length;i++){var o=t[i],s=n,a=r;if(0==o.indexOf("chrome-extension://")?s=Ge(o).b==s&&"chrome-extension"==a:"http"!=a&&"https"!=a?s=!1:Hn.test(o)?s=s==o:(o=o.split(".").join("\\."),s=new RegExp("^(.+\\."+o+"|"+o+")$","i").test(s)),s){t=!0;break t}}t=!1}if(!t)throw new $i(Vn())})}function pa(t){return t.l?t.l:(t.l=zn().then(function(){if(!t.u){var e=t.c,n=t.h,r=ha(t.b),i=new ua(t.m,t.f,t.b);i.f=e,i.b=n,i.c=q(r||[]),t.u=i.toString()}t.i=new ra(t.u),function(t){if(!t.i)throw Error("IfcHandler must be initialized!");!function(t,e){t.fb.then(function(){t.a.register("authEvent",e,sr("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})}(t.i,function(e){var n={};if(e&&e.authEvent){var r=!1;for(e=Yi(e.authEvent),n=0;n<t.g.length;n++)r=t.g[n](e)||r;return(n={}).status=r?"ACK":"ERROR",wt(n)}return n.status="ERROR",wt(n)})}(t)}),t.l)}function da(t){return t.o||(t.v=t.c?ir(t.c,ha(t.b)):null,t.o=new rs(t.f,ai(t.h),t.v)),t.o}function ya(t,e,n,r,i,o,s,a,u,c){return(t=new ca(t,e,n,r,i)).i=o,t.g=s,t.h=a,t.b=it(u||null),t.f=c,t.toString()}function ma(t){if(this.a=t||Gn.INTERNAL.reactNative&&Gn.INTERNAL.reactNative.AsyncStorage,!this.a)throw new Ur("internal-error","The React Native compatibility library was not found.");this.type="asyncStorage"}function ga(t){this.b=t,this.a={},this.c=m(this.f,this)}ua.prototype.toString=function(){return this.f?Qe(this.a,"v",this.f):an(this.a.a,"v"),this.b?Qe(this.a,"eid",this.b):an(this.a.a,"eid"),this.c.length?Qe(this.a,"fw",this.c.join(",")):an(this.a.a,"fw"),this.a.toString()},ca.prototype.toString=function(){var t=ze(this.o,"/__/auth/handler");if(Qe(t,"apiKey",this.m),Qe(t,"appName",this.c),Qe(t,"authType",this.l),this.a.isOAuthProvider){var e=this.a;try{var n=Gn.app(this.c).auth().ea()}catch(t){n=null}for(var r in e.$a=n,Qe(t,"providerId",this.a.providerId),n=pr((e=this.a).yb))n[r]=n[r].toString();r=e.Dc,n=it(n);for(var i=0;i<r.length;i++){var o=r[i];o in n&&delete n[o]}e.cb&&e.$a&&!n[e.cb]&&(n[e.cb]=e.$a),rt(n)||Qe(t,"customParameters",fr(n))}if("function"==typeof this.a.Eb&&((e=this.a.Eb()).length&&Qe(t,"scopes",e.join(","))),this.i?Qe(t,"redirectUrl",this.i):an(t.a,"redirectUrl"),this.g?Qe(t,"eventId",this.g):an(t.a,"eventId"),this.h?Qe(t,"v",this.h):an(t.a,"v"),this.b)for(var s in this.b)this.b.hasOwnProperty(s)&&!He(t,s)&&Qe(t,s,this.b[s]);return this.f?Qe(t,"eid",this.f):an(t.a,"eid"),(s=ha(this.c)).length&&Qe(t,"fw",s.join(",")),t.toString()},(t=la.prototype).Ea=function(t,e,n){var r=new Ur("popup-closed-by-user"),i=new Ur("web-storage-unsupported"),o=this,s=!1;return this.ga().then(function(){(function(t){var e={type:"webStorageSupport"};return pa(t).then(function(){return function(t,e){return t.fb.then(function(){return new dt(function(n){t.a.send(e.type,e,n,sr("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})})}(t.i,e)}).then(function(t){if(t&&t.length&&void 0!==t[0].webStorageSupport)return t[0].webStorageSupport;throw Error()})})(o).then(function(n){n||(t&&Kn(t),e(i),s=!0)})}).s(function(){}).then(function(){if(!s)return function(t){return new dt(function(e){return function n(){Le(2e3).then(function(){if(t&&!t.closed)return n();e()})}()})}(t)}).then(function(){if(!s)return Le(n).then(function(){e(r)})})},t.Mb=function(){var t=or();return!lr(t)&&!mr(t)},t.Hb=function(){return!1},t.Cb=function(t,e,n,r,i,o,s){if(!t)return Et(new Ur("popup-blocked"));if(s&&!lr())return this.ga().s(function(e){Kn(t),i(e)}),r(),wt();this.a||(this.a=fa(da(this)));var a=this;return this.a.then(function(){var e=a.ga().s(function(e){throw Kn(t),i(e),e});return r(),e}).then(function(){(Gi(n),s)||Wn(ya(a.m,a.f,a.b,e,n,null,o,a.c,void 0,a.h),t)}).s(function(t){throw"auth/network-request-failed"==t.code&&(a.a=null),t})},t.Ca=function(t,e,n){this.a||(this.a=fa(da(this)));var r=this;return this.a.then(function(){Gi(e),Wn(ya(r.m,r.f,r.b,t,e,Vn(),n,r.c,void 0,r.h))}).s(function(t){throw"auth/network-request-failed"==t.code&&(r.a=null),t})},t.ga=function(){var t=this;return pa(this).then(function(){return t.i.fb}).s(function(){throw t.a=null,new Ur("network-request-failed")})},t.Qb=function(){return!0},t.wa=function(t){this.g.push(t)},t.Ka=function(t){F(this.g,function(e){return e==t})},(t=ma.prototype).get=function(t){return wt(this.a.getItem(t)).then(function(t){return t&&dr(t)})},t.set=function(t,e){return wt(this.a.setItem(t,fr(e)))},t.P=function(t){return wt(this.a.removeItem(t))},t.Y=function(){},t.ca=function(){};var va,ba=[];function _a(t){this.a=t}function wa(t){this.c=t,this.b=!1,this.a=[]}function Ea(t,e,n,r){var i,o,s,a,u=n||{},c=null;if(t.b)return Et(Error("connection_unavailable"));var h=r?800:50,l="undefined"!=typeof MessageChannel?new MessageChannel:null;return new dt(function(n,r){l?(i=Math.floor(Math.random()*Math.pow(10,20)).toString(),l.port1.start(),s=setTimeout(function(){r(Error("unsupported_event"))},h),c={messageChannel:l,onMessage:o=function(t){t.data.eventId===i&&("ack"===t.data.status?(clearTimeout(s),a=setTimeout(function(){r(Error("timeout"))},3e3)):"done"===t.data.status?(clearTimeout(a),void 0!==t.data.response?n(t.data.response):r(Error("unknown_error"))):(clearTimeout(s),clearTimeout(a),r(Error("invalid_response"))))}},t.a.push(c),l.port1.addEventListener("message",o),t.c.postMessage({eventType:e,eventId:i,data:u},[l.port2])):r(Error("connection_unavailable"))}).then(function(e){return Ta(t,c),e}).s(function(e){throw Ta(t,c),e})}function Ta(t,e){if(e){var n=e.messageChannel,r=e.onMessage;n&&(n.port1.removeEventListener("message",r),n.port1.close()),F(t.a,function(t){return t==e})}}function Sa(){if(!Na())throw new Ur("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 t=this;Jn()&&self?(this.l=function(){var t=Jn()?self:null;if(O(ba,function(n){n.b==t&&(e=n)}),!e){var e=new ga(t);ba.push(e)}return e}(),this.l.subscribe("keyChanged",function(e,n){return Oa(t).then(function(e){return 0<e.length&&O(t.a,function(t){t(e)}),{keyProcessed:M(e,n.key)}})}),this.l.subscribe("ping",function(){return wt(["keyChanged"])})):function(){var t=n.navigator;return t&&t.serviceWorker?wt().then(function(){return t.serviceWorker.ready}).then(function(t){return t.active||null}).s(function(){return null}):wt(null)}().then(function(e){(t.h=e)&&(t.g=new wa(new _a(e)),Ea(t.g,"ping",null,!0).then(function(e){e[0].fulfilled&&M(e[0].value,"keyChanged")&&(t.u=!0)}).s(function(){}))})}function Ia(t){return new dt(function(e,n){var r=t.m.open("firebaseLocalStorageDb",1);r.onerror=function(t){try{t.preventDefault()}catch(t){}n(Error(t.target.error))},r.onupgradeneeded=function(t){t=t.target.result;try{t.createObjectStore("firebaseLocalStorage",{keyPath:"fbase_key"})}catch(t){n(t)}},r.onsuccess=function(r){(r=r.target.result).objectStoreNames.contains("firebaseLocalStorage")?e(r):function(t){return new dt(function(e,n){var r=t.m.deleteDatabase("firebaseLocalStorageDb");r.onsuccess=function(){e()},r.onerror=function(t){n(Error(t.target.error))}})}(t).then(function(){return Ia(t)}).then(function(t){e(t)}).s(function(t){n(t)})}})}function Ca(t){return t.o||(t.o=Ia(t)),t.o}function Na(){try{return!!n.indexedDB}catch(t){return!1}}function Da(t){return t.objectStore("firebaseLocalStorage")}function Aa(t,e){return t.transaction(["firebaseLocalStorage"],e?"readwrite":"readonly")}function ka(t){return new dt(function(e,n){t.onsuccess=function(t){t&&t.target?e(t.target.result):e()},t.onerror=function(t){n(t.target.error)}})}function Ra(t,e){return t.g&&t.h&&function(){var t=n.navigator;return t&&t.serviceWorker&&t.serviceWorker.controller||null}()===t.h?Ea(t.g,"keyChanged",{key:e},t.u).then(function(){}).s(function(){}):wt()}function Oa(t){return Ca(t).then(function(t){var e=Da(Aa(t,!1));return e.getAll?ka(e.getAll()):new dt(function(t,n){var r=[],i=e.openCursor();i.onsuccess=function(e){(e=e.target.result)?(r.push(e.value),e.continue()):t(r)},i.onerror=function(t){n(t.target.error)}})}).then(function(e){var n={},r=[];if(0==t.b){for(r=0;r<e.length;r++)n[e[r].fbase_key]=e[r].value;r=function t(e,n){var r,i=[];for(r in e)r in n?typeof e[r]!=typeof n[r]?i.push(r):"object"==typeof e[r]&&null!=e[r]&&null!=n[r]?0<t(e[r],n[r]).length&&i.push(r):e[r]!==n[r]&&i.push(r):i.push(r);for(r in n)r in e||i.push(r);return i}(t.c,n),t.c=n}return r})}function Pa(t){t.i&&t.i.cancel("STOP_EVENT"),t.f&&(clearTimeout(t.f),t.f=null)}function La(t){var e=this,n=null;this.a=[],this.type="indexedDB",this.c=t,this.b=wt().then(function(){if(Na()){var t=yr(),r="__sak"+t;return va||(va=new Sa),(n=va).set(r,t).then(function(){return n.get(r)}).then(function(e){if(e!==t)throw Error("indexedDB not supported!");return n.P(r)}).then(function(){return n}).s(function(){return e.c})}return e.c}).then(function(t){return e.type=t.type,t.Y(function(t){O(e.a,function(e){e(t)})}),t})}function Ma(){this.a={},this.type="inMemory"}function xa(){if(!function(){var t="Node"==$n();if(!(t=Fa()||t&&Gn.INTERNAL.node&&Gn.INTERNAL.node.localStorage))return!1;try{return t.setItem("__sak","1"),t.removeItem("__sak"),!0}catch(t){return!1}}()){if("Node"==$n())throw new Ur("internal-error","The LocalStorage compatibility library was not found.");throw new Ur("web-storage-unsupported")}this.a=Fa()||Gn.INTERNAL.node.localStorage,this.type="localStorage"}function Fa(){try{var t=n.localStorage,e=yr();return t&&(t.setItem(e,"1"),t.removeItem(e)),t}catch(t){return null}}function Ua(){this.type="nullStorage"}function qa(){if(!function(){var t="Node"==$n();if(!(t=Ba()||t&&Gn.INTERNAL.node&&Gn.INTERNAL.node.sessionStorage))return!1;try{return t.setItem("__sak","1"),t.removeItem("__sak"),!0}catch(t){return!1}}()){if("Node"==$n())throw new Ur("internal-error","The SessionStorage compatibility library was not found.");throw new Ur("web-storage-unsupported")}this.a=Ba()||Gn.INTERNAL.node.sessionStorage,this.type="sessionStorage"}function Ba(){try{var t=n.sessionStorage,e=yr();return t&&(t.setItem(e,"1"),t.removeItem(e)),t}catch(t){return null}}ga.prototype.f=function(t){var e=t.data.eventType,n=t.data.eventId,r=this.a[e];if(r&&0<r.length){t.ports[0].postMessage({status:"ack",eventId:n,eventType:e,response:null});var i=[];O(r,function(e){i.push(wt().then(function(){return e(t.origin,t.data.data)}))}),St(i).then(function(r){var i=[];O(r,function(t){i.push({fulfilled:t.Db,value:t.value,reason:t.reason?t.reason.message:void 0})}),O(i,function(t){for(var e in t)void 0===t[e]&&delete t[e]}),t.ports[0].postMessage({status:"done",eventId:n,eventType:e,response:i})})}},ga.prototype.subscribe=function(t,e){rt(this.a)&&this.b.addEventListener("message",this.c),void 0===this.a[t]&&(this.a[t]=[]),this.a[t].push(e)},ga.prototype.unsubscribe=function(t,e){void 0!==this.a[t]&&e?(F(this.a[t],function(t){return t==e}),0==this.a[t].length&&delete this.a[t]):e||delete this.a[t],rt(this.a)&&this.b.removeEventListener("message",this.c)},_a.prototype.postMessage=function(t,e){this.a.postMessage(t,e)},wa.prototype.close=function(){for(;0<this.a.length;)Ta(this,this.a[0]);this.b=!0},(t=Sa.prototype).set=function(t,e){var n,r=!1,i=this;return Ca(this).then(function(e){return ka((e=Da(Aa(n=e,!0))).get(t))}).then(function(o){var s=Da(Aa(n,!0));return o?(o.value=e,ka(s.put(o))):(i.b++,r=!0,(o={}).fbase_key=t,o.value=e,ka(s.add(o)))}).then(function(){return i.c[t]=e,Ra(i,t)}).ia(function(){r&&i.b--})},t.get=function(t){return Ca(this).then(function(e){return ka(Da(Aa(e,!1)).get(t))}).then(function(t){return t&&t.value})},t.P=function(t){var e=!1,n=this;return Ca(this).then(function(r){return e=!0,n.b++,ka(Da(Aa(r,!0)).delete(t))}).then(function(){return delete n.c[t],Ra(n,t)}).ia(function(){e&&n.b--})},t.Y=function(t){0==this.a.length&&function(t){Pa(t),function e(){t.f=setTimeout(function(){t.i=Oa(t).then(function(e){0<e.length&&O(t.a,function(t){t(e)})}).then(function(){e()}).s(function(t){"STOP_EVENT"!=t.message&&e()})},800)}()}(this),this.a.push(t)},t.ca=function(t){F(this.a,function(e){return e==t}),0==this.a.length&&Pa(this)},(t=La.prototype).get=function(t){return this.b.then(function(e){return e.get(t)})},t.set=function(t,e){return this.b.then(function(n){return n.set(t,e)})},t.P=function(t){return this.b.then(function(e){return e.P(t)})},t.Y=function(t){this.a.push(t)},t.ca=function(t){F(this.a,function(e){return e==t})},(t=Ma.prototype).get=function(t){return wt(this.a[t])},t.set=function(t,e){return this.a[t]=e,wt()},t.P=function(t){return delete this.a[t],wt()},t.Y=function(){},t.ca=function(){},(t=xa.prototype).get=function(t){var e=this;return wt().then(function(){return dr(e.a.getItem(t))})},t.set=function(t,e){var n=this;return wt().then(function(){var r=fr(e);null===r?n.P(t):n.a.setItem(t,r)})},t.P=function(t){var e=this;return wt().then(function(){e.a.removeItem(t)})},t.Y=function(t){n.window&&ge(n.window,"storage",t)},t.ca=function(t){n.window&&_e(n.window,"storage",t)},(t=Ua.prototype).get=function(){return wt(null)},t.set=function(){return wt()},t.P=function(){return wt()},t.Y=function(){},t.ca=function(){},(t=qa.prototype).get=function(t){var e=this;return wt().then(function(){return dr(e.a.getItem(t))})},t.set=function(t,e){var n=this;return wt().then(function(){var r=fr(e);null===r?n.P(t):n.a.setItem(t,r)})},t.P=function(t){var e=this;return wt().then(function(){e.a.removeItem(t)})},t.Y=function(){},t.ca=function(){};var Va,Wa,ja={A:xa,Ra:qa},Ka={A:xa,Ra:qa},Qa={A:ma,Ra:Ua},Ha={A:xa,Ra:Ua},Ga={Zc:"local",NONE:"none",ad:"session"};function za(){var t=!(mr(or())||!Xn()),e=lr(),r=ar();this.o=t,this.h=e,this.l=r,this.a={},Va||(Va=new function(){var t={};t.Browser=ja,t.Node=Ka,t.ReactNative=Qa,t.Worker=Ha,this.a=t[$n()]}),t=Va;try{this.g=!Bn()&&wr()||!n.indexedDB?new t.a.A:new La(Jn()?new Ma:new t.a.A)}catch(t){this.g=new Ma,this.h=!0}try{this.i=new t.a.Ra}catch(t){this.i=new Ma}this.m=new Ma,this.f=m(this.Pb,this),this.b={}}function Ya(){return Wa||(Wa=new za),Wa}function Xa(t,e){switch(e){case"session":return t.i;case"none":return t.m;default:return t.g}}function Ja(t,e){return"firebase:"+t.name+(e?":"+e:"")}function $a(t,e,n){return n=Ja(e,n),"local"==e.A&&(t.b[n]=null),Xa(t,e.A).P(n)}function Za(t){t.c&&(clearInterval(t.c),t.c=null)}(t=za.prototype).get=function(t,e){return Xa(this,t.A).get(Ja(t,e))},t.set=function(t,e,n){var r=Ja(t,n),i=this,o=Xa(this,t.A);return o.set(r,e).then(function(){return o.get(r)}).then(function(e){"local"==t.A&&(i.b[r]=e)})},t.addListener=function(t,e,r){t=Ja(t,e),this.l&&(this.b[t]=n.localStorage.getItem(t)),rt(this.a)&&(Xa(this,"local").Y(this.f),this.h||(Bn()||!wr())&&n.indexedDB||!this.l||function(t){Za(t),t.c=setInterval(function(){for(var e in t.a){var r=n.localStorage.getItem(e),i=t.b[e];r!=i&&(t.b[e]=r,r=new ae({type:"storage",key:e,target:window,oldValue:i,newValue:r,a:!0}),t.Pb(r))}},1e3)}(this)),this.a[t]||(this.a[t]=[]),this.a[t].push(r)},t.removeListener=function(t,e,n){t=Ja(t,e),this.a[t]&&(F(this.a[t],function(t){return t==n}),0==this.a[t].length&&delete this.a[t]),rt(this.a)&&(Xa(this,"local").ca(this.f),Za(this))},t.Pb=function(t){if(t&&t.f){var e=t.a.key;if(null==e)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.Xa(r))}else if(0==e.indexOf("firebase:")&&this.a[e]){if(void 0!==t.a.a?Xa(this,"local").ca(this.f):Za(this),this.o)if(r=n.localStorage.getItem(e),(i=t.a.newValue)!==r)null!==i?n.localStorage.setItem(e,i):n.localStorage.removeItem(e);else if(this.b[e]===i&&void 0===t.a.a)return;var s=this;r=function(){void 0===t.a.a&&s.b[e]===n.localStorage.getItem(e)||(s.b[e]=n.localStorage.getItem(e),s.Xa(e))},jt&&$t&&10==$t&&n.localStorage.getItem(e)!==t.a.newValue&&t.a.newValue!==t.a.oldValue?setTimeout(r,10):r()}}else O(t,m(this.Xa,this))},t.Xa=function(t){this.a[t]&&O(this.a[t],function(t){t()})};var tu,eu={name:"authEvent",A:"local"};function nu(t,e){this.b=ru,this.f=n.Uint8Array?new Uint8Array(this.b):Array(this.b),this.g=this.c=0,this.a=[],this.i=t,this.h=e,this.l=n.Int32Array?new Int32Array(64):Array(64),void 0!==tu||(tu=n.Int32Array?new Int32Array(hu):hu),this.reset()}b(nu,function(){this.b=-1});for(var ru=64,iu=ru-1,ou=[],su=0;su<iu;su++)ou[su]=0;var au=U(128,ou);function uu(t){for(var e=t.f,n=t.l,r=0,i=0;i<e.length;)n[r++]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3],i=4*r;for(e=16;64>e;e++){i=0|n[e-15],r=0|n[e-2];var o=(0|n[e-16])+((i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3)|0,s=(0|n[e-7])+((r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10)|0;n[e]=o+s|0}r=0|t.a[0],i=0|t.a[1];var a=0|t.a[2],u=0|t.a[3],c=0|t.a[4],h=0|t.a[5],l=0|t.a[6];for(o=0|t.a[7],e=0;64>e;e++){var f=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&i^r&a^i&a)|0;s=(o=o+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))|0)+((s=(s=c&h^~c&l)+(0|tu[e])|0)+(0|n[e])|0)|0,o=l,l=h,h=c,c=u+s|0,u=a,a=i,i=r,r=s+f|0}t.a[0]=t.a[0]+r|0,t.a[1]=t.a[1]+i|0,t.a[2]=t.a[2]+a|0,t.a[3]=t.a[3]+u|0,t.a[4]=t.a[4]+c|0,t.a[5]=t.a[5]+h|0,t.a[6]=t.a[6]+l|0,t.a[7]=t.a[7]+o|0}function cu(t,e,n){void 0===n&&(n=e.length);var i=0,o=t.c;if(r(e))for(;i<n;)t.f[o++]=e.charCodeAt(i++),o==t.b&&(uu(t),o=0);else{if(!c(e))throw Error("message must be string or array");for(;i<n;){var s=e[i++];if(!("number"==typeof s&&0<=s&&255>=s&&s==(0|s)))throw Error("message must be a byte array");t.f[o++]=s,o==t.b&&(uu(t),o=0)}}t.c=o,t.g+=n}nu.prototype.reset=function(){this.g=this.c=0,this.a=n.Int32Array?new Int32Array(this.h):q(this.h)};var hu=[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 lu(){nu.call(this,8,fu)}b(lu,nu);var fu=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function pu(t,e,n,r,i){this.m=t,this.i=e,this.l=n,this.o=r||null,this.u=i||null,this.h=e+":"+n,this.v=new function(){this.a=Ya()},this.g=new function(t){this.a=t,this.b=Ya()}(this.h),this.f=null,this.b=[],this.a=this.c=null}function du(t){return new Ur("invalid-cordova-configuration",t)}function yu(t){var e=new lu;cu(e,t),t=[];var n=8*e.g;56>e.c?cu(e,au,56-e.c):cu(e,au,e.b-(e.c-56));for(var r=63;56<=r;r--)e.f[r]=255&n,n/=256;for(uu(e),r=n=0;r<e.i;r++)for(var i=24;0<=i;i-=8)t[n++]=e.a[r]>>i&255;return function(t){return P(t,function(t){return 1<(t=t.toString(16)).length?t:"0"+t}).join("")}(t)}function mu(t,e){for(var n=0;n<t.b.length;n++)try{t.b[n](e)}catch(t){}}function gu(t){return t.f||(t.f=t.ga().then(function(){return new dt(function(e){t.wa(function n(r){return e(r),t.Ka(n),!1}),function(t){function e(e){i=!0,o&&o.cancel(),vu(t).then(function(n){var i=r;if(n&&e&&e.url){var o=null;-1!=(i=wi(e.url)).indexOf("/__/auth/callback")&&(o=(o="object"==typeof(o=dr(He(o=Ge(i),"firebaseError")||null))?qr(o):null)?new zi(n.b,n.c,null,null,o):new zi(n.b,n.c,i,n.g)),i=o||r}mu(t,i)})}var r=new zi("unknown",null,null,null,new Ur("no-auth-event")),i=!1,o=Le(500).then(function(){return vu(t).then(function(){i||mu(t,r)})}),s=n.handleOpenURL;n.handleOpenURL=function(t){if(0==t.toLowerCase().indexOf(sr("BuildInfo.packageName",n).toLowerCase()+"://")&&e({url:t}),"function"==typeof s)try{s(t)}catch(t){console.error(t)}},Ji||(Ji=new Xi),Ji.subscribe(e)}(t)})})),t.f}function vu(t){var e=null;return function(t){return t.b.get(eu,t.a).then(function(t){return Yi(t)})}(t.g).then(function(n){return e=n,$a((n=t.g).b,eu,n.a)}).then(function(){return e})}(t=pu.prototype).ga=function(){return this.za?this.za:this.za=(Yn(void 0)?zn().then(function(){return new dt(function(t,e){var r=n.document,i=setTimeout(function(){e(Error("Cordova framework is not ready."))},1e3);r.addEventListener("deviceready",function(){clearTimeout(i),t()},!1)})}):Et(Error("Cordova must run in an Android or iOS file scheme."))).then(function(){if("function"!=typeof sr("universalLinks.subscribe",n))throw du("cordova-universal-links-plugin-fix is not installed");if(void 0===sr("BuildInfo.packageName",n))throw du("cordova-plugin-buildinfo is not installed");if("function"!=typeof sr("cordova.plugins.browsertab.openUrl",n))throw du("cordova-plugin-browsertab is not installed");if("function"!=typeof sr("cordova.InAppBrowser.open",n))throw du("cordova-plugin-inappbrowser is not installed")},function(){throw new Ur("cordova-not-ready")})},t.Ea=function(t,e){return e(new Ur("operation-not-supported-in-this-environment")),wt()},t.Cb=function(){return Et(new Ur("operation-not-supported-in-this-environment"))},t.Qb=function(){return!1},t.Mb=function(){return!0},t.Hb=function(){return!0},t.Ca=function(t,e,r){if(this.c)return Et(new Ur("redirect-operation-pending"));var i=this,o=n.document,s=null,a=null,u=null,c=null;return this.c=wt().then(function(){return Gi(e),gu(i)}).then(function(){return function(t,e,r,i){var o=function(){for(var t=20,e=[];0<t;)e.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.floor(62*Math.random()))),t--;return e.join("")}(),s=new zi(e,i,null,o,new Ur("no-auth-event")),a=sr("BuildInfo.packageName",n);if("string"!=typeof a)throw new Ur("invalid-cordova-configuration");var u=sr("BuildInfo.displayName",n),c={};if(or().toLowerCase().match(/iphone|ipad|ipod/))c.ibi=a;else{if(!or().toLowerCase().match(/android/))return Et(new Ur("operation-not-supported-in-this-environment"));c.apn=a}u&&(c.appDisplayName=u),o=yu(o),c.sessionId=o;var h=ya(t.m,t.i,t.l,e,r,null,i,t.o,c,t.u);return t.ga().then(function(){var e=t.h;return t.v.a.set(eu,s.C(),e)}).then(function(){var e=sr("cordova.plugins.browsertab.isAvailable",n);if("function"!=typeof e)throw new Ur("invalid-cordova-configuration");var r=null;e(function(e){if(e){if("function"!=typeof(r=sr("cordova.plugins.browsertab.openUrl",n)))throw new Ur("invalid-cordova-configuration");r(h)}else{if("function"!=typeof(r=sr("cordova.InAppBrowser.open",n)))throw new Ur("invalid-cordova-configuration");e=!(!(e=or()).match(/(iPad|iPhone|iPod).*OS 7_\d/i)&&!e.match(/(iPad|iPhone|iPod).*OS 8_\d/i)),t.a=r(h,e?"_blank":"_system","location=yes")}})})}(i,t,e,r)}).then(function(){return new dt(function(t,e){a=function(){var e=sr("cordova.plugins.browsertab.close",n);return t(),"function"==typeof e&&e(),i.a&&"function"==typeof i.a.close&&(i.a.close(),i.a=null),!1},i.wa(a),u=function(){s||(s=Le(2e3).then(function(){e(new Ur("redirect-cancelled-by-user"))}))},c=function(){br()&&u()},o.addEventListener("resume",u,!1),or().toLowerCase().match(/android/)||o.addEventListener("visibilitychange",c,!1)}).s(function(t){return vu(i).then(function(){throw t})})}).ia(function(){u&&o.removeEventListener("resume",u,!1),c&&o.removeEventListener("visibilitychange",c,!1),s&&s.cancel(),a&&i.Ka(a),i.c=null})},t.wa=function(t){this.b.push(t),gu(this).s(function(e){"auth/invalid-cordova-configuration"===e.code&&(e=new zi("unknown",null,null,null,new Ur("no-auth-event")),t(e))})},t.Ka=function(t){F(this.b,function(e){return e==t})};var bu={name:"pendingRedirect",A:"session"};function _u(t){return $a(t.b,bu,t.a)}function wu(t,e,n){this.u=t,this.l=e,this.m=n,this.h=[],this.f=!1,this.i=m(this.bb,this),this.b=new Ru,this.o=new Mu,this.g=new function(t){this.a=t,this.b=Ya()}(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=Eu(this.u,this.l,this.m,oi)}function Eu(t,e,n,r){var i=Gn.SDK_VERSION||null;return Yn()?new pu(t,e,n,i,r):new la(t,e,n,i,r)}function Tu(t){t.f||(t.f=!0,t.a.wa(t.i));var e=t.a;return t.a.ga().s(function(n){throw t.a==e&&t.reset(),n})}function Su(t){t.a.Mb()&&Tu(t).s(function(e){var n=new zi("unknown",null,null,null,new Ur("operation-not-supported-in-this-environment"));Du(e)&&t.bb(n)}),t.a.Hb()||Ou(t.b)}(t=wu.prototype).reset=function(){this.f=!1,this.a.Ka(this.i),this.a=Eu(this.u,this.l,this.m)},t.Ya=function(){this.b.Ya()},t.subscribe=function(t){if(M(this.h,t)||this.h.push(t),!this.f){var e=this;(function(t){return t.b.get(bu,t.a).then(function(t){return"pending"==t})})(this.g).then(function(t){t?_u(e.g).then(function(){Tu(e).s(function(t){var n=new zi("unknown",null,null,null,new Ur("operation-not-supported-in-this-environment"));Du(t)&&e.bb(n)})}):Su(e)}).s(function(){Su(e)})}},t.unsubscribe=function(t){F(this.h,function(e){return e==t})},t.bb=function(t){if(!t)throw new Ur("invalid-auth-event");for(var e=!1,n=0;n<this.h.length;n++){var r=this.h[n];if(r.vb(t.b,t.c)){(e=this.c[t.b])&&e.h(t,r),e=!0;break}}return Ou(this.b),e};var Iu=new vr(2e3,1e4),Cu=new vr(3e4,6e4);function Nu(t,e,n,r,i,o){return t.a.Cb(e,n,r,function(){t.f||(t.f=!0,t.a.wa(t.i))},function(){t.reset()},i,o)}function Du(t){return!(!t||"auth/cordova-not-ready"!=t.code)}wu.prototype.fa=function(){return this.b.fa()},wu.prototype.Ca=function(t,e,n){var r,i=this;return function(t){return t.b.set(bu,"pending",t.a)}(this.g).then(function(){return i.a.Ca(t,e,n).s(function(t){if(Du(t))throw new Ur("operation-not-supported-in-this-environment");return r=t,_u(i.g).then(function(){throw r})}).then(function(){return i.a.Qb()?new dt(function(){}):_u(i.g).then(function(){return i.fa()}).then(function(){}).s(function(){})})})},wu.prototype.Ea=function(t,e,n,r){return this.a.Ea(n,function(n){t.ha(e,null,n,r)},Iu.get())};var Au={};function ku(t,e,n){var r=e+":"+n;return Au[r]||(Au[r]=new wu(t,e,n)),Au[r]}function Ru(){this.b=null,this.f=[],this.c=[],this.a=null,this.i=this.g=!1}function Ou(t){t.g||(t.g=!0,Lu(t,!1,null,null))}function Pu(t,e){if(t.b=function(){return wt(e)},t.f.length)for(var n=0;n<t.f.length;n++)t.f[n](e)}function Lu(t,e,n,r){e?r?function(t,e){if(t.b=function(){return Et(e)},t.c.length)for(var n=0;n<t.c.length;n++)t.c[n](e)}(t,r):Pu(t,n):Pu(t,{user:null}),t.f=[],t.c=[]}function Mu(){}function xu(){this.sb=!1,Object.defineProperty(this,"appVerificationDisabled",{get:function(){return this.sb},set:function(t){this.sb=t},enumerable:!1})}function Fu(t,e){this.a=e,Cr(this,"verificationId",t)}function Uu(t,e,n,r){return new Ki(t).Ua(e,n).then(function(t){return new Fu(t,r)})}function qu(t,e,n){if(this.h=t,this.i=e,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 Bu(t){this.f=t,this.b=this.a=null,this.c=0}function Vu(t,e){var n=e[os],r=e.refreshToken;e=Wu(e.expiresIn),t.b=n,t.c=e,t.a=r}function Wu(t){return v()+1e3*parseInt(t,10)}function ju(t,e){return function(t,e){return new dt(function(n,r){"refresh_token"==e.grant_type&&e.refresh_token||"authorization_code"==e.grant_type&&e.code?fs(t,t.i+"?key="+encodeURIComponent(t.b),function(t){t?t.error?r(na(t)):t.access_token&&t.refresh_token?n(t):r(new Ur("internal-error")):r(new Ur("network-request-failed"))},"POST",sn(e).toString(),t.f,t.l.get()):r(new Ur("internal-error"))})}(t.f,e).then(function(e){return t.b=e.access_token,t.c=Wu(e.expires_in),t.a=e.refresh_token,{accessToken:t.b,expirationTime:t.c,refreshToken:t.a}}).s(function(e){throw"auth/user-token-expired"==e.code&&(t.a=null),e})}function Ku(t,e){this.a=t||null,this.b=e||null,Nr(this,{lastSignInTime:_r(e||null),creationTime:_r(t||null)})}function Qu(t,e){for(var n in se.call(this,t),e)this[n]=e[n]}function Hu(t,e,n){this.G=[],this.m=t.apiKey,this.o=t.appName,this.u=t.authDomain||null,t=Gn.SDK_VERSION?ir(Gn.SDK_VERSION):null,this.b=new rs(this.m,ai(oi),t),this.h=new Bu(this.b),Zu(this,e[os]),Vu(this.h,e),Cr(this,"refreshToken",this.h.a),nc(this,n||{}),Ae.call(this),this.I=!1,this.u&&ur()&&(this.a=ku(this.u,this.m,this.o)),this.N=[],this.i=null,this.w=function(t){return new qu(function(){return t.F(!0)},function(t){return!(!t||"auth/network-request-failed"!=t.code)},function(){var e=t.h.c-v()-3e5;return 0<e?e:0})}(this),this.V=m(this.Ha,this);var r=this;this.ka=null,this.ta=function(t){r.pa(t.g)},this.X=null,this.O=[],this.sa=function(t){zu(r,t.c)},this.W=null}function Gu(t,e){t.X&&_e(t.X,"languageCodeChanged",t.ta),(t.X=e)&&ge(e,"languageCodeChanged",t.ta)}function zu(t,e){t.O=e,ls(t.b,Gn.SDK_VERSION?ir(Gn.SDK_VERSION,t.O):null)}function Yu(t,e){t.W&&_e(t.W,"frameworkChanged",t.sa),(t.W=e)&&ge(e,"frameworkChanged",t.sa)}function Xu(t){try{return Gn.app(t.o).auth()}catch(e){throw new Ur("internal-error","No firebase.auth.Auth instance is available for the Firebase App '"+t.o+"'!")}}function Ju(t){t.D||t.w.b||(t.w.start(),_e(t,"tokenChanged",t.V),ge(t,"tokenChanged",t.V))}function $u(t){_e(t,"tokenChanged",t.V),t.w.stop()}function Zu(t,e){t.ra=e,Cr(t,"_lat",e)}function tc(t){for(var e=[],n=0;n<t.N.length;n++)e.push(t.N[n](t));return St(e).then(function(){return t})}function ec(t){t.a&&!t.I&&(t.I=!0,t.a.subscribe(t))}function nc(t,e){Nr(t,{uid:e.uid,displayName:e.displayName||null,photoURL:e.photoURL||null,email:e.email||null,emailVerified:e.emailVerified||!1,phoneNumber:e.phoneNumber||null,isAnonymous:e.isAnonymous||!1,metadata:new Ku(e.createdAt,e.lastLoginAt),providerData:[]})}function rc(){}function ic(t){return wt().then(function(){if(t.D)throw new Ur("app-deleted")})}function oc(t){return P(t.providerData,function(t){return t.providerId})}function sc(t,e){e&&(ac(t,e.providerId),t.providerData.push(e))}function ac(t,e){F(t.providerData,function(t){return t.providerId==e})}function uc(t,e,n){("uid"!=e||n)&&t.hasOwnProperty(e)&&Cr(t,e,n)}function cc(t,e){t!=e&&(Nr(t,{uid:e.uid,displayName:e.displayName,photoURL:e.photoURL,email:e.email,emailVerified:e.emailVerified,phoneNumber:e.phoneNumber,isAnonymous:e.isAnonymous,providerData:[]}),e.metadata?Cr(t,"metadata",function(t){return new Ku(t.a,t.b)}(e.metadata)):Cr(t,"metadata",new Ku),O(e.providerData,function(e){sc(t,e)}),function(t,e){t.b=e.b,t.a=e.a,t.c=e.c}(t.h,e.h),Cr(t,"refreshToken",t.h.a))}function hc(t){return t.F().then(function(e){var n=t.isAnonymous;return function(t,e){return ta(t.b,Ms,{idToken:e}).then(m(t.xc,t))}(t,e).then(function(){return n||uc(t,"isAnonymous",!1),e})})}function lc(t,e){e[os]&&t.ra!=e[os]&&(Vu(t.h,e),t.dispatchEvent(new Qu("tokenChanged")),Zu(t,e[os]),uc(t,"refreshToken",t.h.a))}function fc(t,e){return hc(t).then(function(){if(M(oc(t),e))return tc(t).then(function(){throw new Ur("provider-already-linked")})})}function pc(t,e,n){return Dr({user:t,credential:Hi(e),additionalUserInfo:e=fi(e),operationType:n})}function dc(t,e){return lc(t,e),t.reload().then(function(){return t})}function yc(t,e,n,r,i){if(!ur())return Et(new Ur("operation-not-supported-in-this-environment"));if(t.i&&!i)return Et(t.i);var o=li(n.providerId),s=yr(t.uid+":::"),a=null;(!lr()||Xn())&&t.u&&n.isOAuthProvider&&(a=ya(t.u,t.m,t.o,e,n,null,s,Gn.SDK_VERSION||null));var u=Qn(a,o&&o.Ba,o&&o.Aa);return r=r().then(function(){if(gc(t),!i)return t.F().then(function(){})}).then(function(){return Nu(t.a,u,e,n,s,!!a)}).then(function(){return new dt(function(n,r){t.ha(e,null,new Ur("cancelled-popup-request"),t.g||null),t.f=n,t.v=r,t.g=s,t.c=t.a.Ea(t,e,u,s)})}).then(function(t){return u&&Kn(u),t?Dr(t):null}).s(function(t){throw u&&Kn(u),t}),vc(t,r,i)}function mc(t,e,n,r,i){if(!ur())return Et(new Ur("operation-not-supported-in-this-environment"));if(t.i&&!i)return Et(t.i);var o=null,s=yr(t.uid+":::");return r=r().then(function(){if(gc(t),!i)return t.F().then(function(){})}).then(function(){return t.aa=s,tc(t)}).then(function(e){return t.ba&&(e=(e=t.ba).b.set(_c,t.C(),e.a)),e}).then(function(){return t.a.Ca(e,n,s)}).s(function(e){if(o=e,t.ba)return wc(t.ba);throw o}).then(function(){if(o)throw o}),vc(t,r,i)}function gc(t){if(!t.a||!t.I){if(t.a&&!t.I)throw new Ur("internal-error");throw new Ur("auth-domain-config-required")}}function vc(t,e,n){var r=function(t,e,n){return t.i&&!n?(e.cancel(),Et(t.i)):e.s(function(e){throw!e||"auth/user-disabled"!=e.code&&"auth/user-token-expired"!=e.code||(t.i||t.dispatchEvent(new Qu("userInvalidated")),t.i=e),e})}(t,e,n);return t.G.push(r),r.ia(function(){x(t.G,r)}),r}function bc(t){if(!t.apiKey)return null;var e={apiKey:t.apiKey,authDomain:t.authDomain,appName:t.appName},n={};if(!(t.stsTokenManager&&t.stsTokenManager.accessToken&&t.stsTokenManager.expirationTime))return null;n[os]=t.stsTokenManager.accessToken,n.refreshToken=t.stsTokenManager.refreshToken||null,n.expiresIn=(t.stsTokenManager.expirationTime-v())/1e3;var r=new Hu(e,n,t);return t.providerData&&O(t.providerData,function(t){t&&sc(r,Dr(t))}),t.redirectEventId&&(r.aa=t.redirectEventId),r}Ru.prototype.reset=function(){this.b=null,this.a&&(this.a.cancel(),this.a=null)},Ru.prototype.h=function(t,e){if(t){this.reset(),this.g=!0;var n=t.b,r=t.c,i=t.a&&"auth/web-storage-unsupported"==t.a.code,o=t.a&&"auth/operation-not-supported-in-this-environment"==t.a.code;this.i=!(!i&&!o),"unknown"!=n||i||o?t.a?(Lu(this,!0,null,t.a),wt()):e.xa(n,r)?function(t,e,n){n=n.xa(e.b,e.c);var r=e.f,i=e.g,o=e.h,s=!!e.b.match(/Redirect$/);n(r,i,o).then(function(e){Lu(t,s,e,null)}).s(function(e){Lu(t,s,null,e)})}(this,t,e):Et(new Ur("invalid-auth-event")):(Lu(this,!1,null,null),wt())}else Et(new Ur("invalid-auth-event"))},Ru.prototype.Ya=function(){this.g&&!this.i&&Lu(this,!1,null,null)},Ru.prototype.fa=function(){var t=this;return new dt(function(e,n){t.b?t.b().then(e,n):(t.f.push(e),t.c.push(n),function(t){var e=new Ur("timeout");t.a&&t.a.cancel(),t.a=Le(Cu.get()).then(function(){t.b||(t.g=!0,Lu(t,!0,null,e))})}(t))})},Mu.prototype.h=function(t,e){if(t){var n=t.b,r=t.c;t.a?(e.ha(t.b,null,t.a,t.c),wt()):e.xa(n,r)?function(t,e){var n=t.c,r=t.b;e.xa(r,n)(t.f,t.g,t.h).then(function(t){e.ha(r,t,null,n)}).s(function(t){e.ha(r,null,t,n)})}(t,e):Et(new Ur("invalid-auth-event"))}else Et(new Ur("invalid-auth-event"))},Fu.prototype.confirm=function(t){return t=Qi(this.verificationId,t),this.a(t)},qu.prototype.start=function(){this.a=this.c,function t(e,r){e.stop();e.b=Le(function(t,e){return e?(t.a=t.c,t.g()):(e=t.a,t.a*=2,t.a>t.f&&(t.a=t.f),e)}(e,r)).then(function(){return t=n.document,e=null,br()||!t?wt():new dt(function(n){e=function(){br()&&(t.removeEventListener("visibilitychange",e,!1),n())},t.addEventListener("visibilitychange",e,!1)}).s(function(n){throw t.removeEventListener("visibilitychange",e,!1),n});var t,e}).then(function(){return e.h()}).then(function(){t(e,!0)}).s(function(n){e.i(n)&&t(e,!1)})}(this,!0)},qu.prototype.stop=function(){this.b&&(this.b.cancel(),this.b=null)},Bu.prototype.C=function(){return{apiKey:this.f.b,refreshToken:this.a,accessToken:this.b,expirationTime:this.c}},Bu.prototype.getToken=function(t){return t=!!t,this.b&&!this.a?Et(new Ur("user-token-expired")):t||!this.b||v()>this.c-3e4?this.a?ju(this,{grant_type:"refresh_token",refresh_token:this.a}):wt(null):wt({accessToken:this.b,expirationTime:this.c,refreshToken:this.a})},Ku.prototype.C=function(){return{lastLoginAt:this.b,createdAt:this.a}},b(Qu,se),b(Hu,Ae),Hu.prototype.pa=function(t){this.ka=t,hs(this.b,t)},Hu.prototype.ea=function(){return this.ka},Hu.prototype.ya=function(){return q(this.O)},Hu.prototype.Ha=function(){this.w.b&&(this.w.stop(),this.w.start())},Cr(Hu.prototype,"providerId","firebase"),(t=Hu.prototype).reload=function(){var t=this;return vc(this,ic(this).then(function(){return hc(t).then(function(){return tc(t)}).then(rc)}))},t.dc=function(t){return this.F(t).then(function(t){return new function(t){var e=ii(t);if(!(e&&e.exp&&e.auth_time&&e.iat))throw new Ur("internal-error","An internal error occurred. The token obtained by Firebase appears to be malformed. Please retry the operation.");Nr(this,{token:t,expirationTime:_r(1e3*e.exp),authTime:_r(1e3*e.auth_time),issuedAtTime:_r(1e3*e.iat),signInProvider:e.firebase&&e.firebase.sign_in_provider?e.firebase.sign_in_provider:null,claims:e})}(t)})},t.F=function(t){var e=this;return vc(this,ic(this).then(function(){return e.h.getToken(t)}).then(function(t){if(!t)throw new Ur("internal-error");return t.accessToken!=e.ra&&(Zu(e,t.accessToken),e.dispatchEvent(new Qu("tokenChanged"))),uc(e,"refreshToken",t.refreshToken),t.accessToken}))},t.xc=function(t){if(!(t=t.users)||!t.length)throw new Ur("internal-error");nc(this,{uid:(t=t[0]).localId,displayName:t.displayName,photoURL:t.photoUrl,email:t.email,emailVerified:!!t.emailVerified,phoneNumber:t.phoneNumber,lastLoginAt:t.lastLoginAt,createdAt:t.createdAt});for(var e=function(t){return(t=t.providerUserInfo)&&t.length?P(t,function(t){return new function(t,e,n,r,i,o){Nr(this,{uid:t,displayName:r||null,photoURL:i||null,email:n||null,phoneNumber:o||null,providerId:e})}(t.rawId,t.providerId,t.email,t.displayName,t.photoUrl,t.phoneNumber)}):[]}(t),n=0;n<e.length;n++)sc(this,e[n]);uc(this,"isAnonymous",!(this.email&&t.passwordHash||this.providerData&&this.providerData.length))},t.gb=function(t){var e=this,n=null;return vc(this,t.f(this.b,this.uid).then(function(t){return lc(e,t),n=pc(e,t,"reauthenticate"),e.i=null,e.reload()}).then(function(){return n}),!0)},t.yc=function(t){return Sr("firebase.User.prototype.reauthenticateWithCredential is deprecated. Please use firebase.User.prototype.reauthenticateAndRetrieveDataWithCredential instead."),this.gb(t).then(function(){})},t.eb=function(t){var e=this,n=null;return vc(this,fc(this,t.providerId).then(function(){return e.F()}).then(function(n){return t.b(e.b,n)}).then(function(t){return n=pc(e,t,"link"),dc(e,t)}).then(function(){return n}))},t.pc=function(t){return Sr("firebase.User.prototype.linkWithCredential is deprecated. Please use firebase.User.prototype.linkAndRetrieveDataWithCredential instead."),this.eb(t).then(function(t){return t.user})},t.qc=function(t,e){var n=this;return vc(this,fc(this,"phone").then(function(){return Uu(Xu(n),t,e,m(n.eb,n))}))},t.zc=function(t,e){var n=this;return vc(this,wt().then(function(){return Uu(Xu(n),t,e,m(n.gb,n))}),!0)},t.pb=function(t){var e=this;return vc(this,this.F().then(function(n){return e.b.pb(n,t)}).then(function(t){return lc(e,t),e.reload()}))},t.Rc=function(t){var e=this;return vc(this,this.F().then(function(n){return t.b(e.b,n)}).then(function(t){return lc(e,t),e.reload()}))},t.qb=function(t){var e=this;return vc(this,this.F().then(function(n){return e.b.qb(n,t)}).then(function(t){return lc(e,t),e.reload()}))},t.rb=function(t){if(void 0===t.displayName&&void 0===t.photoURL)return ic(this);var e=this;return vc(this,this.F().then(function(n){return e.b.rb(n,{displayName:t.displayName,photoUrl:t.photoURL})}).then(function(t){return lc(e,t),uc(e,"displayName",t.displayName||null),uc(e,"photoURL",t.photoUrl||null),O(e.providerData,function(t){"password"===t.providerId&&(Cr(t,"displayName",e.displayName),Cr(t,"photoURL",e.photoURL))}),tc(e)}).then(rc))},t.Pc=function(t){var e=this;return vc(this,hc(this).then(function(n){return M(oc(e),t)?function(t,e,n){return ta(t,Os,{idToken:e,deleteProvider:n})}(e.b,n,[t]).then(function(t){var n={};return O(t.providerUserInfo||[],function(t){n[t.providerId]=!0}),O(oc(e),function(t){n[t]||ac(e,t)}),n[Ki.PROVIDER_ID]||Cr(e,"phoneNumber",null),tc(e)}):tc(e).then(function(){throw new Ur("no-such-provider")})}))},t.delete=function(){var t=this;return vc(this,this.F().then(function(e){return ta(t.b,Rs,{idToken:e})}).then(function(){t.dispatchEvent(new Qu("userDeleted"))})).then(function(){for(var e=0;e<t.G.length;e++)t.G[e].cancel("app-deleted");Gu(t,null),Yu(t,null),t.G=[],t.D=!0,$u(t),Cr(t,"refreshToken",null),t.a&&t.a.unsubscribe(t)})},t.vb=function(t,e){return!!("linkViaPopup"==t&&(this.g||null)==e&&this.f||"reauthViaPopup"==t&&(this.g||null)==e&&this.f||"linkViaRedirect"==t&&(this.aa||null)==e||"reauthViaRedirect"==t&&(this.aa||null)==e)},t.ha=function(t,e,n,r){"linkViaPopup"!=t&&"reauthViaPopup"!=t||r!=(this.g||null)||(n&&this.v?this.v(n):e&&!n&&this.f&&this.f(e),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.v)},t.xa=function(t,e){return"linkViaPopup"==t&&e==(this.g||null)?m(this.Ab,this):"reauthViaPopup"==t&&e==(this.g||null)?m(this.Bb,this):"linkViaRedirect"==t&&(this.aa||null)==e?m(this.Ab,this):"reauthViaRedirect"==t&&(this.aa||null)==e?m(this.Bb,this):null},t.rc=function(t){var e=this;return yc(this,"linkViaPopup",t,function(){return fc(e,t.providerId).then(function(){return tc(e)})},!1)},t.Ac=function(t){return yc(this,"reauthViaPopup",t,function(){return wt()},!0)},t.sc=function(t){var e=this;return mc(this,"linkViaRedirect",t,function(){return fc(e,t.providerId)},!1)},t.Bc=function(t){return mc(this,"reauthViaRedirect",t,function(){return wt()},!0)},t.Ab=function(t,e,n){var r=this;this.c&&(this.c.cancel(),this.c=null);var i=null;return vc(this,this.F().then(function(i){return Ss(r.b,{requestUri:t,postBody:n,sessionId:e,idToken:i})}).then(function(t){return i=pc(r,t,"link"),dc(r,t)}).then(function(){return i}))},t.Bb=function(t,e,n){var r=this;this.c&&(this.c.cancel(),this.c=null);var i=null;return vc(this,wt().then(function(){return Ei(Is(r.b,{requestUri:t,sessionId:e,postBody:n}),r.uid)}).then(function(t){return i=pc(r,t,"reauthenticate"),lc(r,t),r.i=null,r.reload()}).then(function(){return i}),!0)},t.jb=function(t){var e=this,n=null;return vc(this,this.F().then(function(e){return n=e,void 0===t||rt(t)?{}:$r(new Wr(t))}).then(function(t){return e.b.jb(n,t)}).then(function(t){if(e.email!=t)return e.reload()}).then(function(){}))},t.toJSON=function(){return this.C()},t.C=function(){var t={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.C(),redirectEventId:this.aa||null};return this.metadata&&ut(t,this.metadata.C()),O(this.providerData,function(e){t.providerData.push(function(t){var e,n={};for(e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}(e))}),t};var _c={name:"redirectUser",A:"session"};function wc(t){return $a(t.b,_c,t.a)}function Ec(t){this.a=t,this.b=Ya(),this.c=null,this.f=function(t){var e=Ic("local"),r=Ic("session"),i=Ic("none");return function(t,e,r){var i=Ja(e,r),o=Xa(t,e.A);return t.get(e,r).then(function(s){var a=null;try{a=dr(n.localStorage.getItem(i))}catch(t){}if(a&&!s)return n.localStorage.removeItem(i),t.set(e,a,r);a&&s&&"localStorage"!=o.type&&n.localStorage.removeItem(i)})}(t.b,e,t.a).then(function(){return t.b.get(r,t.a)}).then(function(n){return n?r:t.b.get(i,t.a).then(function(n){return n?i:t.b.get(e,t.a).then(function(n){return n?e:t.b.get(Sc,t.a).then(function(t){return t?Ic(t):e})})})}).then(function(e){return t.c=e,Tc(t,e.A)}).s(function(){t.c||(t.c=e)})}(this),this.b.addListener(Ic("local"),this.a,m(this.g,this))}function Tc(t,e){var n,r=[];for(n in Ga)Ga[n]!==e&&r.push($a(t.b,Ic(Ga[n]),t.a));return r.push($a(t.b,Sc,t.a)),function(t){return new dt(function(e,n){var r=t.length,i=[];if(r)for(var o=function(t,n){r--,i[t]=n,0==r&&e(i)},s=function(t){n(t)},a=0;a<t.length;a++)Tt(t[a],g(o,a),s);else e(i)})}(r)}Ec.prototype.g=function(){var t=this,e=Ic("local");Ac(this,function(){return wt().then(function(){return t.c&&"local"!=t.c.A?t.b.get(e,t.a):null}).then(function(n){if(n)return Tc(t,"local").then(function(){t.c=e})})})};var Sc={name:"persistence",A:"session"};function Ic(t){return{name:"authUser",A:t}}function Cc(t,e){return Ac(t,function(){return t.b.set(t.c,e.C(),t.a)})}function Nc(t){return Ac(t,function(){return $a(t.b,t.c,t.a)})}function Dc(t,e){return Ac(t,function(){return t.b.get(t.c,t.a).then(function(t){return t&&e&&(t.authDomain=e),bc(t||{})})})}function Ac(t,e){return t.f=t.f.then(e,e),t.f}function kc(t){if(this.m=!1,Cr(this,"settings",new xu),Cr(this,"app",t),!Fc(this).options||!Fc(this).options.apiKey)throw new Ur("invalid-api-key");t=Gn.SDK_VERSION?ir(Gn.SDK_VERSION):null,this.b=new rs(Fc(this).options&&Fc(this).options.apiKey,ai(oi),t),this.N=[],this.o=[],this.I=[],this.Tb=Gn.INTERNAL.createSubscribe(m(this.mc,this)),this.O=void 0,this.Ub=Gn.INTERNAL.createSubscribe(m(this.nc,this)),Mc(this,null),this.h=new Ec(Fc(this).options.apiKey+":"+Fc(this).name),this.w=new function(t){this.a=t,this.b=Ya()}(Fc(this).options.apiKey+":"+Fc(this).name),this.V=Vc(this,function(t){var e=Fc(t).options.authDomain,n=function(t){var e=function(t,e){return t.b.get(_c,t.a).then(function(t){return t&&e&&(t.authDomain=e),bc(t||{})})}(t.w,Fc(t).options.authDomain).then(function(e){return(t.D=e)&&(e.ba=t.w),wc(t.w)});return Vc(t,e)}(t).then(function(){return Dc(t.h,e)}).then(function(e){return e?(e.ba=t.w,t.D&&(t.D.aa||null)==(e.aa||null)?e:e.reload().then(function(){return Cc(t.h,e).then(function(){return e})}).s(function(n){return"auth/network-request-failed"==n.code?e:Nc(t.h)})):null}).then(function(e){Mc(t,e||null)});return Vc(t,n)}(this)),this.i=Vc(this,function(t){return t.V.then(function(){return t.fa()}).s(function(){}).then(function(){if(!t.m)return t.ka()}).s(function(){}).then(function(){if(!t.m){t.X=!0;var e=t.h;e.b.addListener(Ic("local"),e.a,t.ka)}})}(this)),this.X=!1,this.ka=m(this.Mc,this),this.Ha=m(this.Z,this),this.ra=m(this.bc,this),this.sa=m(this.jc,this),this.ta=m(this.kc,this),function(t){var e=Fc(t).options.authDomain,n=Fc(t).options.apiKey;e&&ur()&&(t.Sb=t.V.then(function(){if(!t.m){if(t.a=ku(e,n,Fc(t).name),t.a.subscribe(t),Uc(t)&&ec(Uc(t)),t.D){ec(t.D);var r=t.D;r.pa(t.ea()),Gu(r,t),zu(r=t.D,t.G),Yu(r,t),t.D=null}return t.a}}))}(this),this.INTERNAL={},this.INTERNAL.delete=m(this.delete,this),this.INTERNAL.logFramework=m(this.tc,this),this.u=0,Ae.call(this),function(t){Object.defineProperty(t,"lc",{get:function(){return this.ea()},set:function(t){this.pa(t)},enumerable:!1}),t.W=null}(this),this.G=[]}function Rc(t){se.call(this,"languageCodeChanged"),this.g=t}function Oc(t){se.call(this,"frameworkChanged"),this.c=t}function Pc(t){return t.Sb||Et(new Ur("auth-domain-config-required"))}function Lc(t,e){var n={};return n.apiKey=Fc(t).options.apiKey,n.authDomain=Fc(t).options.authDomain,n.appName=Fc(t).name,t.V.then(function(){return function(t,e,n,r){var i=new Hu(t,e);return n&&(i.ba=n),r&&zu(i,r),i.reload().then(function(){return i})}(n,e,t.w,t.ya())}).then(function(e){return Uc(t)&&e.uid==Uc(t).uid?(cc(Uc(t),e),t.Z(e)):(Mc(t,e),ec(e),t.Z(e))}).then(function(){Bc(t)})}function Mc(t,e){Uc(t)&&(function(t,e){F(t.N,function(t){return t==e})}(Uc(t),t.Ha),_e(Uc(t),"tokenChanged",t.ra),_e(Uc(t),"userDeleted",t.sa),_e(Uc(t),"userInvalidated",t.ta),$u(Uc(t))),e&&(e.N.push(t.Ha),ge(e,"tokenChanged",t.ra),ge(e,"userDeleted",t.sa),ge(e,"userInvalidated",t.ta),0<t.u&&Ju(e)),Cr(t,"currentUser",e),e&&(e.pa(t.ea()),Gu(e,t),zu(e,t.G),Yu(e,t))}function xc(t,e){var n=null,r=null;return Vc(t,e.then(function(e){return n=Hi(e),r=fi(e),Lc(t,e)}).then(function(){return Dr({user:Uc(t),credential:n,additionalUserInfo:r,operationType:"signIn"})}))}function Fc(t){return t.app}function Uc(t){return t.currentUser}function qc(t){return Uc(t)&&Uc(t)._lat||null}function Bc(t){if(t.X){for(var e=0;e<t.o.length;e++)t.o[e]&&t.o[e](qc(t));if(t.O!==t.getUid()&&t.I.length)for(t.O=t.getUid(),e=0;e<t.I.length;e++)t.I[e]&&t.I[e](qc(t))}}function Vc(t,e){return t.N.push(e),e.ia(function(){x(t.N,e)}),e}function Wc(){}function jc(){this.a={},this.b=1e12}Ec.prototype.mb=function(t){var e=null,n=this;return function(t){var e=new Ur("invalid-persistence-type"),n=new Ur("unsupported-persistence-type");t:{for(r in Ga)if(Ga[r]==t){var r=!0;break t}r=!1}if(!r||"string"!=typeof t)throw e;switch($n()){case"ReactNative":if("session"===t)throw n;break;case"Node":if("none"!==t)throw n;break;default:if(!ar()&&"none"!==t)throw n}}(t),Ac(this,function(){return t!=n.c.A?n.b.get(n.c,n.a).then(function(r){return e=r,Tc(n,t)}).then(function(){if(n.c=Ic(t),e)return n.b.set(n.c,e,n.a)}):wt()})},b(kc,Ae),b(Rc,se),b(Oc,se),(t=kc.prototype).mb=function(t){return Vc(this,t=this.h.mb(t))},t.pa=function(t){this.W===t||this.m||(this.W=t,hs(this.b,this.W),this.dispatchEvent(new Rc(this.ea())))},t.ea=function(){return this.W},t.Sc=function(){var t=n.navigator;this.pa(t&&(t.languages&&t.languages[0]||t.language||t.userLanguage)||null)},t.tc=function(t){this.G.push(t),ls(this.b,Gn.SDK_VERSION?ir(Gn.SDK_VERSION,this.G):null),this.dispatchEvent(new Oc(this.G))},t.ya=function(){return q(this.G)},t.toJSON=function(){return{apiKey:Fc(this).options.apiKey,authDomain:Fc(this).options.authDomain,appName:Fc(this).name,currentUser:Uc(this)&&Uc(this).C()}},t.vb=function(t,e){switch(t){case"unknown":case"signInViaRedirect":return!0;case"signInViaPopup":return this.g==e&&!!this.f;default:return!1}},t.ha=function(t,e,n,r){"signInViaPopup"==t&&this.g==r&&(n&&this.v?this.v(n):e&&!n&&this.f&&this.f(e),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.v)},t.xa=function(t,e){return"signInViaRedirect"==t||"signInViaPopup"==t&&this.g==e&&this.f?m(this.ac,this):null},t.ac=function(t,e,n){var r=this;t={requestUri:t,postBody:n,sessionId:e},this.c&&(this.c.cancel(),this.c=null);var i=null,o=null,s=Ts(r.b,t).then(function(t){return i=Hi(t),o=fi(t),t});return Vc(this,t=r.V.then(function(){return s}).then(function(t){return Lc(r,t)}).then(function(){return Dr({user:Uc(r),credential:i,additionalUserInfo:o,operationType:"signIn"})}))},t.Kc=function(t){if(!ur())return Et(new Ur("operation-not-supported-in-this-environment"));var e=this,n=li(t.providerId),r=yr(),i=null;(!lr()||Xn())&&Fc(this).options.authDomain&&t.isOAuthProvider&&(i=ya(Fc(this).options.authDomain,Fc(this).options.apiKey,Fc(this).name,"signInViaPopup",t,null,r,Gn.SDK_VERSION||null));var o=Qn(i,n&&n.Ba,n&&n.Aa);return Vc(this,n=Pc(this).then(function(e){return Nu(e,o,"signInViaPopup",t,r,!!i)}).then(function(){return new dt(function(t,n){e.ha("signInViaPopup",null,new Ur("cancelled-popup-request"),e.g),e.f=t,e.v=n,e.g=r,e.c=e.a.Ea(e,"signInViaPopup",o,r)})}).then(function(t){return o&&Kn(o),t?Dr(t):null}).s(function(t){throw o&&Kn(o),t}))},t.Lc=function(t){if(!ur())return Et(new Ur("operation-not-supported-in-this-environment"));var e=this;return Vc(this,Pc(this).then(function(){return Ac(t=e.h,function(){return t.b.set(Sc,t.c.A,t.a)});var t}).then(function(){return e.a.Ca("signInViaRedirect",t)}))},t.fa=function(){if(!ur())return Et(new Ur("operation-not-supported-in-this-environment"));var t=this;return Vc(this,Pc(this).then(function(){return t.a.fa()}).then(function(t){return t?Dr(t):null}))},t.Qc=function(t){if(!t)return Et(new Ur("null-user"));var e=this,n={};n.apiKey=Fc(this).options.apiKey,n.authDomain=Fc(this).options.authDomain,n.appName=Fc(this).name;var r=function(t,e,n,r){e=e||{apiKey:t.m,authDomain:t.u,appName:t.o};var i=t.h,o={};return o[os]=i.b,o.refreshToken=i.a,o.expiresIn=(i.c-v())/1e3,e=new Hu(e,o),n&&(e.ba=n),r&&zu(e,r),cc(e,t),e}(t,n,e.w,e.ya());return Vc(this,this.i.then(function(){if(Fc(e).options.apiKey!=t.m)return r.reload()}).then(function(){return Uc(e)&&t.uid==Uc(e).uid?(cc(Uc(e),t),e.Z(t)):(Mc(e,r),ec(r),e.Z(r))}).then(function(){Bc(e)}))},t.nb=function(){var t=this;return Vc(this,this.i.then(function(){return Uc(t)?(Mc(t,null),Nc(t.h).then(function(){Bc(t)})):wt()}))},t.Mc=function(){var t=this;return Dc(this.h,Fc(this).options.authDomain).then(function(e){if(!t.m){var n;if(n=Uc(t)&&e){n=Uc(t).uid;var r=e.uid;n=void 0!==n&&null!==n&&""!==n&&void 0!==r&&null!==r&&""!==r&&n==r}if(n)return cc(Uc(t),e),Uc(t).F();(Uc(t)||e)&&(Mc(t,e),e&&(ec(e),e.ba=t.w),t.a&&t.a.subscribe(t),Bc(t))}})},t.Z=function(t){return Cc(this.h,t)},t.bc=function(){Bc(this),this.Z(Uc(this))},t.jc=function(){this.nb()},t.kc=function(){this.nb()},t.mc=function(t){var e=this;this.addAuthTokenListener(function(){t.next(Uc(e))})},t.nc=function(t){var e=this;!function(t,e){t.I.push(e),Vc(t,t.i.then(function(){!t.m&&M(t.I,e)&&t.O!==t.getUid()&&(t.O=t.getUid(),e(qc(t)))}))}(this,function(){t.next(Uc(e))})},t.vc=function(t,e,n){var r=this;return this.X&&Gn.Promise.resolve().then(function(){h(t)?t(Uc(r)):h(t.next)&&t.next(Uc(r))}),this.Tb(t,e,n)},t.uc=function(t,e,n){var r=this;return this.X&&Gn.Promise.resolve().then(function(){r.O=r.getUid(),h(t)?t(Uc(r)):h(t.next)&&t.next(Uc(r))}),this.Ub(t,e,n)},t.cc=function(t){var e=this;return Vc(this,this.i.then(function(){return Uc(e)?Uc(e).F(t).then(function(t){return{accessToken:t}}):null}))},t.Nb=function(t){var e=this;return this.i.then(function(){return xc(e,ta(e.b,Ys,{token:t}))}).then(function(t){var n=t.user;return uc(n,"isAnonymous",!1),e.Z(n),t})},t.Ec=function(t){return Sr("firebase.auth.Auth.prototype.signInAndRetrieveDataWithCustomToken is deprecated. Please use firebase.auth.Auth.prototype.signInWithCustomToken instead."),this.Nb(t)},t.Fc=function(t,e){return Sr("firebase.auth.Auth.prototype.signInAndRetrieveDataWithEmailAndPassword is deprecated. Please use firebase.auth.Auth.prototype.signInWithEmailAndPassword instead."),this.Ob(t,e)},t.Ob=function(t,e){var n=this;return this.i.then(function(){return xc(n,ta(n.b,Xs,{email:t,password:e}))})},t.xb=function(t,e){var n=this;return this.i.then(function(){return xc(n,ta(n.b,As,{email:t,password:e}))})},t.Wb=function(t,e){return Sr("firebase.auth.Auth.prototype.createUserAndRetrieveDataWithEmailAndPassword is deprecated. Please use firebase.auth.Auth.prototype.createUserWithEmailAndPassword instead."),this.xb(t,e)},t.Hc=function(t){return Sr("firebase.auth.Auth.prototype.signInWithCredential is deprecated. Please use firebase.auth.Auth.prototype.signInAndRetrieveDataWithCredential instead."),this.Pa(t).then(function(t){return t.user})},t.Pa=function(t){var e=this;return this.i.then(function(){return xc(e,t.la(e.b))})},t.Qa=function(){var t=this;return this.i.then(function(){var e=Uc(t);return e&&e.isAnonymous?Dr({user:e,credential:null,additionalUserInfo:Dr({providerId:null,isNewUser:!1}),operationType:"signIn"}):xc(t,t.b.Qa()).then(function(e){var n=e.user;return uc(n,"isAnonymous",!0),t.Z(n),e})})},t.Gc=function(){return Sr("firebase.auth.Auth.prototype.signInAnonymouslyAndRetrieveData is deprecated. Please use firebase.auth.Auth.prototype.signInAnonymously instead."),this.Qa()},t.getUid=function(){return Uc(this)&&Uc(this).uid||null},t.Vb=function(t){this.addAuthTokenListener(t),this.u++,0<this.u&&Uc(this)&&Ju(Uc(this))},t.Cc=function(t){var e=this;O(this.o,function(n){n==t&&e.u--}),0>this.u&&(this.u=0),0==this.u&&Uc(this)&&$u(Uc(this)),this.removeAuthTokenListener(t)},t.addAuthTokenListener=function(t){var e=this;this.o.push(t),Vc(this,this.i.then(function(){e.m||M(e.o,t)&&t(qc(e))}))},t.removeAuthTokenListener=function(t){F(this.o,function(e){return e==t})},t.delete=function(){this.m=!0;for(var t=0;t<this.N.length;t++)this.N[t].cancel("app-deleted");return this.N=[],this.h&&(t=this.h).b.removeListener(Ic("local"),t.a,this.ka),this.a&&(this.a.unsubscribe(this),this.a.Ya()),Gn.Promise.resolve()},t.Zb=function(t){return Sr("firebase.auth.Auth.prototype.fetchProvidersForEmail is deprecated. Please use firebase.auth.Auth.prototype.fetchSignInMethodsForEmail instead."),Vc(this,function(t,e){return ta(t,ks,{identifier:e,continueUri:cr()?Vn():"http://localhost"}).then(function(t){return t.allProviders||[]})}(this.b,t))},t.$b=function(t){return Vc(this,function(t,e){return ta(t,ks,{identifier:e,continueUri:cr()?Vn():"http://localhost"}).then(function(t){return t.signinMethods||[]})}(this.b,t))},t.oc=function(t){return!!Vi(t)},t.lb=function(t,e){var n=this;return Vc(this,wt().then(function(){var t=new Wr(e);if(!t.c)throw new Ur("argument-error",Qr+" must be true when sending sign in link to email");return $r(t)}).then(function(e){return n.b.lb(t,e)}).then(function(){}))},t.Tc=function(t){return this.Ja(t).then(function(t){return t.data.email})},t.Za=function(t,e){return Vc(this,this.b.Za(t,e).then(function(){}))},t.Ja=function(t){return Vc(this,this.b.Ja(t).then(function(t){return new function(t){var e={},n=t[Rr],r=t[Or];if(!(t=t[Pr])||t!=kr&&!n)throw Error("Invalid provider user info!");e[Mr]=r||null,e[Lr]=n||null,Cr(this,Fr,t),Cr(this,xr,Ar(e))}(t)}))},t.Wa=function(t){return Vc(this,this.b.Wa(t).then(function(){}))},t.kb=function(t,e){var n=this;return Vc(this,wt().then(function(){return void 0===e||rt(e)?{}:$r(new Wr(e))}).then(function(e){return n.b.kb(t,e)}).then(function(){}))},t.Jc=function(t,e){return Vc(this,Uu(this,t,e,m(this.Pa,this)))},t.Ic=function(t,e){var n=this;return Vc(this,wt().then(function(){var r=Bi(t,e||Vn());return n.Pa(r)}))},Wc.prototype.render=function(){},Wc.prototype.reset=function(){},Wc.prototype.getResponse=function(){},Wc.prototype.execute=function(){};var Kc=null;function Qc(t,e){return(e=Hc(e))&&t.a[e]||null}function Hc(t){return(t=void 0===t?1e12:t)?t.toString():null}function Gc(t,e){this.g=!1,this.c=e,this.a=this.b=null,this.h="invisible"!==this.c.size,this.f=Rn(t);var n=this;this.i=function(){n.execute()},this.h?this.execute():ge(this.f,"click",this.i)}function zc(t){if(t.g)throw Error("reCAPTCHA mock was already deleted!")}function Yc(){}jc.prototype.render=function(t,e){return this.a[this.b.toString()]=new Gc(t,e),this.b++},jc.prototype.reset=function(t){var e=Qc(this,t);t=Hc(t),e&&t&&(e.delete(),delete this.a[t])},jc.prototype.getResponse=function(t){return(t=Qc(this,t))?t.getResponse():null},jc.prototype.execute=function(t){(t=Qc(this,t))&&t.execute()},Gc.prototype.getResponse=function(){return zc(this),this.b},Gc.prototype.execute=function(){zc(this);var t=this;this.a||(this.a=setTimeout(function(){t.b=function(){for(var t=50,e=[];0<t;)e.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.floor(62*Math.random()))),t--;return e.join("")}();var e=t.c.callback,n=t.c["expired-callback"];if(e)try{e(t.b)}catch(t){}t.a=setTimeout(function(){if(t.a=null,t.b=null,n)try{n()}catch(t){}t.h&&t.execute()},6e4)},500))},Gc.prototype.delete=function(){zc(this),this.g=!0,clearTimeout(this.a),this.a=null,_e(this.f,"click",this.i)},Yc.prototype.g=function(){return Kc||(Kc=new jc),wt(Kc)},Yc.prototype.c=function(){};var Xc=null;function Jc(){this.b=n.grecaptcha?1/0:0,this.f=null,this.a="__rcb"+Math.floor(1e6*Math.random()).toString()}var $c=yn("https://www.google.com/recaptcha/api.js?onload=%{onload}&render=explicit&hl=%{hl}"),Zc=new vr(3e4,6e4);Jc.prototype.g=function(t){var e=this;return new dt(function(r,i){var o=setTimeout(function(){i(new Ur("network-request-failed"))},Zc.get());!n.grecaptcha||t!==e.f&&!e.b?(n[e.a]=function(){if(n.grecaptcha){e.f=t;var s=n.grecaptcha.render;n.grecaptcha.render=function(t,n){return t=s(t,n),e.b++,t},clearTimeout(o),r(n.grecaptcha)}else clearTimeout(o),i(new Ur("internal-error"));delete n[e.a]},wt(Xo(vn($c,{onload:e.a,hl:t||""}))).s(function(){clearTimeout(o),i(new Ur("internal-error","Unable to load external reCAPTCHA dependencies!"))})):(clearTimeout(o),r(n.grecaptcha))})},Jc.prototype.c=function(){this.b--};var th=null;function eh(t,e,r,i,o,s,a){if(Cr(this,"type","recaptcha"),this.c=this.f=null,this.D=!1,this.m=e,this.g=null,a?(Xc||(Xc=new Yc),a=Xc):(th||(th=new Jc),a=th),this.o=a,this.a=r||{theme:"light",type:"image"},this.h=[],this.a[ih])throw new Ur("argument-error","sitekey should not be provided for reCAPTCHA as one is automatically provisioned for the current project.");if(this.i="invisible"===this.a[oh],!n.document)throw new Ur("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment with DOM support.");if(!Rn(e)||!this.i&&Rn(e).hasChildNodes())throw new Ur("argument-error","reCAPTCHA container is either not found or already contains inner elements!");this.u=new rs(t,s||null,o||null),this.v=i||function(){return null};var u=this;this.l=[];var c=this.a[nh];this.a[nh]=function(t){if(sh(u,t),"function"==typeof c)c(t);else if("string"==typeof c){var e=sr(c,n);"function"==typeof e&&e(t)}};var h=this.a[rh];this.a[rh]=function(){if(sh(u,null),"function"==typeof h)h();else if("string"==typeof h){var t=sr(h,n);"function"==typeof t&&t()}}}var nh="callback",rh="expired-callback",ih="sitekey",oh="size";function sh(t,e){for(var n=0;n<t.l.length;n++)try{t.l[n](e)}catch(t){}}function ah(t,e){return t.h.push(e),e.ia(function(){x(t.h,e)}),e}function uh(t){if(t.D)throw new Ur("internal-error","RecaptchaVerifier instance has been destroyed.")}function ch(t,e,n){var r=!1;try{this.b=n||Gn.app()}catch(t){throw new Ur("argument-error","No firebase.app.App instance is currently initialized.")}if(!this.b.options||!this.b.options.apiKey)throw new Ur("invalid-api-key");n=this.b.options.apiKey;var i=this,o=null;try{o=this.b.auth().ya()}catch(t){}try{r=this.b.auth().settings.appVerificationDisabledForTesting}catch(t){}o=Gn.SDK_VERSION?ir(Gn.SDK_VERSION,o):null,eh.call(this,n,t,e,function(){try{var t=i.b.auth().ea()}catch(e){t=null}return t},o,ai(oi),r)}function hh(t,e,n,r){t:{n=Array.prototype.slice.call(n);for(var i=0,o=!1,s=0;s<e.length;s++)if(e[s].optional)o=!0;else{if(o)throw new Ur("internal-error","Argument validator encountered a required argument after an optional argument.");i++}if(o=e.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=e[i].optional&&void 0===n[i],!e[i].M(n[i])&&!o){if(e=e[i],0>i||i>=lh.length)throw new Ur("internal-error","Argument validator received an unsupported number of arguments.");n=lh[i],r=(r?"":n+" argument ")+(e.name?'"'+e.name+'" ':"")+"must be "+e.K+".";break t}r=null}}if(r)throw new Ur("argument-error",t+" failed: "+r)}(t=eh.prototype).za=function(){var t=this;return this.f?this.f:this.f=ah(this,wt().then(function(){if(cr()&&!Jn())return zn();throw new Ur("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment.")}).then(function(){return t.o.g(t.v())}).then(function(e){return t.g=e,ta(t.u,Bs,{})}).then(function(e){t.a[ih]=e.recaptchaSiteKey}).s(function(e){throw t.f=null,e}))},t.render=function(){uh(this);var t=this;return ah(this,this.za().then(function(){if(null===t.c){var e=t.m;if(!t.i){var n=Rn(e);e=Ln("DIV"),n.appendChild(e)}t.c=t.g.render(e,t.a)}return t.c}))},t.verify=function(){uh(this);var t=this;return ah(this,this.render().then(function(e){return new dt(function(n){var r=t.g.getResponse(e);if(r)n(r);else{var i=function(e){e&&(function(t,e){F(t.l,function(t){return t==e})}(t,i),n(e))};t.l.push(i),t.i&&t.g.execute(t.c)}})}))},t.reset=function(){uh(this),null!==this.c&&this.g.reset(this.c)},t.clear=function(){uh(this),this.D=!0,this.o.c();for(var t=0;t<this.h.length;t++)this.h[t].cancel("RecaptchaVerifier instance has been destroyed.");if(!this.i){t=Rn(this.m);for(var e;e=t.firstChild;)t.removeChild(e)}},b(ch,eh);var lh="First Second Third Fourth Fifth Sixth Seventh Eighth Ninth".split(" ");function fh(t,e){return{name:t||"",K:"a valid string",optional:!!e,M:r}}function ph(t,e){return{name:t||"",K:"a boolean",optional:!!e,M:i}}function dh(t,e){return{name:t||"",K:"a valid object",optional:!!e,M:l}}function yh(t,e){return{name:t||"",K:"a function",optional:!!e,M:h}}function mh(t,e){return{name:t||"",K:"null",optional:!!e,M:a}}function gh(t){return{name:t?t+"Credential":"credential",K:t?"a valid "+t+" credential":"a valid credential",optional:!1,M:function(e){if(!e)return!1;var n=!t||e.providerId===t;return!(!e.la||!n)}}}function vh(){return{name:"applicationVerifier",K:"an implementation of firebase.auth.ApplicationVerifier",optional:!1,M:function(t){return!!(t&&r(t.type)&&h(t.verify))}}}function bh(t,e,n,r){return{name:n||"",K:t.K+" or "+e.K,optional:!!r,M:function(n){return t.M(n)||e.M(n)}}}function _h(t,e){for(var n in e){var r=e[n].name;t[r]=Th(r,t[n],e[n].j)}}function wh(t,e){for(var n in e){var r=e[n].name;r!==n&&Object.defineProperty(t,r,{get:g(function(t){return this[t]},n),set:g(function(t,e,n,r){hh(t,[n],[r],!0),this[e]=r},r,n,e[n].tb),enumerable:!0})}}function Eh(t,e,n,r){t[e]=Th(e,n,r)}function Th(t,e,n){function r(){var t=Array.prototype.slice.call(arguments);return hh(o,n,t),e.apply(this,t)}if(!n)return e;var i,o=function(t){return(t=t.split("."))[t.length-1]}(t);for(i in e)r[i]=e[i];for(i in e.prototype)r.prototype[i]=e.prototype[i];return r}_h(kc.prototype,{Wa:{name:"applyActionCode",j:[fh("code")]},Ja:{name:"checkActionCode",j:[fh("code")]},Za:{name:"confirmPasswordReset",j:[fh("code"),fh("newPassword")]},xb:{name:"createUserWithEmailAndPassword",j:[fh("email"),fh("password")]},Wb:{name:"createUserAndRetrieveDataWithEmailAndPassword",j:[fh("email"),fh("password")]},Zb:{name:"fetchProvidersForEmail",j:[fh("email")]},$b:{name:"fetchSignInMethodsForEmail",j:[fh("email")]},fa:{name:"getRedirectResult",j:[]},oc:{name:"isSignInWithEmailLink",j:[fh("emailLink")]},uc:{name:"onAuthStateChanged",j:[bh(dh(),yh(),"nextOrObserver"),yh("opt_error",!0),yh("opt_completed",!0)]},vc:{name:"onIdTokenChanged",j:[bh(dh(),yh(),"nextOrObserver"),yh("opt_error",!0),yh("opt_completed",!0)]},kb:{name:"sendPasswordResetEmail",j:[fh("email"),bh(dh("opt_actionCodeSettings",!0),mh(null,!0),"opt_actionCodeSettings",!0)]},lb:{name:"sendSignInLinkToEmail",j:[fh("email"),dh("actionCodeSettings")]},mb:{name:"setPersistence",j:[fh("persistence")]},Pa:{name:"signInAndRetrieveDataWithCredential",j:[gh()]},Qa:{name:"signInAnonymously",j:[]},Gc:{name:"signInAnonymouslyAndRetrieveData",j:[]},Hc:{name:"signInWithCredential",j:[gh()]},Nb:{name:"signInWithCustomToken",j:[fh("token")]},Ec:{name:"signInAndRetrieveDataWithCustomToken",j:[fh("token")]},Ob:{name:"signInWithEmailAndPassword",j:[fh("email"),fh("password")]},Ic:{name:"signInWithEmailLink",j:[fh("email"),fh("emailLink",!0)]},Fc:{name:"signInAndRetrieveDataWithEmailAndPassword",j:[fh("email"),fh("password")]},Jc:{name:"signInWithPhoneNumber",j:[fh("phoneNumber"),vh()]},Kc:{name:"signInWithPopup",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},Lc:{name:"signInWithRedirect",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},Qc:{name:"updateCurrentUser",j:[bh({name:"user",K:"an instance of Firebase User",optional:!1,M:function(t){return!!(t&&t instanceof Hu)}},mh(),"user")]},nb:{name:"signOut",j:[]},toJSON:{name:"toJSON",j:[fh(null,!0)]},Sc:{name:"useDeviceLanguage",j:[]},Tc:{name:"verifyPasswordResetCode",j:[fh("code")]}}),wh(kc.prototype,{lc:{name:"languageCode",tb:bh(fh(),mh(),"languageCode")}}),kc.Persistence=Ga,kc.Persistence.LOCAL="local",kc.Persistence.SESSION="session",kc.Persistence.NONE="none",_h(Hu.prototype,{delete:{name:"delete",j:[]},dc:{name:"getIdTokenResult",j:[ph("opt_forceRefresh",!0)]},F:{name:"getIdToken",j:[ph("opt_forceRefresh",!0)]},eb:{name:"linkAndRetrieveDataWithCredential",j:[gh()]},pc:{name:"linkWithCredential",j:[gh()]},qc:{name:"linkWithPhoneNumber",j:[fh("phoneNumber"),vh()]},rc:{name:"linkWithPopup",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},sc:{name:"linkWithRedirect",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},gb:{name:"reauthenticateAndRetrieveDataWithCredential",j:[gh()]},yc:{name:"reauthenticateWithCredential",j:[gh()]},zc:{name:"reauthenticateWithPhoneNumber",j:[fh("phoneNumber"),vh()]},Ac:{name:"reauthenticateWithPopup",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},Bc:{name:"reauthenticateWithRedirect",j:[{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}]},reload:{name:"reload",j:[]},jb:{name:"sendEmailVerification",j:[bh(dh("opt_actionCodeSettings",!0),mh(null,!0),"opt_actionCodeSettings",!0)]},toJSON:{name:"toJSON",j:[fh(null,!0)]},Pc:{name:"unlink",j:[fh("provider")]},pb:{name:"updateEmail",j:[fh("email")]},qb:{name:"updatePassword",j:[fh("password")]},Rc:{name:"updatePhoneNumber",j:[gh("phone")]},rb:{name:"updateProfile",j:[dh("profile")]}}),_h(jc.prototype,{execute:{name:"execute"},render:{name:"render"},reset:{name:"reset"},getResponse:{name:"getResponse"}}),_h(Wc.prototype,{execute:{name:"execute"},render:{name:"render"},reset:{name:"reset"},getResponse:{name:"getResponse"}}),_h(dt.prototype,{ia:{name:"finally"},s:{name:"catch"},then:{name:"then"}}),wh(xu.prototype,{appVerificationDisabled:{name:"appVerificationDisabledForTesting",tb:ph("appVerificationDisabledForTesting")}}),_h(Fu.prototype,{confirm:{name:"confirm",j:[fh("verificationCode")]}}),Eh(qi,"credential",function(t,e){return new Ui(t,e)},[fh("email"),fh("password")]),_h(ki.prototype,{ua:{name:"addScope",j:[fh("scope")]},Da:{name:"setCustomParameters",j:[dh("customOAuthParameters")]}}),Eh(ki,"credential",Ri,[bh(fh(),dh(),"token")]),Eh(qi,"credentialWithLink",Bi,[fh("email"),fh("emailLink")]),_h(Oi.prototype,{ua:{name:"addScope",j:[fh("scope")]},Da:{name:"setCustomParameters",j:[dh("customOAuthParameters")]}}),Eh(Oi,"credential",Pi,[bh(fh(),dh(),"token")]),_h(Li.prototype,{ua:{name:"addScope",j:[fh("scope")]},Da:{name:"setCustomParameters",j:[dh("customOAuthParameters")]}}),Eh(Li,"credential",Mi,[bh(fh(),bh(dh(),mh()),"idToken"),bh(fh(),mh(),"accessToken",!0)]),_h(xi.prototype,{Da:{name:"setCustomParameters",j:[dh("customOAuthParameters")]}}),Eh(xi,"credential",Fi,[bh(fh(),dh(),"token"),fh("secret",!0)]),_h(Ai.prototype,{ua:{name:"addScope",j:[fh("scope")]},credential:{name:"credential",j:[bh(fh(),mh(),"idToken",!0),bh(fh(),mh(),"accessToken",!0),bh(fh(),mh(),"nonce",!0)]},Da:{name:"setCustomParameters",j:[dh("customOAuthParameters")]}}),Eh(Ki,"credential",Qi,[fh("verificationId"),fh("verificationCode")]),_h(Ki.prototype,{Ua:{name:"verifyPhoneNumber",j:[fh("phoneNumber"),vh()]}}),_h(Ur.prototype,{toJSON:{name:"toJSON",j:[fh(null,!0)]}}),_h(Zi.prototype,{toJSON:{name:"toJSON",j:[fh(null,!0)]}}),_h($i.prototype,{toJSON:{name:"toJSON",j:[fh(null,!0)]}}),_h(ch.prototype,{clear:{name:"clear",j:[]},render:{name:"render",j:[]},verify:{name:"verify",j:[]}}),function(){if(void 0===Gn||!Gn.INTERNAL||!Gn.INTERNAL.registerService)throw Error("Cannot find the firebase namespace; be sure to include firebase-app.js before this library.");var t={Auth:kc,Error:Ur};Eh(t,"EmailAuthProvider",qi,[]),Eh(t,"FacebookAuthProvider",ki,[]),Eh(t,"GithubAuthProvider",Oi,[]),Eh(t,"GoogleAuthProvider",Li,[]),Eh(t,"TwitterAuthProvider",xi,[]),Eh(t,"OAuthProvider",Ai,[fh("providerId")]),Eh(t,"SAMLAuthProvider",Di,[fh("providerId")]),Eh(t,"PhoneAuthProvider",Ki,[{name:"auth",K:"an instance of Firebase Auth",optional:!0,M:function(t){return!!(t&&t instanceof kc)}}]),Eh(t,"RecaptchaVerifier",ch,[bh(fh(),{name:"",K:"an HTML element",optional:!1,M:function(t){return!!(t&&t instanceof Element)}},"recaptchaContainer"),dh("recaptchaParameters",!0),{name:"app",K:"an instance of Firebase App",optional:!0,M:function(t){return!!(t&&t instanceof Gn.app.App)}}]),Gn.INTERNAL.registerService("auth",function(t,e){return e({INTERNAL:{getUid:m((t=new kc(t)).getUid,t),getToken:m(t.cc,t),addAuthTokenListener:m(t.Vb,t),removeAuthTokenListener:m(t.Cc,t)}}),t},t,function(t,e){if("create"===t)try{e.auth()}catch(t){}}),Gn.INTERNAL.extendNamespace({User:Hu})}()}).apply("undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(Qn||(Qn={}));var zn=Qn.INFO,Yn=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(e<t.logLevel)){var i=(new Date).toISOString();switch(e){case Qn.DEBUG:case Qn.VERBOSE:console.log.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case Qn.INFO:console.info.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case Qn.WARN:console.warn.apply(console,["["+i+"] "+t.name+":"].concat(n));break;case Qn.ERROR:console.error.apply(console,["["+i+"] "+t.name+":"].concat(n));break;default:throw new Error("Attempted to log a message with an invalid logType (value: "+e+")")}}},Xn=function(){function t(t){this.name=t,this._logLevel=zn,this._logHandler=Yn}return Object.defineProperty(t.prototype,"logLevel",{get:function(){return this._logLevel},set:function(t){if(!(t in Qn))throw new TypeError("Invalid value assigned to `logLevel`");this._logLevel=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"logHandler",{get:function(){return this._logHandler},set:function(t){if("function"!=typeof t)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t},enumerable:!0,configurable:!0}),t.prototype.debug=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Qn.DEBUG].concat(t))},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Qn.VERBOSE].concat(t))},t.prototype.info=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Qn.INFO].concat(t))},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Qn.WARN].concat(t))},t.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._logHandler.apply(this,[this,Qn.ERROR].concat(t))},t}(),Jn=function(){function t(t){this.domStorage_=t,this.prefix_="firebase:"}return t.prototype.set=function(t,e){null==e?this.domStorage_.removeItem(this.prefixedName_(t)):this.domStorage_.setItem(this.prefixedName_(t),_n(e))},t.prototype.get=function(t){var e=this.domStorage_.getItem(this.prefixedName_(t));return null==e?null:bn(e)},t.prototype.remove=function(t){this.domStorage_.removeItem(this.prefixedName_(t))},t.prototype.prefixedName_=function(t){return this.prefix_+t},t.prototype.toString=function(){return this.domStorage_.toString()},t}(),$n=function(){function t(){this.cache_={},this.isInMemoryStorage=!0}return t.prototype.set=function(t,e){null==e?delete this.cache_[t]:this.cache_[t]=e},t.prototype.get=function(t){return En(this.cache_,t)?this.cache_[t]:null},t.prototype.remove=function(t){delete this.cache_[t]},t}(),Zn=function(t){try{if("undefined"!=typeof window&&void 0!==window[t]){var e=window[t];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new Jn(e)}}catch(t){}return new $n},tr=Zn("localStorage"),er=Zn("sessionStorage"),nr=new Xn("@firebase/database"),rr=function(){var t=1;return function(){return t++}}(),ir=function(t){var e=function(t){for(var e=[],n=0,r=0;r<t.length;r++){var i=t.charCodeAt(r);if(i>=55296&&i<=56319){var o=i-55296;rn(++r<t.length,"Surrogate pair missing trail surrogate."),i=65536+(o<<10)+(t.charCodeAt(r)-56320)}i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=63&i|128):i<65536?(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128)}return e}(t),n=new Rn;n.update(e);var r=n.digest();return an.encodeByteArray(r)},or=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];for(var n="",r=0;r<t.length;r++)Array.isArray(t[r])||t[r]&&"object"==typeof t[r]&&"number"==typeof t[r].length?n+=or.apply(null,t[r]):"object"==typeof t[r]?n+=_n(t[r]):n+=t[r],n+=" ";return n},sr=null,ar=!0,ur=function(t,e){rn(!e||!0===t||!1===t,"Can't turn on custom loggers persistently."),!0===t?(nr.logLevel=Qn.VERBOSE,sr=nr.log.bind(nr),e&&er.set("logging_enabled",!0)):"function"==typeof t?sr=t:(sr=null,er.remove("logging_enabled"))},cr=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(!0===ar&&(ar=!1,null===sr&&!0===er.get("logging_enabled")&&ur(!0)),sr){var n=or.apply(null,t);sr(n)}},hr=function(t){return function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];cr.apply(void 0,[t].concat(e))}},lr=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="FIREBASE INTERNAL ERROR: "+or.apply(void 0,t);nr.error(n)},fr=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="FIREBASE FATAL ERROR: "+or.apply(void 0,t);throw nr.error(n),new Error(n)},pr=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="FIREBASE WARNING: "+or.apply(void 0,t);nr.warn(n)},dr=function(t){return"number"==typeof t&&(t!=t||t==Number.POSITIVE_INFINITY||t==Number.NEGATIVE_INFINITY)},yr="[MIN_NAME]",mr="[MAX_NAME]",gr=function(t,e){if(t===e)return 0;if(t===yr||e===mr)return-1;if(e===yr||t===mr)return 1;var n=Ir(t),r=Ir(e);return null!==n?null!==r?n-r==0?t.length-e.length:n-r:-1:null!==r?1:t<e?-1:1},vr=function(t,e){return t===e?0:t<e?-1:1},br=function(t,e){if(e&&t in e)return e[t];throw new Error("Missing required key ("+t+") in object: "+_n(e))},_r=function(t){if("object"!=typeof t||null===t)return _n(t);var e=[];for(var n in t)e.push(n);e.sort();for(var r="{",i=0;i<e.length;i++)0!==i&&(r+=","),r+=_n(e[i]),r+=":",r+=_r(t[e[i]]);return r+="}"},wr=function(t,e){var n=t.length;if(n<=e)return[t];for(var r=[],i=0;i<n;i+=e)i+e>n?r.push(t.substring(i,n)):r.push(t.substring(i,i+e));return r},Er=function(t,e){if(Array.isArray(t))for(var n=0;n<t.length;++n)e(n,t[n]);else Sn(t,function(t,n){return e(n,t)})},Tr=function(t){rn(!dr(t),"Invalid JSON number");var e,n,r,i,o,s,a;for(0===t?(n=0,r=0,e=1/t==-1/0?1:0):(e=t<0,(t=Math.abs(t))>=Math.pow(2,-1022)?(n=(i=Math.min(Math.floor(Math.log(t)/Math.LN2),1023))+1023,r=Math.round(t*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,r=Math.round(t/Math.pow(2,-1074)))),s=[],o=52;o;o-=1)s.push(r%2?1:0),r=Math.floor(r/2);for(o=11;o;o-=1)s.push(n%2?1:0),n=Math.floor(n/2);s.push(e?1:0),s.reverse(),a=s.join("");var u="";for(o=0;o<64;o+=8){var c=parseInt(a.substr(o,8),2).toString(16);1===c.length&&(c="0"+c),u+=c}return u.toLowerCase()},Sr=new RegExp("^-?\\d{1,10}$"),Ir=function(t){if(Sr.test(t)){var e=Number(t);if(e>=-2147483648&&e<=2147483647)return e}return null},Cr=function(t){try{t()}catch(t){setTimeout(function(){var e=t.stack||"";throw pr("Exception was thrown by user callback.",e),t},Math.floor(0))}},Nr=function(){return("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Dr=function(t,e){var n=setTimeout(t,e);return"object"==typeof n&&n.unref&&n.unref(),n},Ar=function(){function t(t,e){if(void 0===e){this.pieces_=t.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_=t,this.pieceNum_=e}return Object.defineProperty(t,"Empty",{get:function(){return new t("")},enumerable:!0,configurable:!0}),t.prototype.getFront=function(){return this.pieceNum_>=this.pieces_.length?null:this.pieces_[this.pieceNum_]},t.prototype.getLength=function(){return this.pieces_.length-this.pieceNum_},t.prototype.popFront=function(){var e=this.pieceNum_;return e<this.pieces_.length&&e++,new t(this.pieces_,e)},t.prototype.getBack=function(){return this.pieceNum_<this.pieces_.length?this.pieces_[this.pieces_.length-1]:null},t.prototype.toString=function(){for(var t="",e=this.pieceNum_;e<this.pieces_.length;e++)""!==this.pieces_[e]&&(t+="/"+this.pieces_[e]);return t||"/"},t.prototype.toUrlEncodedString=function(){for(var t="",e=this.pieceNum_;e<this.pieces_.length;e++)""!==this.pieces_[e]&&(t+="/"+encodeURIComponent(String(this.pieces_[e])));return t||"/"},t.prototype.slice=function(t){return void 0===t&&(t=0),this.pieces_.slice(this.pieceNum_+t)},t.prototype.parent=function(){if(this.pieceNum_>=this.pieces_.length)return null;for(var e=[],n=this.pieceNum_;n<this.pieces_.length-1;n++)e.push(this.pieces_[n]);return new t(e,0)},t.prototype.child=function(e){for(var n=[],r=this.pieceNum_;r<this.pieces_.length;r++)n.push(this.pieces_[r]);if(e instanceof t)for(r=e.pieceNum_;r<e.pieces_.length;r++)n.push(e.pieces_[r]);else{var i=e.split("/");for(r=0;r<i.length;r++)i[r].length>0&&n.push(i[r])}return new t(n,0)},t.prototype.isEmpty=function(){return this.pieceNum_>=this.pieces_.length},t.relativePath=function(e,n){var r=e.getFront(),i=n.getFront();if(null===r)return n;if(r===i)return t.relativePath(e.popFront(),n.popFront());throw new Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+e+")")},t.comparePaths=function(t,e){for(var n=t.slice(),r=e.slice(),i=0;i<n.length&&i<r.length;i++){var o=gr(n[i],r[i]);if(0!==o)return o}return n.length===r.length?0:n.length<r.length?-1:1},t.prototype.equals=function(t){if(this.getLength()!==t.getLength())return!1;for(var e=this.pieceNum_,n=t.pieceNum_;e<=this.pieces_.length;e++,n++)if(this.pieces_[e]!==t.pieces_[n])return!1;return!0},t.prototype.contains=function(t){var e=this.pieceNum_,n=t.pieceNum_;if(this.getLength()>t.getLength())return!1;for(;e<this.pieces_.length;){if(this.pieces_[e]!==t.pieces_[n])return!1;++e,++n}return!0},t}(),kr=function(){function t(t,e){this.errorPrefix_=e,this.parts_=t.slice(),this.byteLength_=Math.max(1,this.parts_.length);for(var n=0;n<this.parts_.length;n++)this.byteLength_+=qn(this.parts_[n]);this.checkValid_()}return Object.defineProperty(t,"MAX_PATH_DEPTH",{get:function(){return 32},enumerable:!0,configurable:!0}),Object.defineProperty(t,"MAX_PATH_LENGTH_BYTES",{get:function(){return 768},enumerable:!0,configurable:!0}),t.prototype.push=function(t){this.parts_.length>0&&(this.byteLength_+=1),this.parts_.push(t),this.byteLength_+=qn(t),this.checkValid_()},t.prototype.pop=function(){var t=this.parts_.pop();this.byteLength_-=qn(t),this.parts_.length>0&&(this.byteLength_-=1)},t.prototype.checkValid_=function(){if(this.byteLength_>t.MAX_PATH_LENGTH_BYTES)throw new Error(this.errorPrefix_+"has a key path longer than "+t.MAX_PATH_LENGTH_BYTES+" bytes ("+this.byteLength_+").");if(this.parts_.length>t.MAX_PATH_DEPTH)throw new Error(this.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+t.MAX_PATH_DEPTH+") or object contains a cycle "+this.toErrorString())},t.prototype.toErrorString=function(){return 0==this.parts_.length?"":"in property '"+this.parts_.join(".")+"'"},t}(),Rr="long_polling",Or=function(){function t(t,e,n,r,i){void 0===i&&(i=""),this.secure=e,this.namespace=n,this.webSocketOnly=r,this.persistenceKey=i,this.host=t.toLowerCase(),this.domain=this.host.substr(this.host.indexOf(".")+1),this.internalHost=tr.get("host:"+t)||this.host}return t.prototype.needsQueryParam=function(){return this.host!==this.internalHost||this.isCustomHost()},t.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},t.prototype.isDemoHost=function(){return"firebaseio-demo.com"===this.domain},t.prototype.isCustomHost=function(){return"firebaseio.com"!==this.domain&&"firebaseio-demo.com"!==this.domain},t.prototype.updateHost=function(t){t!==this.internalHost&&(this.internalHost=t,this.isCacheableHost()&&tr.set("host:"+this.host,this.internalHost))},t.prototype.connectionURL=function(t,e){var n;if(rn("string"==typeof t,"typeof type must == string"),rn("object"==typeof e,"typeof params must == object"),"websocket"===t)n=(this.secure?"wss://":"ws://")+this.internalHost+"/.ws?";else{if(t!==Rr)throw new Error("Unknown connection type: "+t);n=(this.secure?"https://":"http://")+this.internalHost+"/.lp?"}this.needsQueryParam()&&(e.ns=this.namespace);var r=[];return Sn(e,function(t,e){r.push(t+"="+e)}),n+r.join("&")},t.prototype.toString=function(){var t=this.toURLString();return this.persistenceKey&&(t+="<"+this.persistenceKey+">"),t},t.prototype.toURLString=function(){return(this.secure?"https://":"http://")+this.host},t}();var Pr,Lr,Mr,xr,Fr,Ur=function(t){var e=qr(t),n=e.subdomain;"firebase"===e.domain&&fr(e.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),n&&"undefined"!=n||"localhost"===e.domain||fr("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),e.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&pr("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");var r="ws"===e.scheme||"wss"===e.scheme;return{repoInfo:new Or(e.host,e.secure,n,r),path:new Ar(e.pathString)}},qr=function(t){var e="",n="",r="",i="",o=!0,s="https",a=443;if("string"==typeof t){var u=t.indexOf("//");u>=0&&(s=t.substring(0,u-1),t=t.substring(u+2));var c=t.indexOf("/");-1===c&&(c=t.length);var h=t.indexOf("?");-1===h&&(h=t.length),e=t.substring(0,Math.min(c,h)),c<h&&(i=function(t){for(var e="",n=t.split("/"),r=0;r<n.length;r++)if(n[r].length>0){var i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(t){}e+="/"+i}return e}(t.substring(c,h)));var l=function(t){var e={};"?"===t.charAt(0)&&(t=t.substring(1));for(var n=0,r=t.split("&");n<r.length;n++){var i=r[n];if(0!==i.length){var o=i.split("=");2===o.length?e[decodeURIComponent(o[0])]=decodeURIComponent(o[1]):pr("Invalid query segment '"+i+"' in query '"+t+"'")}}return e}(t.substring(Math.min(t.length,h)));(u=e.indexOf(":"))>=0?(o="https"===s||"wss"===s,a=parseInt(e.substring(u+1),10)):u=t.length;var f=e.split(".");3===f.length?(n=f[1],r=f[0].toLowerCase()):2===f.length?n=f[0]:"localhost"===f[0].slice(0,u).toLowerCase()&&(n="localhost"),""===r&&"ns"in l&&(r=l.ns)}return{host:e,port:a,domain:n,subdomain:r,secure:o,scheme:s,pathString:i}},Br=/[\[\].#$\/\u0000-\u001F\u007F]/,Vr=/[\[\].#$\u0000-\u001F\u007F]/,Wr=function(t){return"string"==typeof t&&0!==t.length&&!Br.test(t)},jr=function(t){return"string"==typeof t&&0!==t.length&&!Vr.test(t)},Kr=function(t){return null===t||"string"==typeof t||"number"==typeof t&&!dr(t)||t&&"object"==typeof t&&En(t,".sv")},Qr=function(t,e,n,r,i){i&&void 0===n||Hr(xn(t,e,i),n,r)},Hr=function(t,e,n){var r=n instanceof Ar?new kr(n,t):n;if(void 0===e)throw new Error(t+"contains undefined "+r.toErrorString());if("function"==typeof e)throw new Error(t+"contains a function "+r.toErrorString()+" with contents = "+e.toString());if(dr(e))throw new Error(t+"contains "+e.toString()+" "+r.toErrorString());if("string"==typeof e&&e.length>10485760/3&&qn(e)>10485760)throw new Error(t+"contains a string greater than 10485760 utf8 bytes "+r.toErrorString()+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){var i=!1,o=!1;if(Sn(e,function(e,n){if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(o=!0,!Wr(e)))throw new Error(t+" contains an invalid key ("+e+") "+r.toErrorString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');r.push(e),Hr(t,n,r),r.pop()}),i&&o)throw new Error(t+' contains ".value" child '+r.toErrorString()+" in addition to actual children.")}},Gr=function(t,e,n,r,i){if(!i||void 0!==n){var o=xn(t,e,i);if(!n||"object"!=typeof n||Array.isArray(n))throw new Error(o+" must be an object containing the children to replace.");var s=[];Sn(n,function(t,e){var n=new Ar(t);if(Hr(o,e,r.child(n)),".priority"===n.getBack()&&!Kr(e))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).");s.push(n)}),function(t,e){var n,r;for(n=0;n<e.length;n++)for(var i=(r=e[n]).slice(),o=0;o<i.length;o++)if(".priority"===i[o]&&o===i.length-1);else if(!Wr(i[o]))throw new Error(t+"contains an invalid key ("+i[o]+") in path "+r.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');e.sort(Ar.comparePaths);var s=null;for(n=0;n<e.length;n++){if(r=e[n],null!==s&&s.contains(r))throw new Error(t+"contains a path "+s.toString()+" that is ancestor of another path "+r.toString());s=r}}(o,s)}},zr=function(t,e,n,r){if(!r||void 0!==n){if(dr(n))throw new Error(xn(t,e,r)+"is "+n.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!Kr(n))throw new Error(xn(t,e,r)+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},Yr=function(t,e,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(xn(t,e,r)+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}},Xr=function(t,e,n,r){if(!(r&&void 0===n||Wr(n)))throw new Error(xn(t,e,r)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},Jr=function(t,e,n,r){if(!(r&&void 0===n||jr(n)))throw new Error(xn(t,e,r)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},$r=function(t,e){if(".info"===e.getFront())throw new Error(t+" failed = Can't modify data under /.info/")},Zr=function(t,e,n){var r=n.path.toString();if("string"!=typeof n.repoInfo.host||0===n.repoInfo.host.length||!Wr(n.repoInfo.namespace)&&"localhost"!==n.repoInfo.host.split(":")[0]||0!==r.length&&!function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),jr(t)}(r))throw new Error(xn(t,e,!1)+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')},ti=function(){function t(t,e){this.repo_=t,this.path_=e}return t.prototype.cancel=function(t){Mn("OnDisconnect.cancel",0,1,arguments.length),Fn("OnDisconnect.cancel",1,t,!0);var e=new fn;return this.repo_.onDisconnectCancel(this.path_,e.wrapCallback(t)),e.promise},t.prototype.remove=function(t){Mn("OnDisconnect.remove",0,1,arguments.length),$r("OnDisconnect.remove",this.path_),Fn("OnDisconnect.remove",1,t,!0);var e=new fn;return this.repo_.onDisconnectSet(this.path_,null,e.wrapCallback(t)),e.promise},t.prototype.set=function(t,e){Mn("OnDisconnect.set",1,2,arguments.length),$r("OnDisconnect.set",this.path_),Qr("OnDisconnect.set",1,t,this.path_,!1),Fn("OnDisconnect.set",2,e,!0);var n=new fn;return this.repo_.onDisconnectSet(this.path_,t,n.wrapCallback(e)),n.promise},t.prototype.setWithPriority=function(t,e,n){Mn("OnDisconnect.setWithPriority",2,3,arguments.length),$r("OnDisconnect.setWithPriority",this.path_),Qr("OnDisconnect.setWithPriority",1,t,this.path_,!1),zr("OnDisconnect.setWithPriority",2,e,!1),Fn("OnDisconnect.setWithPriority",3,n,!0);var r=new fn;return this.repo_.onDisconnectSetWithPriority(this.path_,t,e,r.wrapCallback(n)),r.promise},t.prototype.update=function(t,e){if(Mn("OnDisconnect.update",1,2,arguments.length),$r("OnDisconnect.update",this.path_),Array.isArray(t)){for(var n={},r=0;r<t.length;++r)n[""+r]=t[r];t=n,pr("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.")}Gr("OnDisconnect.update",1,t,this.path_,!1),Fn("OnDisconnect.update",2,e,!0);var i=new fn;return this.repo_.onDisconnectUpdate(this.path_,t,i.wrapCallback(e)),i.promise},t}(),ei=function(){function t(t,e){this.committed=t,this.snapshot=e}return t.prototype.toJSON=function(){return Mn("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}},t}(),ni=(Pr="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Lr=0,Mr=[],function(t){var e,n=t===Lr;Lr=t;var r=new Array(8);for(e=7;e>=0;e--)r[e]=Pr.charAt(t%64),t=Math.floor(t/64);rn(0===t,"Cannot push at time == 0");var i=r.join("");if(n){for(e=11;e>=0&&63===Mr[e];e--)Mr[e]=0;Mr[e]++}else for(e=0;e<12;e++)Mr[e]=Math.floor(64*Math.random());for(e=0;e<12;e++)i+=Pr.charAt(Mr[e]);return rn(20===i.length,"nextPushId: Length should be 20."),i}),ri=function(){function t(t,e){this.name=t,this.node=e}return t.Wrap=function(e,n){return new t(e,n)},t}(),ii=function(){function t(){}return t.prototype.getCompare=function(){return this.compare.bind(this)},t.prototype.indexedValueChanged=function(t,e){var n=new ri(yr,t),r=new ri(yr,e);return 0!==this.compare(n,r)},t.prototype.minPost=function(){return ri.MIN},t}(),oi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Xe(e,t),Object.defineProperty(e,"__EMPTY_NODE",{get:function(){return xr},set:function(t){xr=t},enumerable:!0,configurable:!0}),e.prototype.compare=function(t,e){return gr(t.name,e.name)},e.prototype.isDefinedOn=function(t){throw on("KeyIndex.isDefinedOn not expected to be called.")},e.prototype.indexedValueChanged=function(t,e){return!1},e.prototype.minPost=function(){return ri.MIN},e.prototype.maxPost=function(){return new ri(mr,xr)},e.prototype.makePost=function(t,e){return rn("string"==typeof t,"KeyIndex indexValue must always be a string."),new ri(t,xr)},e.prototype.toString=function(){return".key"},e}(ii),si=new oi;var ai,ui,ci,hi=function(t){return"number"==typeof t?"number:"+Tr(t):"string:"+t},li=function(t){if(t.isLeafNode()){var e=t.val();rn("string"==typeof e||"number"==typeof e||"object"==typeof e&&En(e,".sv"),"Priority must be a string or number.")}else rn(t===Fr||t.isEmpty(),"priority of unexpected type.");rn(t===Fr||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")},fi=function(){function t(e,n){void 0===n&&(n=t.__childrenNodeConstructor.EMPTY_NODE),this.value_=e,this.priorityNode_=n,this.lazyHash_=null,rn(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),li(this.priorityNode_)}return Object.defineProperty(t,"__childrenNodeConstructor",{get:function(){return ai},set:function(t){ai=t},enumerable:!0,configurable:!0}),t.prototype.isLeafNode=function(){return!0},t.prototype.getPriority=function(){return this.priorityNode_},t.prototype.updatePriority=function(e){return new t(this.value_,e)},t.prototype.getImmediateChild=function(e){return".priority"===e?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE},t.prototype.getChild=function(e){return e.isEmpty()?this:".priority"===e.getFront()?this.priorityNode_:t.__childrenNodeConstructor.EMPTY_NODE},t.prototype.hasChild=function(){return!1},t.prototype.getPredecessorChildName=function(t,e){return null},t.prototype.updateImmediateChild=function(e,n){return".priority"===e?this.updatePriority(n):n.isEmpty()&&".priority"!==e?this:t.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,n).updatePriority(this.priorityNode_)},t.prototype.updateChild=function(e,n){var r=e.getFront();return null===r?n:n.isEmpty()&&".priority"!==r?this:(rn(".priority"!==r||1===e.getLength(),".priority must be the last token in a path"),this.updateImmediateChild(r,t.__childrenNodeConstructor.EMPTY_NODE.updateChild(e.popFront(),n)))},t.prototype.isEmpty=function(){return!1},t.prototype.numChildren=function(){return 0},t.prototype.forEachChild=function(t,e){return!1},t.prototype.val=function(t){return t&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()},t.prototype.hash=function(){if(null===this.lazyHash_){var t="";this.priorityNode_.isEmpty()||(t+="priority:"+hi(this.priorityNode_.val())+":");var e=typeof this.value_;t+=e+":",t+="number"===e?Tr(this.value_):this.value_,this.lazyHash_=ir(t)}return this.lazyHash_},t.prototype.getValue=function(){return this.value_},t.prototype.compareTo=function(e){return e===t.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof t.__childrenNodeConstructor?-1:(rn(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))},t.prototype.compareToLeafNode_=function(e){var n=typeof e.value_,r=typeof this.value_,i=t.VALUE_TYPE_ORDER.indexOf(n),o=t.VALUE_TYPE_ORDER.indexOf(r);return rn(i>=0,"Unknown leaf type: "+n),rn(o>=0,"Unknown leaf type: "+r),i===o?"object"===r?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:o-i},t.prototype.withIndex=function(){return this},t.prototype.isIndexed=function(){return!0},t.prototype.equals=function(t){if(t===this)return!0;if(t.isLeafNode()){var e=t;return this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}return!1},t.VALUE_TYPE_ORDER=["object","boolean","number","string"],t}();var pi,di,yi=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Xe(e,t),e.prototype.compare=function(t,e){var n=t.node.getPriority(),r=e.node.getPriority(),i=n.compareTo(r);return 0===i?gr(t.name,e.name):i},e.prototype.isDefinedOn=function(t){return!t.getPriority().isEmpty()},e.prototype.indexedValueChanged=function(t,e){return!t.getPriority().equals(e.getPriority())},e.prototype.minPost=function(){return ri.MIN},e.prototype.maxPost=function(){return new ri(mr,new fi("[PRIORITY-POST]",ci))},e.prototype.makePost=function(t,e){var n=ui(t);return new ri(e,new fi("[PRIORITY-POST]",n))},e.prototype.toString=function(){return".priority"},e}(ii)),mi=function(){function t(t,e,n,r,i){void 0===i&&(i=null),this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];for(var o=1;!t.isEmpty();)if(t=t,o=e?n(t.key,e):1,r&&(o*=-1),o<0)t=this.isReverse_?t.left:t.right;else{if(0===o){this.nodeStack_.push(t);break}this.nodeStack_.push(t),t=this.isReverse_?t.right:t.left}}return t.prototype.getNext=function(){if(0===this.nodeStack_.length)return null;var t,e=this.nodeStack_.pop();if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t},t.prototype.hasNext=function(){return this.nodeStack_.length>0},t.prototype.peek=function(){if(0===this.nodeStack_.length)return null;var t=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value}},t}(),gi=function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:bi.EMPTY_NODE,this.right=null!=o?o:bi.EMPTY_NODE}return t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},t.prototype.count=function(){return this.left.count()+1+this.right.count()},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min_=function(){return this.left.isEmpty()?this:this.left.min_()},t.prototype.minKey=function(){return this.min_().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r,i;return(i=(r=n(t,(i=this).key))<0?i.copy(null,null,null,i.left.insert(t,e,n),null):0===r?i.copy(null,e,null,null,null):i.copy(null,null,null,null,i.right.insert(t,e,n))).fixUp_()},t.prototype.removeMin_=function(){if(this.left.isEmpty())return bi.EMPTY_NODE;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_()},t.prototype.remove=function(t,e){var n,r;if(e(t,(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(t,e),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===e(t,n.key)){if(n.right.isEmpty())return bi.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(t,e))}return n.fixUp_()},t.prototype.isRed_=function(){return this.color},t.prototype.fixUp_=function(){var t=this;return t.right.isRed_()&&!t.left.isRed_()&&(t=t.rotateLeft_()),t.left.isRed_()&&t.left.left.isRed_()&&(t=t.rotateRight_()),t.left.isRed_()&&t.right.isRed_()&&(t=t.colorFlip_()),t},t.prototype.moveRedLeft_=function(){var t=this.colorFlip_();return t.right.left.isRed_()&&(t=(t=(t=t.copy(null,null,null,null,t.right.rotateRight_())).rotateLeft_()).colorFlip_()),t},t.prototype.moveRedRight_=function(){var t=this.colorFlip_();return t.left.left.isRed_()&&(t=(t=t.rotateRight_()).colorFlip_()),t},t.prototype.rotateLeft_=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight_=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip_=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth_=function(){var t=this.check_();return Math.pow(2,t)<=this.count()+1},t.prototype.check_=function(){var t;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((t=this.left.check_())!==this.right.check_())throw new Error("Black depths differ");return t+(this.isRed_()?0:1)},t.RED=!0,t.BLACK=!1,t}(),vi=function(){function t(){}return t.prototype.copy=function(t,e,n,r,i){return this},t.prototype.insert=function(t,e,n){return new gi(t,e,null)},t.prototype.remove=function(t,e){return this},t.prototype.count=function(){return 0},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.check_=function(){return 0},t.prototype.isRed_=function(){return!1},t}(),bi=function(){function t(e,n){void 0===n&&(n=t.EMPTY_NODE),this.comparator_=e,this.root_=n}return t.prototype.insert=function(e,n){return new t(this.comparator_,this.root_.insert(e,n,this.comparator_).copy(null,null,gi.BLACK,null,null))},t.prototype.remove=function(e){return new t(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,gi.BLACK,null,null))},t.prototype.get=function(t){for(var e,n=this.root_;!n.isEmpty();){if(0===(e=this.comparator_(t,n.key)))return n.value;e<0?n=n.left:e>0&&(n=n.right)}return null},t.prototype.getPredecessorKey=function(t){for(var e,n=this.root_,r=null;!n.isEmpty();){if(0===(e=this.comparator_(t,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}e<0?n=n.left:e>0&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")},t.prototype.isEmpty=function(){return this.root_.isEmpty()},t.prototype.count=function(){return this.root_.count()},t.prototype.minKey=function(){return this.root_.minKey()},t.prototype.maxKey=function(){return this.root_.maxKey()},t.prototype.inorderTraversal=function(t){return this.root_.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.root_.reverseTraversal(t)},t.prototype.getIterator=function(t){return new mi(this.root_,null,this.comparator_,!1,t)},t.prototype.getIteratorFrom=function(t,e){return new mi(this.root_,t,this.comparator_,!1,e)},t.prototype.getReverseIteratorFrom=function(t,e){return new mi(this.root_,t,this.comparator_,!0,e)},t.prototype.getReverseIterator=function(t){return new mi(this.root_,null,this.comparator_,!0,t)},t.EMPTY_NODE=new vi,t}(),_i=Math.log(2),wi=function(){function t(t){var e;this.count=(e=t+1,parseInt(Math.log(e)/_i,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=t+1&r}return t.prototype.nextBitIsOne=function(){var t=!(this.bits_&1<<this.current_);return this.current_--,t},t}(),Ei=function(t,e,n,r){t.sort(e);var i=function(e,r){var o,s,a=r-e;if(0==a)return null;if(1==a)return o=t[e],s=n?n(o):o,new gi(s,o.node,gi.BLACK,null,null);var u=parseInt(a/2,10)+e,c=i(e,u),h=i(u+1,r);return o=t[u],s=n?n(o):o,new gi(s,o.node,gi.BLACK,c,h)},o=function(e){for(var r=null,o=null,s=t.length,a=function(e,r){var o=s-e,a=s;s-=e;var c=i(o+1,a),h=t[o],l=n?n(h):h;u(new gi(l,h.node,r,null,c))},u=function(t){r?(r.left=t,r=t):(o=t,r=t)},c=0;c<e.count;++c){var h=e.nextBitIsOne(),l=Math.pow(2,e.count-(c+1));h?a(l,gi.BLACK):(a(l,gi.BLACK),a(l,gi.RED))}return o}(new wi(t.length));return new bi(r||e,o)},Ti={},Si=function(){function t(t,e){this.indexes_=t,this.indexSet_=e}return Object.defineProperty(t,"Default",{get:function(){return rn(Ti&&yi,"ChildrenNode.ts has not been loaded"),pi=pi||new t({".priority":Ti},{".priority":yi})},enumerable:!0,configurable:!0}),t.prototype.get=function(t){var e=Tn(this.indexes_,t);if(!e)throw new Error("No index defined for "+t);return e===Ti?null:e},t.prototype.hasIndex=function(t){return En(this.indexSet_,t.toString())},t.prototype.addIndex=function(e,n){rn(e!==si,"KeyIndex always exists and isn't meant to be added to the IndexMap.");for(var r,i=[],o=!1,s=n.getIterator(ri.Wrap),a=s.getNext();a;)o=o||e.isDefinedOn(a.node),i.push(a),a=s.getNext();r=o?Ei(i,e.getCompare()):Ti;var u=e.toString(),c=In(this.indexSet_);c[u]=e;var h=In(this.indexes_);return h[u]=r,new t(h,c)},t.prototype.addToIndexes=function(e,n){var r=this;return new t(Dn(this.indexes_,function(t,i){var o=Tn(r.indexSet_,i);if(rn(o,"Missing index implementation for "+i),t===Ti){if(o.isDefinedOn(e.node)){for(var s=[],a=n.getIterator(ri.Wrap),u=a.getNext();u;)u.name!=e.name&&s.push(u),u=a.getNext();return s.push(e),Ei(s,o.getCompare())}return Ti}var c=n.get(e.name),h=t;return c&&(h=h.remove(new ri(e.name,c))),h.insert(e,e.node)}),this.indexSet_)},t.prototype.removeFromIndexes=function(e,n){return new t(Dn(this.indexes_,function(t){if(t===Ti)return t;var r=n.get(e.name);return r?t.remove(new ri(e.name,r)):t}),this.indexSet_)},t}();function Ii(t,e){return gr(t.name,e.name)}function Ci(t,e){return gr(t,e)}var Ni=function(){function t(t,e,n){this.children_=t,this.priorityNode_=e,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&li(this.priorityNode_),this.children_.isEmpty()&&rn(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}return Object.defineProperty(t,"EMPTY_NODE",{get:function(){return di||(di=new t(new bi(Ci),null,Si.Default))},enumerable:!0,configurable:!0}),t.prototype.isLeafNode=function(){return!1},t.prototype.getPriority=function(){return this.priorityNode_||di},t.prototype.updatePriority=function(e){return this.children_.isEmpty()?this:new t(this.children_,e,this.indexMap_)},t.prototype.getImmediateChild=function(t){if(".priority"===t)return this.getPriority();var e=this.children_.get(t);return null===e?di:e},t.prototype.getChild=function(t){var e=t.getFront();return null===e?this:this.getImmediateChild(e).getChild(t.popFront())},t.prototype.hasChild=function(t){return null!==this.children_.get(t)},t.prototype.updateImmediateChild=function(e,n){if(rn(n,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(n);var r=new ri(e,n),i=void 0,o=void 0;return n.isEmpty()?(i=this.children_.remove(e),o=this.indexMap_.removeFromIndexes(r,this.children_)):(i=this.children_.insert(e,n),o=this.indexMap_.addToIndexes(r,this.children_)),new t(i,i.isEmpty()?di:this.priorityNode_,o)},t.prototype.updateChild=function(t,e){var n=t.getFront();if(null===n)return e;rn(".priority"!==t.getFront()||1===t.getLength(),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(t.popFront(),e);return this.updateImmediateChild(n,r)},t.prototype.isEmpty=function(){return this.children_.isEmpty()},t.prototype.numChildren=function(){return this.children_.count()},t.prototype.val=function(e){if(this.isEmpty())return null;var n={},r=0,i=0,o=!0;if(this.forEachChild(yi,function(s,a){n[s]=a.val(e),r++,o&&t.INTEGER_REGEXP_.test(s)?i=Math.max(i,Number(s)):o=!1}),!e&&o&&i<2*r){var s=[];for(var a in n)s[a]=n[a];return s}return e&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n},t.prototype.hash=function(){if(null===this.lazyHash_){var t="";this.getPriority().isEmpty()||(t+="priority:"+hi(this.getPriority().val())+":"),this.forEachChild(yi,function(e,n){var r=n.hash();""!==r&&(t+=":"+e+":"+r)}),this.lazyHash_=""===t?"":ir(t)}return this.lazyHash_},t.prototype.getPredecessorChildName=function(t,e,n){var r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new ri(t,e));return i?i.name:null}return this.children_.getPredecessorKey(t)},t.prototype.getFirstChildName=function(t){var e=this.resolveIndex_(t);if(e){var n=e.minKey();return n&&n.name}return this.children_.minKey()},t.prototype.getFirstChild=function(t){var e=this.getFirstChildName(t);return e?new ri(e,this.children_.get(e)):null},t.prototype.getLastChildName=function(t){var e=this.resolveIndex_(t);if(e){var n=e.maxKey();return n&&n.name}return this.children_.maxKey()},t.prototype.getLastChild=function(t){var e=this.getLastChildName(t);return e?new ri(e,this.children_.get(e)):null},t.prototype.forEachChild=function(t,e){var n=this.resolveIndex_(t);return n?n.inorderTraversal(function(t){return e(t.name,t.node)}):this.children_.inorderTraversal(e)},t.prototype.getIterator=function(t){return this.getIteratorFrom(t.minPost(),t)},t.prototype.getIteratorFrom=function(t,e){var n=this.resolveIndex_(e);if(n)return n.getIteratorFrom(t,function(t){return t});for(var r=this.children_.getIteratorFrom(t.name,ri.Wrap),i=r.peek();null!=i&&e.compare(i,t)<0;)r.getNext(),i=r.peek();return r},t.prototype.getReverseIterator=function(t){return this.getReverseIteratorFrom(t.maxPost(),t)},t.prototype.getReverseIteratorFrom=function(t,e){var n=this.resolveIndex_(e);if(n)return n.getReverseIteratorFrom(t,function(t){return t});for(var r=this.children_.getReverseIteratorFrom(t.name,ri.Wrap),i=r.peek();null!=i&&e.compare(i,t)>0;)r.getNext(),i=r.peek();return r},t.prototype.compareTo=function(t){return this.isEmpty()?t.isEmpty()?0:-1:t.isLeafNode()||t.isEmpty()?1:t===Di?-1:0},t.prototype.withIndex=function(e){if(e===si||this.indexMap_.hasIndex(e))return this;var n=this.indexMap_.addIndex(e,this.children_);return new t(this.children_,this.priorityNode_,n)},t.prototype.isIndexed=function(t){return t===si||this.indexMap_.hasIndex(t)},t.prototype.equals=function(t){if(t===this)return!0;if(t.isLeafNode())return!1;var e=t;if(this.getPriority().equals(e.getPriority())){if(this.children_.count()===e.children_.count()){for(var n=this.getIterator(yi),r=e.getIterator(yi),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},t.prototype.resolveIndex_=function(t){return t===si?null:this.indexMap_.get(t.toString())},t.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/,t}(),Di=new(function(t){function e(){return t.call(this,new bi(Ci),Ni.EMPTY_NODE,Si.Default)||this}return Xe(e,t),e.prototype.compareTo=function(t){return t===this?0:1},e.prototype.equals=function(t){return t===this},e.prototype.getPriority=function(){return this},e.prototype.getImmediateChild=function(t){return Ni.EMPTY_NODE},e.prototype.isEmpty=function(){return!1},e}(Ni));Object.defineProperties(ri,{MIN:{value:new ri(yr,Ni.EMPTY_NODE)},MAX:{value:new ri(mr,Di)}}),oi.__EMPTY_NODE=Ni.EMPTY_NODE,fi.__childrenNodeConstructor=Ni,Fr=Di,function(t){ci=t}(Di);var Ai=!0;function ki(t,e){if(void 0===e&&(e=null),null===t)return Ni.EMPTY_NODE;if("object"==typeof t&&".priority"in t&&(e=t[".priority"]),rn(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"==typeof t&&".value"in t&&null!==t[".value"]&&(t=t[".value"]),"object"!=typeof t||".sv"in t)return new fi(t,ki(e));if(t instanceof Array||!Ai){var n=Ni.EMPTY_NODE,r=t;return Sn(r,function(t,e){if(En(r,t)&&"."!==t.substring(0,1)){var i=ki(e);!i.isLeafNode()&&i.isEmpty()||(n=n.updateImmediateChild(t,i))}}),n.updatePriority(ki(e))}var i=[],o=!1,s=t;if(Sn(s,function(t,e){if("string"!=typeof t||"."!==t.substring(0,1)){var n=ki(s[t]);n.isEmpty()||(o=o||!n.getPriority().isEmpty(),i.push(new ri(t,n)))}}),0==i.length)return Ni.EMPTY_NODE;var a=Ei(i,Ii,function(t){return t.name},Ci);if(o){var u=Ei(i,yi.getCompare());return new Ni(a,ki(e),new Si({".priority":u},{".priority":yi}))}return new Ni(a,ki(e),Si.Default)}!function(t){ui=t}(ki);var Ri,Oi,Pi=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Xe(e,t),e.prototype.compare=function(t,e){var n=t.node.compareTo(e.node);return 0===n?gr(t.name,e.name):n},e.prototype.isDefinedOn=function(t){return!0},e.prototype.indexedValueChanged=function(t,e){return!t.equals(e)},e.prototype.minPost=function(){return ri.MIN},e.prototype.maxPost=function(){return ri.MAX},e.prototype.makePost=function(t,e){var n=ki(t);return new ri(e,n)},e.prototype.toString=function(){return".value"},e}(ii)),Li=function(t){function e(e){var n=t.call(this)||this;return n.indexPath_=e,rn(!e.isEmpty()&&".priority"!==e.getFront(),"Can't create PathIndex with empty path or .priority key"),n}return Xe(e,t),e.prototype.extractChild=function(t){return t.getChild(this.indexPath_)},e.prototype.isDefinedOn=function(t){return!t.getChild(this.indexPath_).isEmpty()},e.prototype.compare=function(t,e){var n=this.extractChild(t.node),r=this.extractChild(e.node),i=n.compareTo(r);return 0===i?gr(t.name,e.name):i},e.prototype.makePost=function(t,e){var n=ki(t),r=Ni.EMPTY_NODE.updateChild(this.indexPath_,n);return new ri(e,r)},e.prototype.maxPost=function(){var t=Ni.EMPTY_NODE.updateChild(this.indexPath_,Di);return new ri(mr,t)},e.prototype.toString=function(){return this.indexPath_.slice().join("/")},e}(ii),Mi=function(){function t(t,e,n){this.node_=t,this.ref_=e,this.index_=n}return t.prototype.val=function(){return Mn("DataSnapshot.val",0,0,arguments.length),this.node_.val()},t.prototype.exportVal=function(){return Mn("DataSnapshot.exportVal",0,0,arguments.length),this.node_.val(!0)},t.prototype.toJSON=function(){return Mn("DataSnapshot.toJSON",0,1,arguments.length),this.exportVal()},t.prototype.exists=function(){return Mn("DataSnapshot.exists",0,0,arguments.length),!this.node_.isEmpty()},t.prototype.child=function(e){Mn("DataSnapshot.child",0,1,arguments.length),e=String(e),Jr("DataSnapshot.child",1,e,!1);var n=new Ar(e),r=this.ref_.child(n);return new t(this.node_.getChild(n),r,yi)},t.prototype.hasChild=function(t){Mn("DataSnapshot.hasChild",1,1,arguments.length),Jr("DataSnapshot.hasChild",1,t,!1);var e=new Ar(t);return!this.node_.getChild(e).isEmpty()},t.prototype.getPriority=function(){return Mn("DataSnapshot.getPriority",0,0,arguments.length),this.node_.getPriority().val()},t.prototype.forEach=function(e){var n=this;return Mn("DataSnapshot.forEach",1,1,arguments.length),Fn("DataSnapshot.forEach",1,e,!1),!this.node_.isLeafNode()&&!!this.node_.forEachChild(this.index_,function(r,i){return e(new t(i,n.ref_.child(r),yi))})},t.prototype.hasChildren=function(){return Mn("DataSnapshot.hasChildren",0,0,arguments.length),!this.node_.isLeafNode()&&!this.node_.isEmpty()},Object.defineProperty(t.prototype,"key",{get:function(){return this.ref_.getKey()},enumerable:!0,configurable:!0}),t.prototype.numChildren=function(){return Mn("DataSnapshot.numChildren",0,0,arguments.length),this.node_.numChildren()},t.prototype.getRef=function(){return Mn("DataSnapshot.ref",0,0,arguments.length),this.ref_},Object.defineProperty(t.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),t}(),xi=function(){function t(t,e,n,r){this.eventType=t,this.eventRegistration=e,this.snapshot=n,this.prevName=r}return t.prototype.getPath=function(){var t=this.snapshot.getRef();return"value"===this.eventType?t.path:t.getParent().path},t.prototype.getEventType=function(){return this.eventType},t.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},t.prototype.toString=function(){return this.getPath().toString()+":"+this.eventType+":"+_n(this.snapshot.exportVal())},t}(),Fi=function(){function t(t,e,n){this.eventRegistration=t,this.error=e,this.path=n}return t.prototype.getPath=function(){return this.path},t.prototype.getEventType=function(){return"cancel"},t.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},t.prototype.toString=function(){return this.path.toString()+":cancel"},t}(),Ui=function(){function t(t,e,n){this.callback_=t,this.cancelCallback_=e,this.context_=n}return t.prototype.respondsTo=function(t){return"value"===t},t.prototype.createEvent=function(t,e){var n=e.getQueryParams().getIndex();return new xi("value",this,new Mi(t.snapshotNode,e.getRef(),n))},t.prototype.getEventRunner=function(t){var e=this.context_;if("cancel"===t.getEventType()){rn(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(e,t.error)}}var r=this.callback_;return function(){r.call(e,t.snapshot)}},t.prototype.createCancelEvent=function(t,e){return this.cancelCallback_?new Fi(this,t,e):null},t.prototype.matches=function(e){return e instanceof t&&(!e.callback_||!this.callback_||e.callback_===this.callback_&&e.context_===this.context_)},t.prototype.hasAnyCallback=function(){return null!==this.callback_},t}(),qi=function(){function t(t,e,n){this.callbacks_=t,this.cancelCallback_=e,this.context_=n}return t.prototype.respondsTo=function(t){var e="children_added"===t?"child_added":t;return e="children_removed"===e?"child_removed":e,En(this.callbacks_,e)},t.prototype.createCancelEvent=function(t,e){return this.cancelCallback_?new Fi(this,t,e):null},t.prototype.createEvent=function(t,e){rn(null!=t.childName,"Child events should have a childName.");var n=e.getRef().child(t.childName),r=e.getQueryParams().getIndex();return new xi(t.type,this,new Mi(t.snapshotNode,n,r),t.prevName)},t.prototype.getEventRunner=function(t){var e=this.context_;if("cancel"===t.getEventType()){rn(this.cancelCallback_,"Raising a cancel event on a listener with no cancel callback");var n=this.cancelCallback_;return function(){n.call(e,t.error)}}var r=this.callbacks_[t.eventType];return function(){r.call(e,t.snapshot,t.prevName)}},t.prototype.matches=function(e){if(e instanceof t){if(!this.callbacks_||!e.callbacks_)return!0;if(this.context_===e.context_){var n=Nn(e.callbacks_);if(n===Nn(this.callbacks_)){if(1===n){var r=kn(e.callbacks_),i=kn(this.callbacks_);return!(i!==r||e.callbacks_[r]&&this.callbacks_[i]&&e.callbacks_[r]!==this.callbacks_[i])}return function(t,e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&!e(n,t[n]))return!1;return!0}(this.callbacks_,function(t,n){return e.callbacks_[t]===n})}}}return!1},t.prototype.hasAnyCallback=function(){return null!==this.callbacks_},t}(),Bi=function(){function t(t,e,n,r){this.repo=t,this.path=e,this.queryParams_=n,this.orderByCalled_=r}return Object.defineProperty(t,"__referenceConstructor",{get:function(){return rn(Ri,"Reference.ts has not been loaded"),Ri},set:function(t){Ri=t},enumerable:!0,configurable:!0}),t.validateQueryEndpoints_=function(t){var e=null,n=null;if(t.hasStart()&&(e=t.getIndexStartValue()),t.hasEnd()&&(n=t.getIndexEndValue()),t.getIndex()===si){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(t.hasStart()){if(t.getIndexStartName()!=yr)throw new Error(r);if("string"!=typeof e)throw new Error(i)}if(t.hasEnd()){if(t.getIndexEndName()!=mr)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(t.getIndex()===yi){if(null!=e&&!Kr(e)||null!=n&&!Kr(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(rn(t.getIndex()instanceof Li||t.getIndex()===Pi,"unknown index type."),null!=e&&"object"==typeof e||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), endAt(), or equalTo() cannot be an object.")},t.validateLimit_=function(t){if(t.hasStart()&&t.hasEnd()&&t.hasLimit()&&!t.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.")},t.prototype.validateNoPreviousOrderByCall_=function(t){if(!0===this.orderByCalled_)throw new Error(t+": You can't combine multiple orderBy calls.")},t.prototype.getQueryParams=function(){return this.queryParams_},t.prototype.getRef=function(){return Mn("Query.ref",0,0,arguments.length),new t.__referenceConstructor(this.repo,this.path)},t.prototype.on=function(e,n,r,i){Mn("Query.on",2,4,arguments.length),Yr("Query.on",1,e,!1),Fn("Query.on",2,n,!1);var o=t.getCancelAndContextArgs_("Query.on",r,i);if("value"===e)this.onValueEvent(n,o.cancel,o.context);else{var s={};s[e]=n,this.onChildEvent(s,o.cancel,o.context)}return n},t.prototype.onValueEvent=function(t,e,n){var r=new Ui(t,e||null,n||null);this.repo.addEventCallbackForQuery(this,r)},t.prototype.onChildEvent=function(t,e,n){var r=new qi(t,e,n);this.repo.addEventCallbackForQuery(this,r)},t.prototype.off=function(t,e,n){Mn("Query.off",0,3,arguments.length),Yr("Query.off",1,t,!0),Fn("Query.off",2,e,!0),Un("Query.off",3,n,!0);var r=null,i=null;"value"===t?r=new Ui(e||null,null,n||null):t&&(e&&((i={})[t]=e),r=new qi(i,null,n||null));this.repo.removeEventCallbackForQuery(this,r)},t.prototype.once=function(e,n,r,i){var o=this;Mn("Query.once",1,4,arguments.length),Yr("Query.once",1,e,!1),Fn("Query.once",2,n,!0);var s=t.getCancelAndContextArgs_("Query.once",r,i),a=!0,u=new fn;u.promise.catch(function(){});var c=function(t){a&&(a=!1,o.off(e,c),n&&n.bind(s.context)(t),u.resolve(t))};return this.on(e,c,function(t){o.off(e,c),s.cancel&&s.cancel.bind(s.context)(t),u.reject(t)}),u.promise},t.prototype.limitToFirst=function(e){if(Mn("Query.limitToFirst",1,1,arguments.length),"number"!=typeof e||Math.floor(e)!==e||e<=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 t(this.repo,this.path,this.queryParams_.limitToFirst(e),this.orderByCalled_)},t.prototype.limitToLast=function(e){if(Mn("Query.limitToLast",1,1,arguments.length),"number"!=typeof e||Math.floor(e)!==e||e<=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 t(this.repo,this.path,this.queryParams_.limitToLast(e),this.orderByCalled_)},t.prototype.orderByChild=function(e){if(Mn("Query.orderByChild",1,1,arguments.length),"$key"===e)throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.');if("$priority"===e)throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.');if("$value"===e)throw new Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.');Jr("Query.orderByChild",1,e,!1),this.validateNoPreviousOrderByCall_("Query.orderByChild");var n=new Ar(e);if(n.isEmpty())throw new Error("Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.");var r=new Li(n),i=this.queryParams_.orderBy(r);return t.validateQueryEndpoints_(i),new t(this.repo,this.path,i,!0)},t.prototype.orderByKey=function(){Mn("Query.orderByKey",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByKey");var e=this.queryParams_.orderBy(si);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.orderByPriority=function(){Mn("Query.orderByPriority",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByPriority");var e=this.queryParams_.orderBy(yi);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.orderByValue=function(){Mn("Query.orderByValue",0,0,arguments.length),this.validateNoPreviousOrderByCall_("Query.orderByValue");var e=this.queryParams_.orderBy(Pi);return t.validateQueryEndpoints_(e),new t(this.repo,this.path,e,!0)},t.prototype.startAt=function(e,n){void 0===e&&(e=null),Mn("Query.startAt",0,2,arguments.length),Qr("Query.startAt",1,e,this.path,!0),Xr("Query.startAt",2,n,!0);var r=this.queryParams_.startAt(e,n);if(t.validateLimit_(r),t.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===e&&(e=null,n=null),new t(this.repo,this.path,r,this.orderByCalled_)},t.prototype.endAt=function(e,n){void 0===e&&(e=null),Mn("Query.endAt",0,2,arguments.length),Qr("Query.endAt",1,e,this.path,!0),Xr("Query.endAt",2,n,!0);var r=this.queryParams_.endAt(e,n);if(t.validateLimit_(r),t.validateQueryEndpoints_(r),this.queryParams_.hasEnd())throw new Error("Query.endAt: Ending point was already set (by another call to endAt or equalTo).");return new t(this.repo,this.path,r,this.orderByCalled_)},t.prototype.equalTo=function(t,e){if(Mn("Query.equalTo",1,2,arguments.length),Qr("Query.equalTo",1,t,this.path,!1),Xr("Query.equalTo",2,e,!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(t,e).endAt(t,e)},t.prototype.toString=function(){return Mn("Query.toString",0,0,arguments.length),this.repo.toString()+this.path.toUrlEncodedString()},t.prototype.toJSON=function(){return Mn("Query.toJSON",0,1,arguments.length),this.toString()},t.prototype.queryObject=function(){return this.queryParams_.getQueryObject()},t.prototype.queryIdentifier=function(){var t=this.queryObject(),e=_r(t);return"{}"===e?"default":e},t.prototype.isEqual=function(e){if(Mn("Query.isEqual",1,1,arguments.length),!(e instanceof t)){throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}var n=this.repo===e.repo,r=this.path.equals(e.path),i=this.queryIdentifier()===e.queryIdentifier();return n&&r&&i},t.getCancelAndContextArgs_=function(t,e,n){var r={cancel:null,context:null};if(e&&n)r.cancel=e,Fn(t,3,r.cancel,!0),r.context=n,Un(t,4,r.context,!0);else if(e)if("object"==typeof e&&null!==e)r.context=e;else{if("function"!=typeof e)throw new Error(xn(t,3,!0)+" must either be a cancel callback or a context object.");r.cancel=e}return r},Object.defineProperty(t.prototype,"ref",{get:function(){return this.getRef()},enumerable:!0,configurable:!0}),t}(),Vi=function(){function t(){this.set={}}return t.prototype.add=function(t,e){this.set[t]=null===e||e},t.prototype.contains=function(t){return En(this.set,t)},t.prototype.get=function(t){return this.contains(t)?this.set[t]:void 0},t.prototype.remove=function(t){delete this.set[t]},t.prototype.clear=function(){this.set={}},t.prototype.isEmpty=function(){return Cn(this.set)},t.prototype.count=function(){return Nn(this.set)},t.prototype.each=function(t){Sn(this.set,function(e,n){return t(e,n)})},t.prototype.keys=function(){var t=[];return Sn(this.set,function(e){t.push(e)}),t},t}(),Wi=function(){function t(){this.value_=null,this.children_=null}return t.prototype.find=function(t){if(null!=this.value_)return this.value_.getChild(t);if(t.isEmpty()||null==this.children_)return null;var e=t.getFront();return t=t.popFront(),this.children_.contains(e)?this.children_.get(e).find(t):null},t.prototype.remember=function(e,n){if(e.isEmpty())this.value_=n,this.children_=null;else if(null!==this.value_)this.value_=this.value_.updateChild(e,n);else{null==this.children_&&(this.children_=new Vi);var r=e.getFront();this.children_.contains(r)||this.children_.add(r,new t);var i=this.children_.get(r);e=e.popFront(),i.remember(e,n)}},t.prototype.forget=function(t){if(t.isEmpty())return this.value_=null,this.children_=null,!0;if(null!==this.value_){if(this.value_.isLeafNode())return!1;var e=this.value_;this.value_=null;var n=this;return e.forEachChild(yi,function(t,e){n.remember(new Ar(t),e)}),this.forget(t)}if(null!==this.children_){var r=t.getFront();if(t=t.popFront(),this.children_.contains(r))this.children_.get(r).forget(t)&&this.children_.remove(r);return!!this.children_.isEmpty()&&(this.children_=null,!0)}return!0},t.prototype.forEachTree=function(t,e){null!==this.value_?e(t,this.value_):this.forEachChild(function(n,r){var i=new Ar(t.toString()+"/"+n);r.forEachTree(i,e)})},t.prototype.forEachChild=function(t){null!==this.children_&&this.children_.each(function(e,n){t(e,n)})},t}(),ji=function(t,e){return t&&"object"==typeof t?(rn(".sv"in t,"Unexpected leaf node or priority contents"),e[t[".sv"]]):t},Ki=function(t,e){var n,r=t.getPriority().val(),i=ji(r,e);if(t.isLeafNode()){var o=t,s=ji(o.getValue(),e);return s!==o.getValue()||i!==o.getPriority().val()?new fi(s,ki(i)):t}var a=t;return n=a,i!==a.getPriority().val()&&(n=n.updatePriority(new fi(i))),a.forEachChild(yi,function(t,r){var i=Ki(r,e);i!==r&&(n=n.updateImmediateChild(t,i))}),n};!function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(Oi||(Oi={}));var Qi,Hi,Gi=function(){function t(t,e,n,r){this.fromUser=t,this.fromServer=e,this.queryId=n,this.tagged=r,rn(!r||e,"Tagged queries must be from server.")}return t.User=new t(!0,!1,null,!1),t.Server=new t(!1,!0,null,!1),t.forServerTaggedQuery=function(e){return new t(!1,!0,e,!0)},t}(),zi=function(){function t(t,e,n){this.path=t,this.affectedTree=e,this.revert=n,this.type=Oi.ACK_USER_WRITE,this.source=Gi.User}return t.prototype.operationForChild=function(e){if(this.path.isEmpty()){if(null!=this.affectedTree.value)return rn(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var n=this.affectedTree.subtree(new Ar(e));return new t(Ar.Empty,n,this.revert)}return rn(this.path.getFront()===e,"operationForChild called for unrelated child."),new t(this.path.popFront(),this.affectedTree,this.revert)},t}(),Yi=function(){return Qi||(Qi=new bi(vr)),Qi},Xi=function(){function t(t,e){void 0===e&&(e=Yi()),this.value=t,this.children=e}return t.fromObject=function(e){var n=t.Empty;return Sn(e,function(t,e){n=n.set(new Ar(t),e)}),n},t.prototype.isEmpty=function(){return null===this.value&&this.children.isEmpty()},t.prototype.findRootMostMatchingPathAndValue=function(t,e){if(null!=this.value&&e(this.value))return{path:Ar.Empty,value:this.value};if(t.isEmpty())return null;var n=t.getFront(),r=this.children.get(n);if(null!==r){var i=r.findRootMostMatchingPathAndValue(t.popFront(),e);return null!=i?{path:new Ar(n).child(i.path),value:i.value}:null}return null},t.prototype.findRootMostValueAndPath=function(t){return this.findRootMostMatchingPathAndValue(t,function(){return!0})},t.prototype.subtree=function(e){if(e.isEmpty())return this;var n=e.getFront(),r=this.children.get(n);return null!==r?r.subtree(e.popFront()):t.Empty},t.prototype.set=function(e,n){if(e.isEmpty())return new t(n,this.children);var r=e.getFront(),i=(this.children.get(r)||t.Empty).set(e.popFront(),n),o=this.children.insert(r,i);return new t(this.value,o)},t.prototype.remove=function(e){if(e.isEmpty())return this.children.isEmpty()?t.Empty:new t(null,this.children);var n=e.getFront(),r=this.children.get(n);if(r){var i=r.remove(e.popFront()),o=void 0;return o=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&o.isEmpty()?t.Empty:new t(this.value,o)}return this},t.prototype.get=function(t){if(t.isEmpty())return this.value;var e=t.getFront(),n=this.children.get(e);return n?n.get(t.popFront()):null},t.prototype.setTree=function(e,n){if(e.isEmpty())return n;var r=e.getFront(),i=(this.children.get(r)||t.Empty).setTree(e.popFront(),n),o=void 0;return o=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new t(this.value,o)},t.prototype.fold=function(t){return this.fold_(Ar.Empty,t)},t.prototype.fold_=function(t,e){var n={};return this.children.inorderTraversal(function(r,i){n[r]=i.fold_(t.child(r),e)}),e(t,this.value,n)},t.prototype.findOnPath=function(t,e){return this.findOnPath_(t,Ar.Empty,e)},t.prototype.findOnPath_=function(t,e,n){var r=!!this.value&&n(e,this.value);if(r)return r;if(t.isEmpty())return null;var i=t.getFront(),o=this.children.get(i);return o?o.findOnPath_(t.popFront(),e.child(i),n):null},t.prototype.foreachOnPath=function(t,e){return this.foreachOnPath_(t,Ar.Empty,e)},t.prototype.foreachOnPath_=function(e,n,r){if(e.isEmpty())return this;this.value&&r(n,this.value);var i=e.getFront(),o=this.children.get(i);return o?o.foreachOnPath_(e.popFront(),n.child(i),r):t.Empty},t.prototype.foreach=function(t){this.foreach_(Ar.Empty,t)},t.prototype.foreach_=function(t,e){this.children.inorderTraversal(function(n,r){r.foreach_(t.child(n),e)}),this.value&&e(t,this.value)},t.prototype.foreachChild=function(t){this.children.inorderTraversal(function(e,n){n.value&&t(e,n.value)})},t.Empty=new t(null),t}(),Ji=function(){function t(t,e){this.source=t,this.path=e,this.type=Oi.LISTEN_COMPLETE}return t.prototype.operationForChild=function(e){return this.path.isEmpty()?new t(this.source,Ar.Empty):new t(this.source,this.path.popFront())},t}(),$i=function(){function t(t,e,n){this.source=t,this.path=e,this.snap=n,this.type=Oi.OVERWRITE}return t.prototype.operationForChild=function(e){return this.path.isEmpty()?new t(this.source,Ar.Empty,this.snap.getImmediateChild(e)):new t(this.source,this.path.popFront(),this.snap)},t}(),Zi=function(){function t(t,e,n){this.source=t,this.path=e,this.children=n,this.type=Oi.MERGE}return t.prototype.operationForChild=function(e){if(this.path.isEmpty()){var n=this.children.subtree(new Ar(e));return n.isEmpty()?null:n.value?new $i(this.source,Ar.Empty,n.value):new t(this.source,Ar.Empty,n)}return rn(this.path.getFront()===e,"Can't get a merge for a child not on the path of the operation"),new t(this.source,this.path.popFront(),this.children)},t.prototype.toString=function(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"},t}(),to=function(){function t(t,e,n){this.node_=t,this.fullyInitialized_=e,this.filtered_=n}return t.prototype.isFullyInitialized=function(){return this.fullyInitialized_},t.prototype.isFiltered=function(){return this.filtered_},t.prototype.isCompleteForPath=function(t){if(t.isEmpty())return this.isFullyInitialized()&&!this.filtered_;var e=t.getFront();return this.isCompleteForChild(e)},t.prototype.isCompleteForChild=function(t){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(t)},t.prototype.getNode=function(){return this.node_},t}(),eo=function(){function t(t,e){this.eventCache_=t,this.serverCache_=e}return t.prototype.updateEventSnap=function(e,n,r){return new t(new to(e,n,r),this.serverCache_)},t.prototype.updateServerSnap=function(e,n,r){return new t(this.eventCache_,new to(e,n,r))},t.prototype.getEventCache=function(){return this.eventCache_},t.prototype.getCompleteEventSnap=function(){return this.eventCache_.isFullyInitialized()?this.eventCache_.getNode():null},t.prototype.getServerCache=function(){return this.serverCache_},t.prototype.getCompleteServerSnap=function(){return this.serverCache_.isFullyInitialized()?this.serverCache_.getNode():null},t.Empty=new t(new to(Ni.EMPTY_NODE,!1,!1),new to(Ni.EMPTY_NODE,!1,!1)),t}(),no=function(){function t(t,e,n,r,i){this.type=t,this.snapshotNode=e,this.childName=n,this.oldSnap=r,this.prevName=i}return t.valueChange=function(e){return new t(t.VALUE,e)},t.childAddedChange=function(e,n){return new t(t.CHILD_ADDED,n,e)},t.childRemovedChange=function(e,n){return new t(t.CHILD_REMOVED,n,e)},t.childChangedChange=function(e,n,r){return new t(t.CHILD_CHANGED,n,e,r)},t.childMovedChange=function(e,n){return new t(t.CHILD_MOVED,n,e)},t.CHILD_ADDED="child_added",t.CHILD_REMOVED="child_removed",t.CHILD_CHANGED="child_changed",t.CHILD_MOVED="child_moved",t.VALUE="value",t}(),ro=function(){function t(t){this.index_=t}return t.prototype.updateChild=function(t,e,n,r,i,o){rn(t.isIndexed(this.index_),"A node must be indexed if only a child is updated");var s=t.getImmediateChild(e);return s.getChild(r).equals(n.getChild(r))&&s.isEmpty()==n.isEmpty()?t:(null!=o&&(n.isEmpty()?t.hasChild(e)?o.trackChildChange(no.childRemovedChange(e,s)):rn(t.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):s.isEmpty()?o.trackChildChange(no.childAddedChange(e,n)):o.trackChildChange(no.childChangedChange(e,n,s))),t.isLeafNode()&&n.isEmpty()?t:t.updateImmediateChild(e,n).withIndex(this.index_))},t.prototype.updateFullNode=function(t,e,n){return null!=n&&(t.isLeafNode()||t.forEachChild(yi,function(t,r){e.hasChild(t)||n.trackChildChange(no.childRemovedChange(t,r))}),e.isLeafNode()||e.forEachChild(yi,function(e,r){if(t.hasChild(e)){var i=t.getImmediateChild(e);i.equals(r)||n.trackChildChange(no.childChangedChange(e,r,i))}else n.trackChildChange(no.childAddedChange(e,r))})),e.withIndex(this.index_)},t.prototype.updatePriority=function(t,e){return t.isEmpty()?Ni.EMPTY_NODE:t.updatePriority(e)},t.prototype.filtersNodes=function(){return!1},t.prototype.getIndexedFilter=function(){return this},t.prototype.getIndex=function(){return this.index_},t}(),io=function(){function t(){this.changeMap_={}}return t.prototype.trackChildChange=function(t){var e=t.type,n=t.childName;rn(e==no.CHILD_ADDED||e==no.CHILD_CHANGED||e==no.CHILD_REMOVED,"Only child changes supported for tracking"),rn(".priority"!==n,"Only non-priority child changes can be tracked.");var r=Tn(this.changeMap_,n);if(r){var i=r.type;if(e==no.CHILD_ADDED&&i==no.CHILD_REMOVED)this.changeMap_[n]=no.childChangedChange(n,t.snapshotNode,r.snapshotNode);else if(e==no.CHILD_REMOVED&&i==no.CHILD_ADDED)delete this.changeMap_[n];else if(e==no.CHILD_REMOVED&&i==no.CHILD_CHANGED)this.changeMap_[n]=no.childRemovedChange(n,r.oldSnap);else if(e==no.CHILD_CHANGED&&i==no.CHILD_ADDED)this.changeMap_[n]=no.childAddedChange(n,t.snapshotNode);else{if(e!=no.CHILD_CHANGED||i!=no.CHILD_CHANGED)throw on("Illegal combination of changes: "+t+" occurred after "+r);this.changeMap_[n]=no.childChangedChange(n,t.snapshotNode,r.oldSnap)}}else this.changeMap_[n]=t},t.prototype.getChanges=function(){return function(t){var e=[],n=0;for(var r in t)e[n++]=t[r];return e}(this.changeMap_)},t}(),oo=new(function(){function t(){}return t.prototype.getCompleteChild=function(t){return null},t.prototype.getChildAfterChild=function(t,e,n){return null},t}()),so=function(){function t(t,e,n){void 0===n&&(n=null),this.writes_=t,this.viewCache_=e,this.optCompleteServerCache_=n}return t.prototype.getCompleteChild=function(t){var e=this.viewCache_.getEventCache();if(e.isCompleteForChild(t))return e.getNode().getImmediateChild(t);var n=null!=this.optCompleteServerCache_?new to(this.optCompleteServerCache_,!0,!1):this.viewCache_.getServerCache();return this.writes_.calcCompleteChild(t,n)},t.prototype.getChildAfterChild=function(t,e,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:this.viewCache_.getCompleteServerSnap(),i=this.writes_.calcIndexedSlice(r,e,1,n,t);return 0===i.length?null:i[0]},t}(),ao=function(){return function(t,e){this.viewCache=t,this.changes=e}}(),uo=function(){function t(t){this.filter_=t}return t.prototype.assertIndexed=function(t){rn(t.getEventCache().getNode().isIndexed(this.filter_.getIndex()),"Event snap not indexed"),rn(t.getServerCache().getNode().isIndexed(this.filter_.getIndex()),"Server snap not indexed")},t.prototype.applyOperation=function(e,n,r,i){var o,s,a=new io;if(n.type===Oi.OVERWRITE){var u=n;u.source.fromUser?o=this.applyUserOverwrite_(e,u.path,u.snap,r,i,a):(rn(u.source.fromServer,"Unknown source."),s=u.source.tagged||e.getServerCache().isFiltered()&&!u.path.isEmpty(),o=this.applyServerOverwrite_(e,u.path,u.snap,r,i,s,a))}else if(n.type===Oi.MERGE){var c=n;c.source.fromUser?o=this.applyUserMerge_(e,c.path,c.children,r,i,a):(rn(c.source.fromServer,"Unknown source."),s=c.source.tagged||e.getServerCache().isFiltered(),o=this.applyServerMerge_(e,c.path,c.children,r,i,s,a))}else if(n.type===Oi.ACK_USER_WRITE){var h=n;o=h.revert?this.revertUserWrite_(e,h.path,r,i,a):this.ackUserWrite_(e,h.path,h.affectedTree,r,i,a)}else{if(n.type!==Oi.LISTEN_COMPLETE)throw on("Unknown operation type: "+n.type);o=this.listenComplete_(e,n.path,r,a)}var l=a.getChanges();return t.maybeAddValueEvent_(e,o,l),new ao(o,l)},t.maybeAddValueEvent_=function(t,e,n){var r=e.getEventCache();if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty(),o=t.getCompleteEventSnap();(n.length>0||!t.getEventCache().isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(no.valueChange(e.getCompleteEventSnap()))}},t.prototype.generateEventCacheAfterServerEvent_=function(t,e,n,r,i){var o=t.getEventCache();if(null!=n.shadowingWrite(e))return t;var s=void 0,a=void 0;if(e.isEmpty())if(rn(t.getServerCache().isFullyInitialized(),"If change path is empty, we must have complete server data"),t.getServerCache().isFiltered()){var u=t.getCompleteServerSnap(),c=u instanceof Ni?u:Ni.EMPTY_NODE,h=n.calcCompleteEventChildren(c);s=this.filter_.updateFullNode(t.getEventCache().getNode(),h,i)}else{var l=n.calcCompleteEventCache(t.getCompleteServerSnap());s=this.filter_.updateFullNode(t.getEventCache().getNode(),l,i)}else{var f=e.getFront();if(".priority"==f){rn(1==e.getLength(),"Can't have a priority with additional path components");var p=o.getNode();a=t.getServerCache().getNode();var d=n.calcEventCacheAfterServerOverwrite(e,p,a);s=null!=d?this.filter_.updatePriority(p,d):o.getNode()}else{var y=e.popFront(),m=void 0;if(o.isCompleteForChild(f)){a=t.getServerCache().getNode();var g=n.calcEventCacheAfterServerOverwrite(e,o.getNode(),a);m=null!=g?o.getNode().getImmediateChild(f).updateChild(y,g):o.getNode().getImmediateChild(f)}else m=n.calcCompleteChild(f,t.getServerCache());s=null!=m?this.filter_.updateChild(o.getNode(),f,m,y,r,i):o.getNode()}}return t.updateEventSnap(s,o.isFullyInitialized()||e.isEmpty(),this.filter_.filtersNodes())},t.prototype.applyServerOverwrite_=function(t,e,n,r,i,o,s){var a,u=t.getServerCache(),c=o?this.filter_:this.filter_.getIndexedFilter();if(e.isEmpty())a=c.updateFullNode(u.getNode(),n,null);else if(c.filtersNodes()&&!u.isFiltered()){var h=u.getNode().updateChild(e,n);a=c.updateFullNode(u.getNode(),h,null)}else{var l=e.getFront();if(!u.isCompleteForPath(e)&&e.getLength()>1)return t;var f=e.popFront(),p=u.getNode().getImmediateChild(l).updateChild(f,n);a=".priority"==l?c.updatePriority(u.getNode(),p):c.updateChild(u.getNode(),l,p,f,oo,null)}var d=t.updateServerSnap(a,u.isFullyInitialized()||e.isEmpty(),c.filtersNodes()),y=new so(r,d,i);return this.generateEventCacheAfterServerEvent_(d,e,r,y,s)},t.prototype.applyUserOverwrite_=function(t,e,n,r,i,o){var s,a,u=t.getEventCache(),c=new so(r,t,i);if(e.isEmpty())a=this.filter_.updateFullNode(t.getEventCache().getNode(),n,o),s=t.updateEventSnap(a,!0,this.filter_.filtersNodes());else{var h=e.getFront();if(".priority"===h)a=this.filter_.updatePriority(t.getEventCache().getNode(),n),s=t.updateEventSnap(a,u.isFullyInitialized(),u.isFiltered());else{var l=e.popFront(),f=u.getNode().getImmediateChild(h),p=void 0;if(l.isEmpty())p=n;else{var d=c.getCompleteChild(h);p=null!=d?".priority"===l.getBack()&&d.getChild(l.parent()).isEmpty()?d:d.updateChild(l,n):Ni.EMPTY_NODE}if(f.equals(p))s=t;else{var y=this.filter_.updateChild(u.getNode(),h,p,l,c,o);s=t.updateEventSnap(y,u.isFullyInitialized(),this.filter_.filtersNodes())}}}return s},t.cacheHasChild_=function(t,e){return t.getEventCache().isCompleteForChild(e)},t.prototype.applyUserMerge_=function(e,n,r,i,o,s){var a=this,u=e;return r.foreach(function(r,c){var h=n.child(r);t.cacheHasChild_(e,h.getFront())&&(u=a.applyUserOverwrite_(u,h,c,i,o,s))}),r.foreach(function(r,c){var h=n.child(r);t.cacheHasChild_(e,h.getFront())||(u=a.applyUserOverwrite_(u,h,c,i,o,s))}),u},t.prototype.applyMerge_=function(t,e){return e.foreach(function(e,n){t=t.updateChild(e,n)}),t},t.prototype.applyServerMerge_=function(t,e,n,r,i,o,s){var a=this;if(t.getServerCache().getNode().isEmpty()&&!t.getServerCache().isFullyInitialized())return t;var u,c=t;u=e.isEmpty()?n:Xi.Empty.setTree(e,n);var h=t.getServerCache().getNode();return u.children.inorderTraversal(function(e,n){if(h.hasChild(e)){var u=t.getServerCache().getNode().getImmediateChild(e),l=a.applyMerge_(u,n);c=a.applyServerOverwrite_(c,new Ar(e),l,r,i,o,s)}}),u.children.inorderTraversal(function(e,n){var u=!t.getServerCache().isCompleteForChild(e)&&null==n.value;if(!h.hasChild(e)&&!u){var l=t.getServerCache().getNode().getImmediateChild(e),f=a.applyMerge_(l,n);c=a.applyServerOverwrite_(c,new Ar(e),f,r,i,o,s)}}),c},t.prototype.ackUserWrite_=function(t,e,n,r,i,o){if(null!=r.shadowingWrite(e))return t;var s=t.getServerCache().isFiltered(),a=t.getServerCache();if(null!=n.value){if(e.isEmpty()&&a.isFullyInitialized()||a.isCompleteForPath(e))return this.applyServerOverwrite_(t,e,a.getNode().getChild(e),r,i,s,o);if(e.isEmpty()){var u=Xi.Empty;return a.getNode().forEachChild(si,function(t,e){u=u.set(new Ar(t),e)}),this.applyServerMerge_(t,e,u,r,i,s,o)}return t}var c=Xi.Empty;return n.foreach(function(t,n){var r=e.child(t);a.isCompleteForPath(r)&&(c=c.set(t,a.getNode().getChild(r)))}),this.applyServerMerge_(t,e,c,r,i,s,o)},t.prototype.listenComplete_=function(t,e,n,r){var i=t.getServerCache(),o=t.updateServerSnap(i.getNode(),i.isFullyInitialized()||e.isEmpty(),i.isFiltered());return this.generateEventCacheAfterServerEvent_(o,e,n,oo,r)},t.prototype.revertUserWrite_=function(t,e,n,r,i){var o;if(null!=n.shadowingWrite(e))return t;var s=new so(n,t,r),a=t.getEventCache().getNode(),u=void 0;if(e.isEmpty()||".priority"===e.getFront()){var c=void 0;if(t.getServerCache().isFullyInitialized())c=n.calcCompleteEventCache(t.getCompleteServerSnap());else{var h=t.getServerCache().getNode();rn(h instanceof Ni,"serverChildren would be complete if leaf node"),c=n.calcCompleteEventChildren(h)}c=c,u=this.filter_.updateFullNode(a,c,i)}else{var l=e.getFront(),f=n.calcCompleteChild(l,t.getServerCache());null==f&&t.getServerCache().isCompleteForChild(l)&&(f=a.getImmediateChild(l)),(u=null!=f?this.filter_.updateChild(a,l,f,e.popFront(),s,i):t.getEventCache().getNode().hasChild(l)?this.filter_.updateChild(a,l,Ni.EMPTY_NODE,e.popFront(),s,i):a).isEmpty()&&t.getServerCache().isFullyInitialized()&&(o=n.calcCompleteEventCache(t.getCompleteServerSnap())).isLeafNode()&&(u=this.filter_.updateFullNode(u,o,i))}return o=t.getServerCache().isFullyInitialized()||null!=n.shadowingWrite(Ar.Empty),t.updateEventSnap(u,o,this.filter_.filtersNodes())},t}(),co=function(){function t(t){this.query_=t,this.index_=this.query_.getQueryParams().getIndex()}return t.prototype.generateEventsForChanges=function(t,e,n){var r=this,i=[],o=[];return t.forEach(function(t){t.type===no.CHILD_CHANGED&&r.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&o.push(no.childMovedChange(t.childName,t.snapshotNode))}),this.generateEventsForType_(i,no.CHILD_REMOVED,t,n,e),this.generateEventsForType_(i,no.CHILD_ADDED,t,n,e),this.generateEventsForType_(i,no.CHILD_MOVED,o,n,e),this.generateEventsForType_(i,no.CHILD_CHANGED,t,n,e),this.generateEventsForType_(i,no.VALUE,t,n,e),i},t.prototype.generateEventsForType_=function(t,e,n,r,i){var o=this,s=n.filter(function(t){return t.type===e});s.sort(this.compareChanges_.bind(this)),s.forEach(function(e){var n=o.materializeSingleChange_(e,i);r.forEach(function(r){r.respondsTo(e.type)&&t.push(r.createEvent(n,o.query_))})})},t.prototype.materializeSingleChange_=function(t,e){return"value"===t.type||"child_removed"===t.type?t:(t.prevName=e.getPredecessorChildName(t.childName,t.snapshotNode,this.index_),t)},t.prototype.compareChanges_=function(t,e){if(null==t.childName||null==e.childName)throw on("Should only compare child_ events.");var n=new ri(t.childName,t.snapshotNode),r=new ri(e.childName,e.snapshotNode);return this.index_.compare(n,r)},t}(),ho=function(){function t(t,e){this.query_=t,this.eventRegistrations_=[];var n=this.query_.getQueryParams(),r=new ro(n.getIndex()),i=n.getNodeFilter();this.processor_=new uo(i);var o=e.getServerCache(),s=e.getEventCache(),a=r.updateFullNode(Ni.EMPTY_NODE,o.getNode(),null),u=i.updateFullNode(Ni.EMPTY_NODE,s.getNode(),null),c=new to(a,o.isFullyInitialized(),r.filtersNodes()),h=new to(u,s.isFullyInitialized(),i.filtersNodes());this.viewCache_=new eo(h,c),this.eventGenerator_=new co(this.query_)}return t.prototype.getQuery=function(){return this.query_},t.prototype.getServerCache=function(){return this.viewCache_.getServerCache().getNode()},t.prototype.getCompleteServerCache=function(t){var e=this.viewCache_.getCompleteServerSnap();return e&&(this.query_.getQueryParams().loadsAllData()||!t.isEmpty()&&!e.getImmediateChild(t.getFront()).isEmpty())?e.getChild(t):null},t.prototype.isEmpty=function(){return 0===this.eventRegistrations_.length},t.prototype.addEventRegistration=function(t){this.eventRegistrations_.push(t)},t.prototype.removeEventRegistration=function(t,e){var n=[];if(e){rn(null==t,"A cancel should cancel all event registrations.");var r=this.query_.path;this.eventRegistrations_.forEach(function(t){e=e;var i=t.createCancelEvent(e,r);i&&n.push(i)})}if(t){for(var i=[],o=0;o<this.eventRegistrations_.length;++o){var s=this.eventRegistrations_[o];if(s.matches(t)){if(t.hasAnyCallback()){i=i.concat(this.eventRegistrations_.slice(o+1));break}}else i.push(s)}this.eventRegistrations_=i}else this.eventRegistrations_=[];return n},t.prototype.applyOperation=function(t,e,n){t.type===Oi.MERGE&&null!==t.source.queryId&&(rn(this.viewCache_.getCompleteServerSnap(),"We should always have a full cache before handling merges"),rn(this.viewCache_.getCompleteEventSnap(),"Missing event cache, even though we have a server cache"));var r=this.viewCache_,i=this.processor_.applyOperation(r,t,e,n);return this.processor_.assertIndexed(i.viewCache),rn(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)},t.prototype.getInitialEvents=function(t){var e=this.viewCache_.getEventCache(),n=[];e.getNode().isLeafNode()||e.getNode().forEachChild(yi,function(t,e){n.push(no.childAddedChange(t,e))});return e.isFullyInitialized()&&n.push(no.valueChange(e.getNode())),this.generateEventsForChanges_(n,e.getNode(),t)},t.prototype.generateEventsForChanges_=function(t,e,n){var r=n?[n]:this.eventRegistrations_;return this.eventGenerator_.generateEventsForChanges(t,e,r)},t}(),lo=function(){function t(){this.views_={}}return Object.defineProperty(t,"__referenceConstructor",{get:function(){return rn(Hi,"Reference.ts has not been loaded"),Hi},set:function(t){rn(!Hi,"__referenceConstructor has already been defined"),Hi=t},enumerable:!0,configurable:!0}),t.prototype.isEmpty=function(){return Cn(this.views_)},t.prototype.applyOperation=function(t,e,n){var r=t.source.queryId;if(null!==r){var i=Tn(this.views_,r);return rn(null!=i,"SyncTree gave us an op for an invalid query."),i.applyOperation(t,e,n)}var o=[];return Sn(this.views_,function(r,i){o=o.concat(i.applyOperation(t,e,n))}),o},t.prototype.addEventRegistration=function(t,e,n,r,i){var o=t.queryIdentifier(),s=Tn(this.views_,o);if(!s){var a=n.calcCompleteEventCache(i?r:null),u=!1;a?u=!0:r instanceof Ni?(a=n.calcCompleteEventChildren(r),u=!1):(a=Ni.EMPTY_NODE,u=!1);var c=new eo(new to(a,u,!1),new to(r,i,!1));s=new ho(t,c),this.views_[o]=s}return s.addEventRegistration(e),s.getInitialEvents(e)},t.prototype.removeEventRegistration=function(e,n,r){var i=e.queryIdentifier(),o=[],s=[],a=this.hasCompleteView();if("default"===i){var u=this;Sn(this.views_,function(t,e){s=s.concat(e.removeEventRegistration(n,r)),e.isEmpty()&&(delete u.views_[t],e.getQuery().getQueryParams().loadsAllData()||o.push(e.getQuery()))})}else{var c=Tn(this.views_,i);c&&(s=s.concat(c.removeEventRegistration(n,r)),c.isEmpty()&&(delete this.views_[i],c.getQuery().getQueryParams().loadsAllData()||o.push(c.getQuery())))}return a&&!this.hasCompleteView()&&o.push(new t.__referenceConstructor(e.repo,e.path)),{removed:o,events:s}},t.prototype.getQueryViews=function(){var t=this;return Object.keys(this.views_).map(function(e){return t.views_[e]}).filter(function(t){return!t.getQuery().getQueryParams().loadsAllData()})},t.prototype.getCompleteServerCache=function(t){var e=null;return Sn(this.views_,function(n,r){e=e||r.getCompleteServerCache(t)}),e},t.prototype.viewForQuery=function(t){if(t.getQueryParams().loadsAllData())return this.getCompleteView();var e=t.queryIdentifier();return Tn(this.views_,e)},t.prototype.viewExistsForQuery=function(t){return null!=this.viewForQuery(t)},t.prototype.hasCompleteView=function(){return null!=this.getCompleteView()},t.prototype.getCompleteView=function(){var t,e,n;return(t=this.views_,(n=An(t,function(t){return t.getQuery().getQueryParams().loadsAllData()},e))&&t[n])||null},t}(),fo=function(){function t(t){this.writeTree_=t}return t.prototype.addWrite=function(e,n){if(e.isEmpty())return new t(new Xi(n));var r=this.writeTree_.findRootMostValueAndPath(e);if(null!=r){var i=r.path,o=r.value,s=Ar.relativePath(i,e);return o=o.updateChild(s,n),new t(this.writeTree_.set(i,o))}var a=new Xi(n);return new t(this.writeTree_.setTree(e,a))},t.prototype.addWrites=function(t,e){var n=this;return Sn(e,function(e,r){n=n.addWrite(t.child(e),r)}),n},t.prototype.removeWrite=function(e){return e.isEmpty()?t.Empty:new t(this.writeTree_.setTree(e,Xi.Empty))},t.prototype.hasCompleteWrite=function(t){return null!=this.getCompleteNode(t)},t.prototype.getCompleteNode=function(t){var e=this.writeTree_.findRootMostValueAndPath(t);return null!=e?this.writeTree_.get(e.path).getChild(Ar.relativePath(e.path,t)):null},t.prototype.getCompleteChildren=function(){var t=[],e=this.writeTree_.value;return null!=e?e.isLeafNode()||e.forEachChild(yi,function(e,n){t.push(new ri(e,n))}):this.writeTree_.children.inorderTraversal(function(e,n){null!=n.value&&t.push(new ri(e,n.value))}),t},t.prototype.childCompoundWrite=function(e){if(e.isEmpty())return this;var n=this.getCompleteNode(e);return new t(null!=n?new Xi(n):this.writeTree_.subtree(e))},t.prototype.isEmpty=function(){return this.writeTree_.isEmpty()},t.prototype.apply=function(e){return t.applySubtreeWrite_(Ar.Empty,this.writeTree_,e)},t.Empty=new t(new Xi(null)),t.applySubtreeWrite_=function(e,n,r){if(null!=n.value)return r.updateChild(e,n.value);var i=null;return n.children.inorderTraversal(function(n,o){".priority"===n?(rn(null!==o.value,"Priority writes must always be leaf nodes"),i=o.value):r=t.applySubtreeWrite_(e.child(n),o,r)}),r.getChild(e).isEmpty()||null===i||(r=r.updateChild(e.child(".priority"),i)),r},t}(),po=function(){function t(){this.visibleWrites_=fo.Empty,this.allWrites_=[],this.lastWriteId_=-1}return t.prototype.childWrites=function(t){return new yo(t,this)},t.prototype.addOverwrite=function(t,e,n,r){rn(n>this.lastWriteId_,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),this.allWrites_.push({path:t,snap:e,writeId:n,visible:r}),r&&(this.visibleWrites_=this.visibleWrites_.addWrite(t,e)),this.lastWriteId_=n},t.prototype.addMerge=function(t,e,n){rn(n>this.lastWriteId_,"Stacking an older merge on top of newer ones"),this.allWrites_.push({path:t,children:e,writeId:n,visible:!0}),this.visibleWrites_=this.visibleWrites_.addWrites(t,e),this.lastWriteId_=n},t.prototype.getWrite=function(t){for(var e=0;e<this.allWrites_.length;e++){var n=this.allWrites_[e];if(n.writeId===t)return n}return null},t.prototype.removeWrite=function(t){var e=this,n=this.allWrites_.findIndex(function(e){return e.writeId===t});rn(n>=0,"removeWrite called with nonexistent writeId.");var r=this.allWrites_[n];this.allWrites_.splice(n,1);for(var i=r.visible,o=!1,s=this.allWrites_.length-1;i&&s>=0;){var a=this.allWrites_[s];a.visible&&(s>=n&&this.recordContainsPath_(a,r.path)?i=!1:r.path.contains(a.path)&&(o=!0)),s--}if(i){if(o)return this.resetTree_(),!0;if(r.snap)this.visibleWrites_=this.visibleWrites_.removeWrite(r.path);else{var u=r.children;Sn(u,function(t){e.visibleWrites_=e.visibleWrites_.removeWrite(r.path.child(t))})}return!0}return!1},t.prototype.getCompleteWriteData=function(t){return this.visibleWrites_.getCompleteNode(t)},t.prototype.calcCompleteEventCache=function(e,n,r,i){if(r||i){var o=this.visibleWrites_.childCompoundWrite(e);if(!i&&o.isEmpty())return n;if(i||null!=n||o.hasCompleteWrite(Ar.Empty)){var s=t.layerTree_(this.allWrites_,function(t){return(t.visible||i)&&(!r||!~r.indexOf(t.writeId))&&(t.path.contains(e)||e.contains(t.path))},e);c=n||Ni.EMPTY_NODE;return s.apply(c)}return null}var a=this.visibleWrites_.getCompleteNode(e);if(null!=a)return a;var u=this.visibleWrites_.childCompoundWrite(e);if(u.isEmpty())return n;if(null!=n||u.hasCompleteWrite(Ar.Empty)){var c=n||Ni.EMPTY_NODE;return u.apply(c)}return null},t.prototype.calcCompleteEventChildren=function(t,e){var n=Ni.EMPTY_NODE,r=this.visibleWrites_.getCompleteNode(t);if(r)return r.isLeafNode()||r.forEachChild(yi,function(t,e){n=n.updateImmediateChild(t,e)}),n;if(e){var i=this.visibleWrites_.childCompoundWrite(t);return e.forEachChild(yi,function(t,e){var r=i.childCompoundWrite(new Ar(t)).apply(e);n=n.updateImmediateChild(t,r)}),i.getCompleteChildren().forEach(function(t){n=n.updateImmediateChild(t.name,t.node)}),n}return this.visibleWrites_.childCompoundWrite(t).getCompleteChildren().forEach(function(t){n=n.updateImmediateChild(t.name,t.node)}),n},t.prototype.calcEventCacheAfterServerOverwrite=function(t,e,n,r){rn(n||r,"Either existingEventSnap or existingServerSnap must exist");var i=t.child(e);if(this.visibleWrites_.hasCompleteWrite(i))return null;var o=this.visibleWrites_.childCompoundWrite(i);return o.isEmpty()?r.getChild(e):o.apply(r.getChild(e))},t.prototype.calcCompleteChild=function(t,e,n){var r=t.child(e),i=this.visibleWrites_.getCompleteNode(r);return null!=i?i:n.isCompleteForChild(e)?this.visibleWrites_.childCompoundWrite(r).apply(n.getNode().getImmediateChild(e)):null},t.prototype.shadowingWrite=function(t){return this.visibleWrites_.getCompleteNode(t)},t.prototype.calcIndexedSlice=function(t,e,n,r,i,o){var s,a=this.visibleWrites_.childCompoundWrite(t),u=a.getCompleteNode(Ar.Empty);if(null!=u)s=u;else{if(null==e)return[];s=a.apply(e)}if((s=s.withIndex(o)).isEmpty()||s.isLeafNode())return[];for(var c=[],h=o.getCompare(),l=i?s.getReverseIteratorFrom(n,o):s.getIteratorFrom(n,o),f=l.getNext();f&&c.length<r;)0!==h(f,n)&&c.push(f),f=l.getNext();return c},t.prototype.recordContainsPath_=function(t,e){return t.snap?t.path.contains(e):!!An(t.children,function(n,r){return t.path.child(r).contains(e)})},t.prototype.resetTree_=function(){this.visibleWrites_=t.layerTree_(this.allWrites_,t.DefaultFilter_,Ar.Empty),this.allWrites_.length>0?this.lastWriteId_=this.allWrites_[this.allWrites_.length-1].writeId:this.lastWriteId_=-1},t.DefaultFilter_=function(t){return t.visible},t.layerTree_=function(t,e,n){for(var r=fo.Empty,i=0;i<t.length;++i){var o=t[i];if(e(o)){var s=o.path,a=void 0;if(o.snap)n.contains(s)?(a=Ar.relativePath(n,s),r=r.addWrite(a,o.snap)):s.contains(n)&&(a=Ar.relativePath(s,n),r=r.addWrite(Ar.Empty,o.snap.getChild(a)));else{if(!o.children)throw on("WriteRecord should have .snap or .children");if(n.contains(s))a=Ar.relativePath(n,s),r=r.addWrites(a,o.children);else if(s.contains(n))if((a=Ar.relativePath(s,n)).isEmpty())r=r.addWrites(Ar.Empty,o.children);else{var u=Tn(o.children,a.getFront());if(u){var c=u.getChild(a.popFront());r=r.addWrite(Ar.Empty,c)}}}}}return r},t}(),yo=function(){function t(t,e){this.treePath_=t,this.writeTree_=e}return t.prototype.calcCompleteEventCache=function(t,e,n){return this.writeTree_.calcCompleteEventCache(this.treePath_,t,e,n)},t.prototype.calcCompleteEventChildren=function(t){return this.writeTree_.calcCompleteEventChildren(this.treePath_,t)},t.prototype.calcEventCacheAfterServerOverwrite=function(t,e,n){return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_,t,e,n)},t.prototype.shadowingWrite=function(t){return this.writeTree_.shadowingWrite(this.treePath_.child(t))},t.prototype.calcIndexedSlice=function(t,e,n,r,i){return this.writeTree_.calcIndexedSlice(this.treePath_,t,e,n,r,i)},t.prototype.calcCompleteChild=function(t,e){return this.writeTree_.calcCompleteChild(this.treePath_,t,e)},t.prototype.child=function(e){return new t(this.treePath_.child(e),this.writeTree_)},t}(),mo=function(){function t(t){this.listenProvider_=t,this.syncPointTree_=Xi.Empty,this.pendingWriteTree_=new po,this.tagToQueryMap_={},this.queryToTagMap_={}}return t.prototype.applyUserOverwrite=function(t,e,n,r){return this.pendingWriteTree_.addOverwrite(t,e,n,r),r?this.applyOperationToSyncPoints_(new $i(Gi.User,t,e)):[]},t.prototype.applyUserMerge=function(t,e,n){this.pendingWriteTree_.addMerge(t,e,n);var r=Xi.fromObject(e);return this.applyOperationToSyncPoints_(new Zi(Gi.User,t,r))},t.prototype.ackUserWrite=function(t,e){void 0===e&&(e=!1);var n=this.pendingWriteTree_.getWrite(t);if(this.pendingWriteTree_.removeWrite(t)){var r=Xi.Empty;return null!=n.snap?r=r.set(Ar.Empty,!0):Sn(n.children,function(t,e){r=r.set(new Ar(t),e)}),this.applyOperationToSyncPoints_(new zi(n.path,r,e))}return[]},t.prototype.applyServerOverwrite=function(t,e){return this.applyOperationToSyncPoints_(new $i(Gi.Server,t,e))},t.prototype.applyServerMerge=function(t,e){var n=Xi.fromObject(e);return this.applyOperationToSyncPoints_(new Zi(Gi.Server,t,n))},t.prototype.applyListenComplete=function(t){return this.applyOperationToSyncPoints_(new Ji(Gi.Server,t))},t.prototype.applyTaggedQueryOverwrite=function(e,n,r){var i=this.queryKeyForTag_(r);if(null!=i){var o=t.parseQueryKey_(i),s=o.path,a=o.queryId,u=Ar.relativePath(s,e),c=new $i(Gi.forServerTaggedQuery(a),u,n);return this.applyTaggedOperation_(s,c)}return[]},t.prototype.applyTaggedQueryMerge=function(e,n,r){var i=this.queryKeyForTag_(r);if(i){var o=t.parseQueryKey_(i),s=o.path,a=o.queryId,u=Ar.relativePath(s,e),c=Xi.fromObject(n),h=new Zi(Gi.forServerTaggedQuery(a),u,c);return this.applyTaggedOperation_(s,h)}return[]},t.prototype.applyTaggedListenComplete=function(e,n){var r=this.queryKeyForTag_(n);if(r){var i=t.parseQueryKey_(r),o=i.path,s=i.queryId,a=Ar.relativePath(o,e),u=new Ji(Gi.forServerTaggedQuery(s),a);return this.applyTaggedOperation_(o,u)}return[]},t.prototype.addEventRegistration=function(e,n){var r=e.path,i=null,o=!1;this.syncPointTree_.foreachOnPath(r,function(t,e){var n=Ar.relativePath(t,r);i=i||e.getCompleteServerCache(n),o=o||e.hasCompleteView()});var s,a=this.syncPointTree_.get(r);(a?(o=o||a.hasCompleteView(),i=i||a.getCompleteServerCache(Ar.Empty)):(a=new lo,this.syncPointTree_=this.syncPointTree_.set(r,a)),null!=i)?s=!0:(s=!1,i=Ni.EMPTY_NODE,this.syncPointTree_.subtree(r).foreachChild(function(t,e){var n=e.getCompleteServerCache(Ar.Empty);n&&(i=i.updateImmediateChild(t,n))}));var u=a.viewExistsForQuery(e);if(!u&&!e.getQueryParams().loadsAllData()){var c=t.makeQueryKey_(e);rn(!(c in this.queryToTagMap_),"View does not exist, but we have a tag");var h=t.getNextQueryTag_();this.queryToTagMap_[c]=h,this.tagToQueryMap_["_"+h]=c}var l=this.pendingWriteTree_.childWrites(r),f=a.addEventRegistration(e,n,l,i,s);if(!u&&!o){var p=a.viewForQuery(e);f=f.concat(this.setupListener_(e,p))}return f},t.prototype.removeEventRegistration=function(e,n,r){var i=this,o=e.path,s=this.syncPointTree_.get(o),a=[];if(s&&("default"===e.queryIdentifier()||s.viewExistsForQuery(e))){var u=s.removeEventRegistration(e,n,r);s.isEmpty()&&(this.syncPointTree_=this.syncPointTree_.remove(o));var c=u.removed;a=u.events;var h=-1!==c.findIndex(function(t){return t.getQueryParams().loadsAllData()}),l=this.syncPointTree_.findOnPath(o,function(t,e){return e.hasCompleteView()});if(h&&!l){var f=this.syncPointTree_.subtree(o);if(!f.isEmpty())for(var p=this.collectDistinctViewsForSubTree_(f),d=0;d<p.length;++d){var y=p[d],m=y.getQuery(),g=this.createListenerForView_(y);this.listenProvider_.startListening(t.queryForListening_(m),this.tagForQuery_(m),g.hashFn,g.onComplete)}}if(!l&&c.length>0&&!r)if(h){this.listenProvider_.stopListening(t.queryForListening_(e),null)}else c.forEach(function(e){var n=i.queryToTagMap_[t.makeQueryKey_(e)];i.listenProvider_.stopListening(t.queryForListening_(e),n)});this.removeTags_(c)}return a},t.prototype.calcCompleteEventCache=function(t,e){var n=this.pendingWriteTree_,r=this.syncPointTree_.findOnPath(t,function(e,n){var r=Ar.relativePath(e,t),i=n.getCompleteServerCache(r);if(i)return i});return n.calcCompleteEventCache(t,r,e,!0)},t.prototype.collectDistinctViewsForSubTree_=function(t){return t.fold(function(t,e,n){if(e&&e.hasCompleteView())return[e.getCompleteView()];var r=[];return e&&(r=e.getQueryViews()),Sn(n,function(t,e){r=r.concat(e)}),r})},t.prototype.removeTags_=function(e){for(var n=0;n<e.length;++n){var r=e[n];if(!r.getQueryParams().loadsAllData()){var i=t.makeQueryKey_(r),o=this.queryToTagMap_[i];delete this.queryToTagMap_[i],delete this.tagToQueryMap_["_"+o]}}},t.queryForListening_=function(t){return t.getQueryParams().loadsAllData()&&!t.getQueryParams().isDefault()?t.getRef():t},t.prototype.setupListener_=function(e,n){var r=e.path,i=this.tagForQuery_(e),o=this.createListenerForView_(n),s=this.listenProvider_.startListening(t.queryForListening_(e),i,o.hashFn,o.onComplete),a=this.syncPointTree_.subtree(r);if(i)rn(!a.value.hasCompleteView(),"If we're adding a query, it shouldn't be shadowed");else for(var u=a.fold(function(t,e,n){if(!t.isEmpty()&&e&&e.hasCompleteView())return[e.getCompleteView().getQuery()];var r=[];return e&&(r=r.concat(e.getQueryViews().map(function(t){return t.getQuery()}))),Sn(n,function(t,e){r=r.concat(e)}),r}),c=0;c<u.length;++c){var h=u[c];this.listenProvider_.stopListening(t.queryForListening_(h),this.tagForQuery_(h))}return s},t.prototype.createListenerForView_=function(t){var e=this,n=t.getQuery(),r=this.tagForQuery_(n);return{hashFn:function(){return(t.getServerCache()||Ni.EMPTY_NODE).hash()},onComplete:function(t){if("ok"===t)return r?e.applyTaggedListenComplete(n.path,r):e.applyListenComplete(n.path);var i=function(t,e){var n="Unknown Error";"too_big"===t?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"==t?n="Client doesn't have permission to access the desired data.":"unavailable"==t&&(n="The service is unavailable");var r=new Error(t+" at "+e.path.toString()+": "+n);return r.code=t.toUpperCase(),r}(t,n);return e.removeEventRegistration(n,null,i)}}},t.makeQueryKey_=function(t){return t.path.toString()+"$"+t.queryIdentifier()},t.parseQueryKey_=function(t){var e=t.indexOf("$");return rn(-1!==e&&e<t.length-1,"Bad queryKey."),{queryId:t.substr(e+1),path:new Ar(t.substr(0,e))}},t.prototype.queryKeyForTag_=function(t){return this.tagToQueryMap_["_"+t]},t.prototype.tagForQuery_=function(e){var n=t.makeQueryKey_(e);return Tn(this.queryToTagMap_,n)},t.getNextQueryTag_=function(){return t.nextQueryTag_++},t.prototype.applyTaggedOperation_=function(t,e){var n=this.syncPointTree_.get(t);rn(n,"Missing sync point for query tag that we're tracking");var r=this.pendingWriteTree_.childWrites(t);return n.applyOperation(e,r,null)},t.prototype.applyOperationToSyncPoints_=function(t){return this.applyOperationHelper_(t,this.syncPointTree_,null,this.pendingWriteTree_.childWrites(Ar.Empty))},t.prototype.applyOperationHelper_=function(t,e,n,r){if(t.path.isEmpty())return this.applyOperationDescendantsHelper_(t,e,n,r);var i=e.get(Ar.Empty);null==n&&null!=i&&(n=i.getCompleteServerCache(Ar.Empty));var o=[],s=t.path.getFront(),a=t.operationForChild(s),u=e.children.get(s);if(u&&a){var c=n?n.getImmediateChild(s):null,h=r.child(s);o=o.concat(this.applyOperationHelper_(a,u,c,h))}return i&&(o=o.concat(i.applyOperation(t,r,n))),o},t.prototype.applyOperationDescendantsHelper_=function(t,e,n,r){var i=this,o=e.get(Ar.Empty);null==n&&null!=o&&(n=o.getCompleteServerCache(Ar.Empty));var s=[];return e.children.inorderTraversal(function(e,o){var a=n?n.getImmediateChild(e):null,u=r.child(e),c=t.operationForChild(e);c&&(s=s.concat(i.applyOperationDescendantsHelper_(c,o,a,u)))}),o&&(s=s.concat(o.applyOperation(t,r,n))),s},t.nextQueryTag_=1,t}(),go=function(){function t(){this.rootNode_=Ni.EMPTY_NODE}return t.prototype.getNode=function(t){return this.rootNode_.getChild(t)},t.prototype.updateSnapshot=function(t,e){this.rootNode_=this.rootNode_.updateChild(t,e)},t}(),vo=function(){function t(t){this.app_=t}return t.prototype.getToken=function(t){return this.app_.INTERNAL.getToken(t).then(null,function(t){return t&&"auth/token-not-initialized"===t.code?(cr("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(t)})},t.prototype.addTokenChangeListener=function(t){this.app_.INTERNAL.addAuthTokenListener(t)},t.prototype.removeTokenChangeListener=function(t){this.app_.INTERNAL.removeAuthTokenListener(t)},t.prototype.notifyForInvalidToken=function(){var t='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?t+='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?t+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':t+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',pr(t)},t}(),bo=function(){function t(){this.counters_={}}return t.prototype.incrementCounter=function(t,e){void 0===e&&(e=1),En(this.counters_,t)||(this.counters_[t]=0),this.counters_[t]+=e},t.prototype.get=function(){return cn(this.counters_)},t}(),_o=function(){function t(){}return t.getCollection=function(t){var e=t.toString();return this.collections_[e]||(this.collections_[e]=new bo),this.collections_[e]},t.getOrCreateReporter=function(t,e){var n=t.toString();return this.reporters_[n]||(this.reporters_[n]=e()),this.reporters_[n]},t.collections_={},t.reporters_={},t}(),wo=function(){function t(t){this.collection_=t,this.last_=null}return t.prototype.get=function(){var t=this.collection_.get(),e=In(t);return this.last_&&Sn(this.last_,function(t,n){e[t]=e[t]-n}),this.last_=t,e},t}(),Eo=1e4,To=3e4,So=function(){function t(t,e){this.server_=e,this.statsToReport_={},this.statsListener_=new wo(t);var n=Eo+(To-Eo)*Math.random();Dr(this.reportStats_.bind(this),Math.floor(n))}return t.prototype.includeStat=function(t){this.statsToReport_[t]=!0},t.prototype.reportStats_=function(){var t=this,e=this.statsListener_.get(),n={},r=!1;Sn(e,function(e,i){i>0&&En(t.statsToReport_,e)&&(n[e]=i,r=!0)}),r&&this.server_.reportStats(n),Dr(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))},t}(),Io=function(){function t(){this.eventLists_=[],this.recursionDepth_=0}return t.prototype.queueEvents=function(t){for(var e=null,n=0;n<t.length;n++){var r=t[n],i=r.getPath();null===e||i.equals(e.getPath())||(this.eventLists_.push(e),e=null),null===e&&(e=new Co(i)),e.add(r)}e&&this.eventLists_.push(e)},t.prototype.raiseEventsAtPath=function(t,e){this.queueEvents(e),this.raiseQueuedEventsMatchingPredicate_(function(e){return e.equals(t)})},t.prototype.raiseEventsForChangedPath=function(t,e){this.queueEvents(e),this.raiseQueuedEventsMatchingPredicate_(function(e){return e.contains(t)||t.contains(e)})},t.prototype.raiseQueuedEventsMatchingPredicate_=function(t){this.recursionDepth_++;for(var e=!0,n=0;n<this.eventLists_.length;n++){var r=this.eventLists_[n];if(r)t(r.getPath())?(this.eventLists_[n].raise(),this.eventLists_[n]=null):e=!1}e&&(this.eventLists_=[]),this.recursionDepth_--},t}(),Co=function(){function t(t){this.path_=t,this.events_=[]}return t.prototype.add=function(t){this.events_.push(t)},t.prototype.raise=function(){for(var t=0;t<this.events_.length;t++){var e=this.events_[t];if(null!==e){this.events_[t]=null;var n=e.getEventRunner();sr&&cr("event: "+e.toString()),Cr(n)}}},t.prototype.getPath=function(){return this.path_},t}(),No=function(){function t(t){this.allowedEvents_=t,this.listeners_={},rn(Array.isArray(t)&&t.length>0,"Requires a non-empty array")}return t.prototype.trigger=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(Array.isArray(this.listeners_[t]))for(var r=this.listeners_[t].slice(),i=0;i<r.length;i++)r[i].callback.apply(r[i].context,e)},t.prototype.on=function(t,e,n){this.validateEventType_(t),this.listeners_[t]=this.listeners_[t]||[],this.listeners_[t].push({callback:e,context:n});var r=this.getInitialEvent(t);r&&e.apply(n,r)},t.prototype.off=function(t,e,n){this.validateEventType_(t);for(var r=this.listeners_[t]||[],i=0;i<r.length;i++)if(r[i].callback===e&&(!n||n===r[i].context))return void r.splice(i,1)},t.prototype.validateEventType_=function(t){rn(this.allowedEvents_.find(function(e){return e===t}),"Unknown event: "+t)},t}(),Do=function(t){function e(){var e,n,r=t.call(this,["visible"])||this;return"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(n="visibilitychange",e="hidden"):void 0!==document.mozHidden?(n="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(n="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(n="webkitvisibilitychange",e="webkitHidden")),r.visible_=!0,n&&document.addEventListener(n,function(){var t=!document[e];t!==r.visible_&&(r.visible_=t,r.trigger("visible",t))},!1),r}return Xe(e,t),e.getInstance=function(){return new e},e.prototype.getInitialEvent=function(t){return rn("visible"===t,"Unknown event type: "+t),[this.visible_]},e}(No),Ao=function(t){function e(){var e=t.call(this,["online"])||this;return e.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||pn()||(window.addEventListener("online",function(){e.online_||(e.online_=!0,e.trigger("online",!0))},!1),window.addEventListener("offline",function(){e.online_&&(e.online_=!1,e.trigger("online",!1))},!1)),e}return Xe(e,t),e.getInstance=function(){return new e},e.prototype.getInitialEvent=function(t){return rn("online"===t,"Unknown event type: "+t),[this.online_]},e.prototype.currentlyOnline=function(){return this.online_},e}(No),ko=function(){function t(t){this.onMessage_=t,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}return t.prototype.closeAfter=function(t,e){this.closeAfterResponse=t,this.onClose=e,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)},t.prototype.handleResponse=function(t,e){var n=this;this.pendingResponses[t]=e;for(var r=function(){var t=i.pendingResponses[i.currentResponseNum];delete i.pendingResponses[i.currentResponseNum];for(var e=function(e){t[e]&&Cr(function(){n.onMessage_(t[e])})},r=0;r<t.length;++r)e(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}},t}(),Ro="pLPCommand",Oo="pRTLPCB",Po=function(){function t(t,e,n,r){this.connId=t,this.repoInfo=e,this.transportSessionId=n,this.lastSessionId=r,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=hr(t),this.stats_=_o.getCollection(e),this.urlFn=function(t){return e.connectionURL(Rr,t)}}return t.prototype.open=function(t,e){var n=this;this.curSegmentNum=0,this.onDisconnect_=e,this.myPacketOrderer=new ko(t),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(function(){n.log_("Timed out trying to connect."),n.onClosed_(),n.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if(dn()||"complete"===document.readyState)t();else{var e=!1,n=function(){document.body?e||(e=!0,t()):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))}}(function(){if(!n.isClosed_){n.scriptTagHolder=new Lo(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=t[0],i=t[1],o=t[2];if(n.incrementIncomingBytes_(t),n.scriptTagHolder)if(n.connectTimeoutTimer_&&(clearTimeout(n.connectTimeoutTimer_),n.connectTimeoutTimer_=null),n.everConnected_=!0,"start"==r)n.id=i,n.password=o;else{if("close"!==r)throw new Error("Unrecognized command received: "+r);i?(n.scriptTagHolder.sendNewPolls=!1,n.myPacketOrderer.closeAfter(i,function(){n.onClosed_()})):n.onClosed_()}},function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=t[0],i=t[1];n.incrementIncomingBytes_(t),n.myPacketOrderer.handleResponse(r,i)},function(){n.onClosed_()},n.urlFn);var t={start:"t"};t.ser=Math.floor(1e8*Math.random()),n.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=n.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",n.transportSessionId&&(t.s=n.transportSessionId),n.lastSessionId&&(t.ls=n.lastSessionId),!dn()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf("firebaseio.com")&&(t.r="f");var e=n.urlFn(t);n.log_("Connecting via long-poll to "+e),n.scriptTagHolder.addTag(e,function(){})}})},t.prototype.start=function(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)},t.forceAllow=function(){t.forceAllow_=!0},t.forceDisallow=function(){t.forceDisallow_=!0},t.isAvailable=function(){return t.forceAllow_||!t.forceDisallow_&&"undefined"!=typeof document&&null!=document.createElement&&!("object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))&&!("object"==typeof Windows&&"object"==typeof Windows.UI)&&!dn()},t.prototype.markConnectionHealthy=function(){},t.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)},t.prototype.onClosed_=function(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))},t.prototype.close=function(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())},t.prototype.send=function(t){var e=_n(t);this.bytesSent+=e.length,this.stats_.incrementCounter("bytes_sent",e.length);for(var n,r=(n=sn(e),an.encodeByteArray(n,!0)),i=wr(r,1840),o=0;o<i.length;o++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[o]),this.curSegmentNum++},t.prototype.addDisconnectPingFrame=function(t,e){if(!dn()){this.myDisconnFrame=document.createElement("iframe");var n={dframe:"t"};n.id=t,n.pw=e,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}},t.prototype.incrementIncomingBytes_=function(t){var e=_n(t).length;this.bytesReceived+=e,this.stats_.incrementCounter("bytes_received",e)},t}(),Lo=function(){function t(e,n,r,i){if(this.onDisconnect=r,this.urlFn=i,this.outstandingRequests=new Vi,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,dn())this.commandCB=e,this.onMessageCB=n;else{this.uniqueCallbackIdentifier=rr(),window[Ro+this.uniqueCallbackIdentifier]=e,window[Oo+this.uniqueCallbackIdentifier]=n,this.myIFrame=t.createIFrame_();var o="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length))o='<script>document.domain="'+document.domain+'";<\/script>';var s="<html><body>"+o+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(s),this.myIFrame.doc.close()}catch(t){cr("frame writing exception"),t.stack&&cr(t.stack),cr(t)}}}return t.createIFrame_=function(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||cr("No IE domain setting required")}catch(n){var e=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+e+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t},t.prototype.close=function(){var e=this;if(this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(function(){null!==e.myIFrame&&(document.body.removeChild(e.myIFrame),e.myIFrame=null)},Math.floor(0))),dn()&&this.myID){var n={disconn:"t"};n.id=this.myID,n.pw=this.myPW;var r=this.urlFn(n);t.nodeRestRequest(r)}var i=this.onDisconnect;i&&(this.onDisconnect=null,i())},t.prototype.startLongPoll=function(t,e){for(this.myID=t,this.myPW=e,this.alive=!0;this.newRequest_(););},t.prototype.newRequest_=function(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.count()<(this.pendingSegs.length>0?2:1)){this.currentSerial++;var t={};t.id=this.myID,t.pw=this.myPW,t.ser=this.currentSerial;for(var e=this.urlFn(t),n="",r=0;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;var i=this.pendingSegs.shift();n=n+"&seg"+r+"="+i.seg+"&ts"+r+"="+i.ts+"&d"+r+"="+i.d,r++}return e+=n,this.addLongPollTag_(e,this.currentSerial),!0}return!1},t.prototype.enqueueSegment=function(t,e,n){this.pendingSegs.push({seg:t,ts:e,d:n}),this.alive&&this.newRequest_()},t.prototype.addLongPollTag_=function(t,e){var n=this;this.outstandingRequests.add(e,1);var r=function(){n.outstandingRequests.remove(e),n.newRequest_()},i=setTimeout(r,Math.floor(25e3));this.addTag(t,function(){clearTimeout(i),r()})},t.prototype.addTag=function(t,e){var n=this;dn()?this.doNodeLongPoll(t,e):setTimeout(function(){try{if(!n.sendNewPolls)return;var r=n.myIFrame.doc.createElement("script");r.type="text/javascript",r.async=!0,r.src=t,r.onload=r.onreadystatechange=function(){var t=r.readyState;t&&"loaded"!==t&&"complete"!==t||(r.onload=r.onreadystatechange=null,r.parentNode&&r.parentNode.removeChild(r),e())},r.onerror=function(){cr("Long-poll script failed to load: "+t),n.sendNewPolls=!1,n.close()},n.myIFrame.doc.body.appendChild(r)}catch(t){}},Math.floor(1))},t}(),Mo=null;"undefined"!=typeof MozWebSocket?Mo=MozWebSocket:"undefined"!=typeof WebSocket&&(Mo=WebSocket);var xo=function(){function t(e,n,r,i){this.connId=e,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=hr(this.connId),this.stats_=_o.getCollection(n),this.connURL=t.connectionURL_(n,r,i)}return t.connectionURL_=function(t,e,n){var r={v:"5"};return!dn()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf("firebaseio.com")&&(r.r="f"),e&&(r.s=e),n&&(r.ls=n),t.connectionURL("websocket",r)},t.prototype.open=function(t,e){var n=this;this.onDisconnect=e,this.onMessage=t,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,tr.set("previous_websocket_failure",!0);try{if(dn()){var r=en?"AdminNode":"Node",i={headers:{"User-Agent":"Firebase/5/"+Gn.SDK_VERSION+"/"+process.platform+"/"+r}},o=process.env,s=0==this.connURL.indexOf("wss://")?o.HTTPS_PROXY||o.https_proxy:o.HTTP_PROXY||o.http_proxy;s&&(i.proxy={origin:s}),this.mySock=new Mo(this.connURL,[],i)}else this.mySock=new Mo(this.connURL)}catch(t){this.log_("Error instantiating WebSocket.");var a=t.message||t.data;return a&&this.log_(a),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(t){n.handleIncomingFrame(t)},this.mySock.onerror=function(t){n.log_("WebSocket error. Closing connection.");var e=t.message||t.data;e&&n.log_(e),n.onClosed_()}},t.prototype.start=function(){},t.forceDisallow=function(){t.forceDisallow_=!0},t.isAvailable=function(){var e=!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&&(e=!0)}return!e&&null!==Mo&&!t.forceDisallow_},t.previouslyFailed=function(){return tr.isInMemoryStorage||!0===tr.get("previous_websocket_failure")},t.prototype.markConnectionHealthy=function(){tr.remove("previous_websocket_failure")},t.prototype.appendFrame_=function(t){if(this.frames.push(t),this.frames.length==this.totalFrames){var e=this.frames.join("");this.frames=null;var n=bn(e);this.onMessage(n)}},t.prototype.handleNewFrameCount_=function(t){this.totalFrames=t,this.frames=[]},t.prototype.extractFrameCount_=function(t){if(rn(null===this.frames,"We already have a frame buffer"),t.length<=6){var e=Number(t);if(!isNaN(e))return this.handleNewFrameCount_(e),null}return this.handleNewFrameCount_(1),t},t.prototype.handleIncomingFrame=function(t){if(null!==this.mySock){var e=t.data;if(this.bytesReceived+=e.length,this.stats_.incrementCounter("bytes_received",e.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(e);else{var n=this.extractFrameCount_(e);null!==n&&this.appendFrame_(n)}}},t.prototype.send=function(t){this.resetKeepAlive();var e=_n(t);this.bytesSent+=e.length,this.stats_.incrementCounter("bytes_sent",e.length);var n=wr(e,16384);n.length>1&&this.sendString_(String(n.length));for(var r=0;r<n.length;r++)this.sendString_(n[r])},t.prototype.shutdown_=function(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)},t.prototype.onClosed_=function(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))},t.prototype.close=function(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())},t.prototype.resetKeepAlive=function(){var t=this;clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(function(){t.mySock&&t.sendString_("0"),t.resetKeepAlive()},Math.floor(45e3))},t.prototype.sendString_=function(t){try{this.mySock.send(t)}catch(t){this.log_("Exception thrown from WebSocket.send():",t.message||t.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}},t.responsesRequiredToBeHealthy=2,t.healthyTimeout=3e4,t}(),Fo=function(){function t(t){this.initTransports_(t)}return Object.defineProperty(t,"ALL_TRANSPORTS",{get:function(){return[Po,xo]},enumerable:!0,configurable:!0}),t.prototype.initTransports_=function(e){var n=xo&&xo.isAvailable(),r=n&&!xo.previouslyFailed();if(e.webSocketOnly&&(n||pr("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),r=!0),r)this.transports_=[xo];else{var i=this.transports_=[];Er(t.ALL_TRANSPORTS,function(t,e){e&&e.isAvailable()&&i.push(e)})}},t.prototype.initialTransport=function(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")},t.prototype.upgradeTransport=function(){return this.transports_.length>1?this.transports_[1]:null},t}(),Uo=function(){function t(t,e,n,r,i,o,s){this.id=t,this.repoInfo_=e,this.onMessage_=n,this.onReady_=r,this.onDisconnect_=i,this.onKill_=o,this.lastSessionId=s,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=hr("c:"+this.id+":"),this.transportManager_=new Fo(e),this.log_("Connection created"),this.start_()}return t.prototype.start_=function(){var t=this,e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,void 0,this.lastSessionId),this.primaryResponsesRequired_=e.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(){t.conn_&&t.conn_.open(n,r)},Math.floor(0));var i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Dr(function(){t.healthyTimeout_=null,t.isHealthy_||(t.conn_&&t.conn_.bytesReceived>102400?(t.log_("Connection exceeded healthy timeout but has received "+t.conn_.bytesReceived+" bytes. Marking connection healthy."),t.isHealthy_=!0,t.conn_.markConnectionHealthy()):t.conn_&&t.conn_.bytesSent>10240?t.log_("Connection exceeded healthy timeout but has sent "+t.conn_.bytesSent+" bytes. Leaving connection alive."):(t.log_("Closing unhealthy connection after timeout."),t.close()))},Math.floor(i)))},t.prototype.nextTransportId_=function(){return"c:"+this.id+":"+this.connectionCount++},t.prototype.disconnReceiver_=function(t){var e=this;return function(n){t===e.conn_?e.onConnectionLost_(n):t===e.secondaryConn_?(e.log_("Secondary connection lost."),e.onSecondaryConnectionLost_()):e.log_("closing an old connection")}},t.prototype.connReceiver_=function(t){var e=this;return function(n){2!=e.state_&&(t===e.rx_?e.onPrimaryMessageReceived_(n):t===e.secondaryConn_?e.onSecondaryMessageReceived_(n):e.log_("message on old connection"))}},t.prototype.sendRequest=function(t){var e={t:"d",d:t};this.sendData_(e)},t.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)},t.prototype.onSecondaryControl_=function(t){if("t"in t){var e=t.t;"a"===e?this.upgradeIfSecondaryHealthy_():"r"===e?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===e&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}},t.prototype.onSecondaryMessageReceived_=function(t){var e=br("t",t),n=br("d",t);if("c"==e)this.onSecondaryControl_(n);else{if("d"!=e)throw new Error("Unknown protocol layer: "+e);this.pendingDataMessages.push(n)}},t.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:"p",d:{}}}))},t.prototype.proceedWithUpgrade_=function(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()},t.prototype.onPrimaryMessageReceived_=function(t){var e=br("t",t),n=br("d",t);"c"==e?this.onControl_(n):"d"==e&&this.onDataMessage_(n)},t.prototype.onDataMessage_=function(t){this.onPrimaryResponse_(),this.onMessage_(t)},t.prototype.onPrimaryResponse_=function(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))},t.prototype.onControl_=function(t){var e=br("t",t);if("d"in t){var n=t.d;if("h"===e)this.onHandshake_(n);else if("n"===e){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"s"===e?this.onConnectionShutdown_(n):"r"===e?this.onReset_(n):"e"===e?lr("Server Error: "+n):"o"===e?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):lr("Unknown control packet command: "+e)}},t.prototype.onHandshake_=function(t){var e=t.ts,n=t.v,r=t.h;this.sessionId=t.s,this.repoInfo_.updateHost(r),0==this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,e),"5"!==n&&pr("Protocol version mismatch detected"),this.tryStartUpgrade_())},t.prototype.tryStartUpgrade_=function(){var t=this.transportManager_.upgradeTransport();t&&this.startUpgrade_(t)},t.prototype.startUpgrade_=function(t){var e=this;this.secondaryConn_=new t(this.nextTransportId_(),this.repoInfo_,this.sessionId),this.secondaryResponsesRequired_=t.responsesRequiredToBeHealthy||0;var n=this.connReceiver_(this.secondaryConn_),r=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(n,r),Dr(function(){e.secondaryConn_&&(e.log_("Timed out trying to upgrade."),e.secondaryConn_.close())},Math.floor(6e4))},t.prototype.onReset_=function(t){this.log_("Reset packet received. New host: "+t),this.repoInfo_.updateHost(t),1===this.state_?this.close():(this.closeConnections_(),this.start_())},t.prototype.onConnectionEstablished_=function(t,e){var n=this;this.log_("Realtime connection established."),this.conn_=t,this.state_=1,this.onReady_&&(this.onReady_(e,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Dr(function(){n.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))},t.prototype.sendPingOnPrimaryIfNecessary_=function(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))},t.prototype.onSecondaryConnectionLost_=function(){var t=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==t&&this.rx_!==t||this.close()},t.prototype.onConnectionLost_=function(t){this.conn_=null,t||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(tr.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()},t.prototype.onConnectionShutdown_=function(t){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(t),this.onKill_=null),this.onDisconnect_=null,this.close()},t.prototype.sendData_=function(t){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(t)},t.prototype.close=function(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))},t.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)},t}(),qo=function(){function t(){}return t.prototype.put=function(t,e,n,r){},t.prototype.merge=function(t,e,n,r){},t.prototype.refreshAuthToken=function(t){},t.prototype.onDisconnectPut=function(t,e,n){},t.prototype.onDisconnectMerge=function(t,e,n){},t.prototype.onDisconnectCancel=function(t,e){},t.prototype.reportStats=function(t){},t}(),Bo=1e3,Vo=3e5,Wo=function(t){function e(n,r,i,o,s,a){var u=t.call(this)||this;if(u.repoInfo_=n,u.onDataUpdate_=r,u.onConnectStatus_=i,u.onServerInfoUpdate_=o,u.authTokenProvider_=s,u.authOverride_=a,u.id=e.nextPersistentConnectionId_++,u.log_=hr("p:"+u.id+":"),u.interruptReasons_={},u.listens_={},u.outstandingPuts_=[],u.outstandingPutCount_=0,u.onDisconnectRequestQueue_=[],u.connected_=!1,u.reconnectDelay_=Bo,u.maxReconnectDelay_=Vo,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,a&&!dn())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");return u.scheduleConnect_(0),Do.getInstance().on("visible",u.onVisible_,u),-1===n.host.indexOf("fblocal")&&Ao.getInstance().on("online",u.onOnline_,u),u}return Xe(e,t),e.prototype.sendRequest=function(t,e,n){var r=++this.requestNumber_,i={r:r,a:t,b:e};this.log_(_n(i)),rn(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)},e.prototype.listen=function(t,e,n,r){var i=t.queryIdentifier(),o=t.path.toString();this.log_("Listen called for "+o+" "+i),this.listens_[o]=this.listens_[o]||{},rn(t.getQueryParams().isDefault()||!t.getQueryParams().loadsAllData(),"listen() called for non-default but complete query"),rn(!this.listens_[o][i],"listen() called twice for same path/queryId.");var s={onComplete:r,hashFn:e,query:t,tag:n};this.listens_[o][i]=s,this.connected_&&this.sendListen_(s)},e.prototype.sendListen_=function(t){var n=this,r=t.query,i=r.path.toString(),o=r.queryIdentifier();this.log_("Listen on "+i+" for "+o);var s={p:i};t.tag&&(s.q=r.queryObject(),s.t=t.tag),s.h=t.hashFn(),this.sendRequest("q",s,function(s){var a=s.d,u=s.s;e.warnOnListenWarnings_(a,r),(n.listens_[i]&&n.listens_[i][o])===t&&(n.log_("listen response",s),"ok"!==u&&n.removeListen_(i,o),t.onComplete&&t.onComplete(u,a))})},e.warnOnListenWarnings_=function(t,e){if(t&&"object"==typeof t&&En(t,"w")){var n=Tn(t,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){var r='".indexOn": "'+e.getQueryParams().getIndex().toString()+'"',i=e.path.toString();pr("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.")}}},e.prototype.refreshAuthToken=function(t){this.authToken_=t,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},function(){}),this.reduceReconnectDelayIfAdminCredential_(t)},e.prototype.reduceReconnectDelayIfAdminCredential_=function(t){var e;(t&&40===t.length||"object"==typeof(e=wn(t).claims)&&!0===e.admin)&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)},e.prototype.tryAuth=function(){var t,e=this;if(this.connected_&&this.authToken_){var n=this.authToken_,r=(t=wn(n).claims)&&"object"==typeof t&&t.hasOwnProperty("iat")?"auth":"gauth",i={cred:n};null===this.authOverride_?i.noauth=!0:"object"==typeof this.authOverride_&&(i.authvar=this.authOverride_),this.sendRequest(r,i,function(t){var r=t.s,i=t.d||"error";e.authToken_===n&&("ok"===r?e.invalidAuthTokenCount_=0:e.onAuthRevoked_(r,i))})}},e.prototype.unlisten=function(t,e){var n=t.path.toString(),r=t.queryIdentifier();this.log_("Unlisten called for "+n+" "+r),rn(t.getQueryParams().isDefault()||!t.getQueryParams().loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,t.queryObject(),e)},e.prototype.sendUnlisten_=function(t,e,n,r){this.log_("Unlisten on "+t+" for "+e);var i={p:t};r&&(i.q=n,i.t=r),this.sendRequest("n",i)},e.prototype.onDisconnectPut=function(t,e,n){this.connected_?this.sendOnDisconnect_("o",t,e,n):this.onDisconnectRequestQueue_.push({pathString:t,action:"o",data:e,onComplete:n})},e.prototype.onDisconnectMerge=function(t,e,n){this.connected_?this.sendOnDisconnect_("om",t,e,n):this.onDisconnectRequestQueue_.push({pathString:t,action:"om",data:e,onComplete:n})},e.prototype.onDisconnectCancel=function(t,e){this.connected_?this.sendOnDisconnect_("oc",t,null,e):this.onDisconnectRequestQueue_.push({pathString:t,action:"oc",data:null,onComplete:e})},e.prototype.sendOnDisconnect_=function(t,e,n,r){var i={p:e,d:n};this.log_("onDisconnect "+t,i),this.sendRequest(t,i,function(t){r&&setTimeout(function(){r(t.s,t.d)},Math.floor(0))})},e.prototype.put=function(t,e,n,r){this.putInternal("p",t,e,n,r)},e.prototype.merge=function(t,e,n,r){this.putInternal("m",t,e,n,r)},e.prototype.putInternal=function(t,e,n,r,i){var o={p:e,d:n};void 0!==i&&(o.h=i),this.outstandingPuts_.push({action:t,request:o,onComplete:r}),this.outstandingPutCount_++;var s=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(s):this.log_("Buffering put: "+e)},e.prototype.sendPut_=function(t){var e=this,n=this.outstandingPuts_[t].action,r=this.outstandingPuts_[t].request,i=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,r,function(r){e.log_(n+" response",r),delete e.outstandingPuts_[t],e.outstandingPutCount_--,0===e.outstandingPutCount_&&(e.outstandingPuts_=[]),i&&i(r.s,r.d)})},e.prototype.reportStats=function(t){var e=this;if(this.connected_){var n={c:t};this.log_("reportStats",n),this.sendRequest("s",n,function(t){if("ok"!==t.s){var n=t.d;e.log_("reportStats","Error sending stats: "+n)}})}},e.prototype.onDataMessage_=function(t){if("r"in t){this.log_("from server: "+_n(t));var e=t.r,n=this.requestCBHash_[e];n&&(delete this.requestCBHash_[e],n(t.b))}else{if("error"in t)throw"A server-side error has occurred: "+t.error;"a"in t&&this.onDataPush_(t.a,t.b)}},e.prototype.onDataPush_=function(t,e){this.log_("handleServerMessage",t,e),"d"===t?this.onDataUpdate_(e.p,e.d,!1,e.t):"m"===t?this.onDataUpdate_(e.p,e.d,!0,e.t):"c"===t?this.onListenRevoked_(e.p,e.q):"ac"===t?this.onAuthRevoked_(e.s,e.d):"sd"===t?this.onSecurityDebugPacket_(e):lr("Unrecognized action received from server: "+_n(t)+"\nAre you using the latest client?")},e.prototype.onReady_=function(t,e){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(t),this.lastSessionId=e,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)},e.prototype.scheduleConnect_=function(t){var e=this;rn(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(function(){e.establishConnectionTimer_=null,e.establishConnection_()},Math.floor(t))},e.prototype.onVisible_=function(t){t&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=Bo,this.realtime_||this.scheduleConnect_(0)),this.visible_=t},e.prototype.onOnline_=function(t){t?(this.log_("Browser went online."),this.reconnectDelay_=Bo,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())},e.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_>3e4&&(this.reconnectDelay_=Bo),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();var t=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-t);e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)},e.prototype.establishConnection_=function(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var t=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+e.nextConnectionId_++,o=this,s=this.lastSessionId,a=!1,u=null,c=function(){u?u.close():(a=!0,r())};this.realtime_={close:c,sendRequest:function(t){rn(u,"sendRequest call when we're not connected not allowed."),u.sendRequest(t)}};var h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1,this.authTokenProvider_.getToken(h).then(function(e){a?cr("getToken() completed but was canceled"):(cr("getToken() completed. Creating connection."),o.authToken_=e&&e.accessToken,u=new Uo(i,o.repoInfo_,t,n,r,function(t){pr(t+" ("+o.repoInfo_.toString()+")"),o.interrupt("server_kill")},s))}).then(null,function(t){o.log_("Failed to get token: "+t),a||(en&&pr(t),c())})}},e.prototype.interrupt=function(t){cr("Interrupting connection for reason: "+t),this.interruptReasons_[t]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())},e.prototype.resume=function(t){cr("Resuming connection for reason: "+t),delete this.interruptReasons_[t],Cn(this.interruptReasons_)&&(this.reconnectDelay_=Bo,this.realtime_||this.scheduleConnect_(0))},e.prototype.handleTimestamp_=function(t){var e=t-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:e})},e.prototype.cancelSentTransactions_=function(){for(var t=0;t<this.outstandingPuts_.length;t++){var e=this.outstandingPuts_[t];e&&"h"in e.request&&e.queued&&(e.onComplete&&e.onComplete("disconnect"),delete this.outstandingPuts_[t],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])},e.prototype.onListenRevoked_=function(t,e){var n;n=e?e.map(function(t){return _r(t)}).join("$"):"default";var r=this.removeListen_(t,n);r&&r.onComplete&&r.onComplete("permission_denied")},e.prototype.removeListen_=function(t,e){var n,r=new Ar(t).toString();return void 0!==this.listens_[r]?(n=this.listens_[r][e],delete this.listens_[r][e],0===Nn(this.listens_[r])&&delete this.listens_[r]):n=void 0,n},e.prototype.onAuthRevoked_=function(t,e){cr("Auth token revoked: "+t+"/"+e),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==t&&"permission_denied"!==t||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))},e.prototype.onSecurityDebugPacket_=function(t){this.securityDebugCallback_?this.securityDebugCallback_(t):"msg"in t&&console.log("FIREBASE: "+t.msg.replace("\n","\nFIREBASE: "))},e.prototype.restoreState_=function(){var t=this;this.tryAuth(),Sn(this.listens_,function(e,n){Sn(n,function(e,n){t.sendListen_(n)})});for(var e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){var n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}},e.prototype.sendConnectStats_=function(){var t={},e="js";en?e="admin_node":tn&&(e="node"),t["sdk."+e+"."+Gn.SDK_VERSION.replace(/\./g,"-")]=1,pn()?t["framework.cordova"]=1:"object"==typeof navigator&&"ReactNative"===navigator.product&&(t["framework.reactnative"]=1),this.reportStats(t)},e.prototype.shouldReconnect_=function(){var t=Ao.getInstance().currentlyOnline();return Cn(this.interruptReasons_)&&t},e.nextPersistentConnectionId_=0,e.nextConnectionId_=0,e}(qo),jo=function(t){function e(e,n,r){var i=t.call(this)||this;return i.repoInfo_=e,i.onDataUpdate_=n,i.authTokenProvider_=r,i.log_=hr("p:rest:"),i.listens_={},i}return Xe(e,t),e.prototype.reportStats=function(t){throw new Error("Method not implemented.")},e.getListenId_=function(t,e){return void 0!==e?"tag$"+e:(rn(t.getQueryParams().isDefault(),"should have a tag if it's not a default query."),t.path.toString())},e.prototype.listen=function(t,n,r,i){var o=this,s=t.path.toString();this.log_("Listen called for "+s+" "+t.queryIdentifier());var a=e.getListenId_(t,r),u={};this.listens_[a]=u;var c=t.getQueryParams().toRestQueryStringParameters();this.restRequest_(s+".json",c,function(t,e){var n=e;(404===t&&(n=null,t=null),null===t&&o.onDataUpdate_(s,n,!1,r),Tn(o.listens_,a)===u)&&i(t?401==t?"permission_denied":"rest_error:"+t:"ok",null)})},e.prototype.unlisten=function(t,n){var r=e.getListenId_(t,n);delete this.listens_[r]},e.prototype.refreshAuthToken=function(t){},e.prototype.restRequest_=function(t,e,n){var r=this;void 0===e&&(e={}),e.format="export",this.authTokenProvider_.getToken(!1).then(function(i){var o=i&&i.accessToken;o&&(e.auth=o);var s,a=(r.repoInfo_.secure?"https://":"http://")+r.repoInfo_.host+t+"?"+(s=[],Sn(e,function(t,e){Array.isArray(e)?e.forEach(function(e){s.push(encodeURIComponent(t)+"="+encodeURIComponent(e))}):s.push(encodeURIComponent(t)+"="+encodeURIComponent(e))}),s.length?"&"+s.join("&"):"");r.log_("Sending REST request for "+a);var u=new XMLHttpRequest;u.onreadystatechange=function(){if(n&&4===u.readyState){r.log_("REST Response for "+a+" received. status:",u.status,"response:",u.responseText);var t=null;if(u.status>=200&&u.status<300){try{t=bn(u.responseText)}catch(t){pr("Failed to parse JSON response for "+a+": "+u.responseText)}n(null,t)}else 401!==u.status&&404!==u.status&&pr("Got unsuccessful REST response for "+a+" Status: "+u.status),n(u.status);n=null}},u.open("GET",a,!0),u.send()})},e}(qo),Ko=function(){function t(t,e,n){var r=this;this.repoInfo_=t,this.app=n,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Io,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=new Wi,this.persistentConnection_=null;var i=new vo(n);if(this.stats_=_o.getCollection(t),e||Nr())this.server_=new jo(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{_n(o)}catch(t){throw new Error("Invalid authOverride provided: "+t)}}this.persistentConnection_=new Wo(this.repoInfo_,this.onDataUpdate_.bind(this),this.onConnectStatus_.bind(this),this.onServerInfoUpdate_.bind(this),i,o),this.server_=this.persistentConnection_}i.addTokenChangeListener(function(t){r.server_.refreshAuthToken(t)}),this.statsReporter_=_o.getOrCreateReporter(t,function(){return new So(r.stats_,r.server_)}),this.transactions_init_(),this.infoData_=new go,this.infoSyncTree_=new mo({startListening:function(t,e,n,i){var o=[],s=r.infoData_.getNode(t.path);return s.isEmpty()||(o=r.infoSyncTree_.applyServerOverwrite(t.path,s),setTimeout(function(){i("ok")},0)),o},stopListening:function(){}}),this.updateInfo_("connected",!1),this.serverSyncTree_=new mo({startListening:function(t,e,n,i){return r.server_.listen(t,n,e,function(e,n){var o=i(e,n);r.eventQueue_.raiseEventsForChangedPath(t.path,o)}),[]},stopListening:function(t,e){r.server_.unlisten(t,e)}})}return t.prototype.toString=function(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host},t.prototype.name=function(){return this.repoInfo_.namespace},t.prototype.serverTime=function(){var t=this.infoData_.getNode(new Ar(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t},t.prototype.generateServerValues=function(){return(t=(t={timestamp:this.serverTime()})||{}).timestamp=t.timestamp||(new Date).getTime(),t;var t},t.prototype.onDataUpdate_=function(t,e,n,r){this.dataUpdateCount++;var i=new Ar(t);e=this.interceptServerDataCallback_?this.interceptServerDataCallback_(t,e):e;var o=[];if(r)if(n){var s=Dn(e,function(t){return ki(t)});o=this.serverSyncTree_.applyTaggedQueryMerge(i,s,r)}else{var a=ki(e);o=this.serverSyncTree_.applyTaggedQueryOverwrite(i,a,r)}else if(n){var u=Dn(e,function(t){return ki(t)});o=this.serverSyncTree_.applyServerMerge(i,u)}else{var c=ki(e);o=this.serverSyncTree_.applyServerOverwrite(i,c)}var h=i;o.length>0&&(h=this.rerunTransactions_(i)),this.eventQueue_.raiseEventsForChangedPath(h,o)},t.prototype.interceptServerData_=function(t){this.interceptServerDataCallback_=t},t.prototype.onConnectStatus_=function(t){this.updateInfo_("connected",t),!1===t&&this.runOnDisconnectEvents_()},t.prototype.onServerInfoUpdate_=function(t){var e=this;Er(t,function(t,n){e.updateInfo_(n,t)})},t.prototype.updateInfo_=function(t,e){var n=new Ar("/.info/"+t),r=ki(e);this.infoData_.updateSnapshot(n,r);var i=this.infoSyncTree_.applyServerOverwrite(n,r);this.eventQueue_.raiseEventsForChangedPath(n,i)},t.prototype.getNextWriteId_=function(){return this.nextWriteId_++},t.prototype.setWithPriority=function(t,e,n,r){var i=this;this.log_("set",{path:t.toString(),value:e,priority:n});var o=this.generateServerValues(),s=ki(e,n),a=Ki(s,o),u=this.getNextWriteId_(),c=this.serverSyncTree_.applyUserOverwrite(t,a,u,!0);this.eventQueue_.queueEvents(c),this.server_.put(t.toString(),s.val(!0),function(e,n){var o="ok"===e;o||pr("set at "+t+" failed: "+e);var s=i.serverSyncTree_.ackUserWrite(u,!o);i.eventQueue_.raiseEventsForChangedPath(t,s),i.callOnCompleteCallback(r,e,n)});var h=this.abortTransactions_(t);this.rerunTransactions_(h),this.eventQueue_.raiseEventsForChangedPath(h,[])},t.prototype.update=function(t,e,n){var r=this;this.log_("update",{path:t.toString(),value:e});var i=!0,o=this.generateServerValues(),s={};if(Sn(e,function(t,e){i=!1;var n=ki(e);s[t]=Ki(n,o)}),i)cr("update() called with empty data. Don't do anything."),this.callOnCompleteCallback(n,"ok");else{var a=this.getNextWriteId_(),u=this.serverSyncTree_.applyUserMerge(t,s,a);this.eventQueue_.queueEvents(u),this.server_.merge(t.toString(),e,function(e,i){var o="ok"===e;o||pr("update at "+t+" failed: "+e);var s=r.serverSyncTree_.ackUserWrite(a,!o),u=s.length>0?r.rerunTransactions_(t):t;r.eventQueue_.raiseEventsForChangedPath(u,s),r.callOnCompleteCallback(n,e,i)}),Sn(e,function(e){var n=r.abortTransactions_(t.child(e));r.rerunTransactions_(n)}),this.eventQueue_.raiseEventsForChangedPath(t,[])}},t.prototype.runOnDisconnectEvents_=function(){var t=this;this.log_("onDisconnectEvents");var e=this.generateServerValues(),n=[];(function(t,e){var n=new Wi;return t.forEachTree(new Ar(""),function(t,r){n.remember(t,Ki(r,e))}),n})(this.onDisconnect_,e).forEachTree(Ar.Empty,function(e,r){n=n.concat(t.serverSyncTree_.applyServerOverwrite(e,r));var i=t.abortTransactions_(e);t.rerunTransactions_(i)}),this.onDisconnect_=new Wi,this.eventQueue_.raiseEventsForChangedPath(Ar.Empty,n)},t.prototype.onDisconnectCancel=function(t,e){var n=this;this.server_.onDisconnectCancel(t.toString(),function(r,i){"ok"===r&&n.onDisconnect_.forget(t),n.callOnCompleteCallback(e,r,i)})},t.prototype.onDisconnectSet=function(t,e,n){var r=this,i=ki(e);this.server_.onDisconnectPut(t.toString(),i.val(!0),function(e,o){"ok"===e&&r.onDisconnect_.remember(t,i),r.callOnCompleteCallback(n,e,o)})},t.prototype.onDisconnectSetWithPriority=function(t,e,n,r){var i=this,o=ki(e,n);this.server_.onDisconnectPut(t.toString(),o.val(!0),function(e,n){"ok"===e&&i.onDisconnect_.remember(t,o),i.callOnCompleteCallback(r,e,n)})},t.prototype.onDisconnectUpdate=function(t,e,n){var r=this;if(Cn(e))return cr("onDisconnect().update() called with empty data. Don't do anything."),void this.callOnCompleteCallback(n,"ok");this.server_.onDisconnectMerge(t.toString(),e,function(i,o){"ok"===i&&Sn(e,function(e,n){var i=ki(n);r.onDisconnect_.remember(t.child(e),i)}),r.callOnCompleteCallback(n,i,o)})},t.prototype.addEventCallbackForQuery=function(t,e){var n;n=".info"===t.path.getFront()?this.infoSyncTree_.addEventRegistration(t,e):this.serverSyncTree_.addEventRegistration(t,e),this.eventQueue_.raiseEventsAtPath(t.path,n)},t.prototype.removeEventCallbackForQuery=function(t,e){var n;n=".info"===t.path.getFront()?this.infoSyncTree_.removeEventRegistration(t,e):this.serverSyncTree_.removeEventRegistration(t,e),this.eventQueue_.raiseEventsAtPath(t.path,n)},t.prototype.interrupt=function(){this.persistentConnection_&&this.persistentConnection_.interrupt("repo_interrupt")},t.prototype.resume=function(){this.persistentConnection_&&this.persistentConnection_.resume("repo_interrupt")},t.prototype.stats=function(t){if(void 0===t&&(t=!1),"undefined"!=typeof console){var e;t?(this.statsListener_||(this.statsListener_=new wo(this.stats_)),e=this.statsListener_.get()):e=this.stats_.get();var n=Object.keys(e).reduce(function(t,e){return Math.max(e.length,t)},0);Sn(e,function(t,e){for(var r=t.length;r<n+2;r++)t+=" ";console.log(t+e)})}},t.prototype.statsIncrementCounter=function(t){this.stats_.incrementCounter(t),this.statsReporter_.includeStat(t)},t.prototype.log_=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n="";this.persistentConnection_&&(n=this.persistentConnection_.id+":"),cr.apply(void 0,[n].concat(t))},t.prototype.callOnCompleteCallback=function(t,e,n){t&&Cr(function(){if("ok"==e)t(null);else{var r=(e||"error").toUpperCase(),i=r;n&&(i+=": "+n);var o=new Error(i);o.code=r,t(o)}})},Object.defineProperty(t.prototype,"database",{get:function(){return this.__database||(this.__database=new ts(this))},enumerable:!0,configurable:!0}),t}(),Qo=function(){function t(e){this.indexedFilter_=new ro(e.getIndex()),this.index_=e.getIndex(),this.startPost_=t.getStartPost_(e),this.endPost_=t.getEndPost_(e)}return t.prototype.getStartPost=function(){return this.startPost_},t.prototype.getEndPost=function(){return this.endPost_},t.prototype.matches=function(t){return this.index_.compare(this.getStartPost(),t)<=0&&this.index_.compare(t,this.getEndPost())<=0},t.prototype.updateChild=function(t,e,n,r,i,o){return this.matches(new ri(e,n))||(n=Ni.EMPTY_NODE),this.indexedFilter_.updateChild(t,e,n,r,i,o)},t.prototype.updateFullNode=function(t,e,n){e.isLeafNode()&&(e=Ni.EMPTY_NODE);var r=e.withIndex(this.index_);r=r.updatePriority(Ni.EMPTY_NODE);var i=this;return e.forEachChild(yi,function(t,e){i.matches(new ri(t,e))||(r=r.updateImmediateChild(t,Ni.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(t,r,n)},t.prototype.updatePriority=function(t,e){return t},t.prototype.filtersNodes=function(){return!0},t.prototype.getIndexedFilter=function(){return this.indexedFilter_},t.prototype.getIndex=function(){return this.index_},t.getStartPost_=function(t){if(t.hasStart()){var e=t.getIndexStartName();return t.getIndex().makePost(t.getIndexStartValue(),e)}return t.getIndex().minPost()},t.getEndPost_=function(t){if(t.hasEnd()){var e=t.getIndexEndName();return t.getIndex().makePost(t.getIndexEndValue(),e)}return t.getIndex().maxPost()},t}(),Ho=function(){function t(t){this.rangedFilter_=new Qo(t),this.index_=t.getIndex(),this.limit_=t.getLimit(),this.reverse_=!t.isViewFromLeft()}return t.prototype.updateChild=function(t,e,n,r,i,o){return this.rangedFilter_.matches(new ri(e,n))||(n=Ni.EMPTY_NODE),t.getImmediateChild(e).equals(n)?t:t.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(t,e,n,r,i,o):this.fullLimitUpdateChild_(t,e,n,i,o)},t.prototype.updateFullNode=function(t,e,n){var r;if(e.isLeafNode()||e.isEmpty())r=Ni.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<e.numChildren()&&e.isIndexed(this.index_)){r=Ni.EMPTY_NODE.withIndex(this.index_);var i=void 0;i=this.reverse_?e.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):e.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);for(var o=0;i.hasNext()&&o<this.limit_;){var s=i.getNext();if(!(this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),s)<=0:this.index_.compare(s,this.rangedFilter_.getEndPost())<=0))break;r=r.updateImmediateChild(s.name,s.node),o++}}else{r=(r=e.withIndex(this.index_)).updatePriority(Ni.EMPTY_NODE);var a=void 0,u=void 0,c=void 0;i=void 0;if(this.reverse_){i=r.getReverseIterator(this.index_),a=this.rangedFilter_.getEndPost(),u=this.rangedFilter_.getStartPost();var h=this.index_.getCompare();c=function(t,e){return h(e,t)}}else i=r.getIterator(this.index_),a=this.rangedFilter_.getStartPost(),u=this.rangedFilter_.getEndPost(),c=this.index_.getCompare();o=0;for(var l=!1;i.hasNext();){s=i.getNext();!l&&c(a,s)<=0&&(l=!0),l&&o<this.limit_&&c(s,u)<=0?o++:r=r.updateImmediateChild(s.name,Ni.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(t,r,n)},t.prototype.updatePriority=function(t,e){return t},t.prototype.filtersNodes=function(){return!0},t.prototype.getIndexedFilter=function(){return this.rangedFilter_.getIndexedFilter()},t.prototype.getIndex=function(){return this.index_},t.prototype.fullLimitUpdateChild_=function(t,e,n,r,i){var o;if(this.reverse_){var s=this.index_.getCompare();o=function(t,e){return s(e,t)}}else o=this.index_.getCompare();var a=t;rn(a.numChildren()==this.limit_,"");var u=new ri(e,n),c=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(u);if(a.hasChild(e)){for(var l=a.getImmediateChild(e),f=r.getChildAfterChild(this.index_,c,this.reverse_);null!=f&&(f.name==e||a.hasChild(f.name));)f=r.getChildAfterChild(this.index_,f,this.reverse_);var p=null==f?1:o(f,u);if(h&&!n.isEmpty()&&p>=0)return null!=i&&i.trackChildChange(no.childChangedChange(e,n,l)),a.updateImmediateChild(e,n);null!=i&&i.trackChildChange(no.childRemovedChange(e,l));var d=a.updateImmediateChild(e,Ni.EMPTY_NODE);return null!=f&&this.rangedFilter_.matches(f)?(null!=i&&i.trackChildChange(no.childAddedChange(f.name,f.node)),d.updateImmediateChild(f.name,f.node)):d}return n.isEmpty()?t:h&&o(c,u)>=0?(null!=i&&(i.trackChildChange(no.childRemovedChange(c.name,c.node)),i.trackChildChange(no.childAddedChange(e,n))),a.updateImmediateChild(e,n).updateImmediateChild(c.name,Ni.EMPTY_NODE)):t},t}(),Go=function(){function t(){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_=yi}return t.prototype.hasStart=function(){return this.startSet_},t.prototype.isViewFromLeft=function(){return""===this.viewFrom_?this.startSet_:this.viewFrom_===t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT},t.prototype.getIndexStartValue=function(){return rn(this.startSet_,"Only valid if start has been set"),this.indexStartValue_},t.prototype.getIndexStartName=function(){return rn(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:yr},t.prototype.hasEnd=function(){return this.endSet_},t.prototype.getIndexEndValue=function(){return rn(this.endSet_,"Only valid if end has been set"),this.indexEndValue_},t.prototype.getIndexEndName=function(){return rn(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:mr},t.prototype.hasLimit=function(){return this.limitSet_},t.prototype.hasAnchoredLimit=function(){return this.limitSet_&&""!==this.viewFrom_},t.prototype.getLimit=function(){return rn(this.limitSet_,"Only valid if limit has been set"),this.limit_},t.prototype.getIndex=function(){return this.index_},t.prototype.copy_=function(){var e=new t;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e},t.prototype.limit=function(t){var e=this.copy_();return e.limitSet_=!0,e.limit_=t,e.viewFrom_="",e},t.prototype.limitToFirst=function(e){var n=this.copy_();return n.limitSet_=!0,n.limit_=e,n.viewFrom_=t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT,n},t.prototype.limitToLast=function(e){var n=this.copy_();return n.limitSet_=!0,n.limit_=e,n.viewFrom_=t.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT,n},t.prototype.startAt=function(t,e){var n=this.copy_();return n.startSet_=!0,void 0===t&&(t=null),n.indexStartValue_=t,null!=e?(n.startNameSet_=!0,n.indexStartName_=e):(n.startNameSet_=!1,n.indexStartName_=""),n},t.prototype.endAt=function(t,e){var n=this.copy_();return n.endSet_=!0,void 0===t&&(t=null),n.indexEndValue_=t,void 0!==e?(n.endNameSet_=!0,n.indexEndName_=e):(n.endNameSet_=!1,n.indexEndName_=""),n},t.prototype.orderBy=function(t){var e=this.copy_();return e.index_=t,e},t.prototype.getQueryObject=function(){var e=t.WIRE_PROTOCOL_CONSTANTS_,n={};if(this.startSet_&&(n[e.INDEX_START_VALUE]=this.indexStartValue_,this.startNameSet_&&(n[e.INDEX_START_NAME]=this.indexStartName_)),this.endSet_&&(n[e.INDEX_END_VALUE]=this.indexEndValue_,this.endNameSet_&&(n[e.INDEX_END_NAME]=this.indexEndName_)),this.limitSet_){n[e.LIMIT]=this.limit_;var r=this.viewFrom_;""===r&&(r=this.isViewFromLeft()?e.VIEW_FROM_LEFT:e.VIEW_FROM_RIGHT),n[e.VIEW_FROM]=r}return this.index_!==yi&&(n[e.INDEX]=this.index_.toString()),n},t.prototype.loadsAllData=function(){return!(this.startSet_||this.endSet_||this.limitSet_)},t.prototype.isDefault=function(){return this.loadsAllData()&&this.index_==yi},t.prototype.getNodeFilter=function(){return this.loadsAllData()?new ro(this.getIndex()):this.hasLimit()?new Ho(this):new Qo(this)},t.prototype.toRestQueryStringParameters=function(){var e,n=t.REST_QUERY_CONSTANTS_,r={};return this.isDefault()?r:(this.index_===yi?e=n.PRIORITY_INDEX:this.index_===Pi?e=n.VALUE_INDEX:this.index_===si?e=n.KEY_INDEX:(rn(this.index_ instanceof Li,"Unrecognized index type!"),e=this.index_.toString()),r[n.ORDER_BY]=_n(e),this.startSet_&&(r[n.START_AT]=_n(this.indexStartValue_),this.startNameSet_&&(r[n.START_AT]+=","+_n(this.indexStartName_))),this.endSet_&&(r[n.END_AT]=_n(this.indexEndValue_),this.endNameSet_&&(r[n.END_AT]+=","+_n(this.indexEndName_))),this.limitSet_&&(this.isViewFromLeft()?r[n.LIMIT_TO_FIRST]=this.limit_:r[n.LIMIT_TO_LAST]=this.limit_),r)},t.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"},t.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"},t.DEFAULT=new t,t}(),zo=function(t){function e(e,n){if(!(e instanceof Ko))throw new Error("new Reference() no longer supported - use app.database().");return t.call(this,e,n,Go.DEFAULT,!1)||this}return Xe(e,t),e.prototype.getKey=function(){return Mn("Reference.key",0,0,arguments.length),this.path.isEmpty()?null:this.path.getBack()},e.prototype.child=function(t){return Mn("Reference.child",1,1,arguments.length),"number"==typeof t?t=String(t):t instanceof Ar||(null===this.path.getFront()?function(t,e,n,r){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),Jr(t,e,n,r)}("Reference.child",1,t,!1):Jr("Reference.child",1,t,!1)),new e(this.repo,this.path.child(t))},e.prototype.getParent=function(){Mn("Reference.parent",0,0,arguments.length);var t=this.path.parent();return null===t?null:new e(this.repo,t)},e.prototype.getRoot=function(){Mn("Reference.root",0,0,arguments.length);for(var t=this;null!==t.getParent();)t=t.getParent();return t},e.prototype.databaseProp=function(){return this.repo.database},e.prototype.set=function(t,e){Mn("Reference.set",1,2,arguments.length),$r("Reference.set",this.path),Qr("Reference.set",1,t,this.path,!1),Fn("Reference.set",2,e,!0);var n=new fn;return this.repo.setWithPriority(this.path,t,null,n.wrapCallback(e)),n.promise},e.prototype.update=function(t,e){if(Mn("Reference.update",1,2,arguments.length),$r("Reference.update",this.path),Array.isArray(t)){for(var n={},r=0;r<t.length;++r)n[""+r]=t[r];t=n,pr("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.")}Gr("Reference.update",1,t,this.path,!1),Fn("Reference.update",2,e,!0);var i=new fn;return this.repo.update(this.path,t,i.wrapCallback(e)),i.promise},e.prototype.setWithPriority=function(t,e,n){if(Mn("Reference.setWithPriority",2,3,arguments.length),$r("Reference.setWithPriority",this.path),Qr("Reference.setWithPriority",1,t,this.path,!1),zr("Reference.setWithPriority",2,e,!1),Fn("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 fn;return this.repo.setWithPriority(this.path,t,e,r.wrapCallback(n)),r.promise},e.prototype.remove=function(t){return Mn("Reference.remove",0,1,arguments.length),$r("Reference.remove",this.path),Fn("Reference.remove",1,t,!0),this.set(null,t)},e.prototype.transaction=function(t,e,n){if(Mn("Reference.transaction",1,3,arguments.length),$r("Reference.transaction",this.path),Fn("Reference.transaction",1,t,!1),Fn("Reference.transaction",2,e,!0),function(t,e,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(xn(t,e,r)+"must be a boolean.")}("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 fn;"function"==typeof e&&r.promise.catch(function(){});return this.repo.startTransaction(this.path,t,function(t,n,i){t?r.reject(t):r.resolve(new ei(n,i)),"function"==typeof e&&e(t,n,i)},n),r.promise},e.prototype.setPriority=function(t,e){Mn("Reference.setPriority",1,2,arguments.length),$r("Reference.setPriority",this.path),zr("Reference.setPriority",1,t,!1),Fn("Reference.setPriority",2,e,!0);var n=new fn;return this.repo.setWithPriority(this.path.child(".priority"),t,null,n.wrapCallback(e)),n.promise},e.prototype.push=function(t,e){Mn("Reference.push",0,2,arguments.length),$r("Reference.push",this.path),Qr("Reference.push",1,t,this.path,!0),Fn("Reference.push",2,e,!0);var n,r=this.repo.serverTime(),i=ni(r),o=this.child(i),s=this.child(i);return n=null!=t?o.set(t,e).then(function(){return s}):Promise.resolve(s),o.then=n.then.bind(n),o.catch=n.then.bind(n,void 0),"function"==typeof e&&n.catch(function(){}),o},e.prototype.onDisconnect=function(){return $r("Reference.onDisconnect",this.path),new ti(this.repo,this.path)},Object.defineProperty(e.prototype,"database",{get:function(){return this.databaseProp()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"key",{get:function(){return this.getKey()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return this.getParent()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"root",{get:function(){return this.getRoot()},enumerable:!0,configurable:!0}),e}(Bi);Bi.__referenceConstructor=zo,lo.__referenceConstructor=zo;var Yo,Xo=function(){return function(){this.children={},this.childCount=0,this.value=null}}(),Jo=function(){function t(t,e,n){void 0===t&&(t=""),void 0===e&&(e=null),void 0===n&&(n=new Xo),this.name_=t,this.parent_=e,this.node_=n}return t.prototype.subTree=function(e){for(var n,r=e instanceof Ar?e:new Ar(e),i=this;null!==(n=r.getFront());){i=new t(n,i,Tn(i.node_.children,n)||new Xo),r=r.popFront()}return i},t.prototype.getValue=function(){return this.node_.value},t.prototype.setValue=function(t){rn(void 0!==t,"Cannot set value to undefined"),this.node_.value=t,this.updateParents_()},t.prototype.clear=function(){this.node_.value=null,this.node_.children={},this.node_.childCount=0,this.updateParents_()},t.prototype.hasChildren=function(){return this.node_.childCount>0},t.prototype.isEmpty=function(){return null===this.getValue()&&!this.hasChildren()},t.prototype.forEachChild=function(e){var n=this;Sn(this.node_.children,function(r,i){e(new t(r,n,i))})},t.prototype.forEachDescendant=function(t,e,n){e&&!n&&t(this),this.forEachChild(function(e){e.forEachDescendant(t,!0,n)}),e&&n&&t(this)},t.prototype.forEachAncestor=function(t,e){for(var n=e?this:this.parent();null!==n;){if(t(n))return!0;n=n.parent()}return!1},t.prototype.forEachImmediateDescendantWithValue=function(t){this.forEachChild(function(e){null!==e.getValue()?t(e):e.forEachImmediateDescendantWithValue(t)})},t.prototype.path=function(){return new Ar(null===this.parent_?this.name_:this.parent_.path()+"/"+this.name_)},t.prototype.name=function(){return this.name_},t.prototype.parent=function(){return this.parent_},t.prototype.updateParents_=function(){null!==this.parent_&&this.parent_.updateChild_(this.name_,this)},t.prototype.updateChild_=function(t,e){var n=e.isEmpty(),r=En(this.node_.children,t);n&&r?(delete this.node_.children[t],this.node_.childCount--,this.updateParents_()):n||r||(this.node_.children[t]=e.node_,this.node_.childCount++,this.updateParents_())},t}();!function(t){t[t.RUN=0]="RUN",t[t.SENT=1]="SENT",t[t.COMPLETED=2]="COMPLETED",t[t.SENT_NEEDS_ABORT=3]="SENT_NEEDS_ABORT",t[t.NEEDS_ABORT=4]="NEEDS_ABORT"}(Yo||(Yo={})),Ko.MAX_TRANSACTION_RETRIES_=25,Ko.prototype.transactions_init_=function(){this.transactionQueueTree_=new Jo},Ko.prototype.startTransaction=function(t,e,n,r){this.log_("transaction on "+t);var i=function(){},o=new zo(this,t);o.on("value",i);var s={path:t,update:e,onComplete:n,status:null,order:rr(),applyLocally:r,retryCount:0,unwatcher:function(){o.off("value",i)},abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=this.getLatestState_(t);s.currentInputSnapshot=a;var u=s.update(a.val());if(void 0===u){if(s.unwatcher(),s.currentOutputSnapshotRaw=null,s.currentOutputSnapshotResolved=null,s.onComplete){var c=new Mi(s.currentInputSnapshot,new zo(this,s.path),yi);s.onComplete(null,!1,c)}}else{Hr("transaction failed: Data returned ",u,s.path),s.status=Yo.RUN;var h=this.transactionQueueTree_.subTree(t),l=h.getValue()||[];l.push(s),h.setValue(l);var f=void 0;if("object"==typeof u&&null!==u&&En(u,".priority"))f=Tn(u,".priority"),rn(Kr(f),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else f=(this.serverSyncTree_.calcCompleteEventCache(t)||Ni.EMPTY_NODE).getPriority().val();f=f;var p=this.generateServerValues(),d=ki(u,f),y=Ki(d,p);s.currentOutputSnapshotRaw=d,s.currentOutputSnapshotResolved=y,s.currentWriteId=this.getNextWriteId_();var m=this.serverSyncTree_.applyUserOverwrite(t,y,s.currentWriteId,s.applyLocally);this.eventQueue_.raiseEventsForChangedPath(t,m),this.sendReadyTransactions_()}},Ko.prototype.getLatestState_=function(t,e){return this.serverSyncTree_.calcCompleteEventCache(t,e)||Ni.EMPTY_NODE},Ko.prototype.sendReadyTransactions_=function(t){var e=this;if(void 0===t&&(t=this.transactionQueueTree_),t||this.pruneCompletedTransactionsBelowNode_(t),null!==t.getValue()){var n=this.buildTransactionQueue_(t);rn(n.length>0,"Sending zero length transaction queue"),n.every(function(t){return t.status===Yo.RUN})&&this.sendTransactionQueue_(t.path(),n)}else t.hasChildren()&&t.forEachChild(function(t){e.sendReadyTransactions_(t)})},Ko.prototype.sendTransactionQueue_=function(t,e){for(var n=this,r=e.map(function(t){return t.currentWriteId}),i=this.getLatestState_(t,r),o=i,s=i.hash(),a=0;a<e.length;a++){var u=e[a];rn(u.status===Yo.RUN,"tryToSendTransactionQueue_: items in queue should all be run."),u.status=Yo.SENT,u.retryCount++;var c=Ar.relativePath(t,u.path);o=o.updateChild(c,u.currentOutputSnapshotRaw)}var h=o.val(!0),l=t;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=[],s=0;s<e.length;s++){if(e[s].status=Yo.COMPLETED,i=i.concat(n.serverSyncTree_.ackUserWrite(e[s].currentWriteId)),e[s].onComplete){var a=e[s].currentOutputSnapshotResolved,u=new zo(n,e[s].path),c=new Mi(a,u,yi);o.push(e[s].onComplete.bind(null,null,!0,c))}e[s].unwatcher()}n.pruneCompletedTransactionsBelowNode_(n.transactionQueueTree_.subTree(t)),n.sendReadyTransactions_(),n.eventQueue_.raiseEventsForChangedPath(t,i);for(s=0;s<o.length;s++)Cr(o[s])}else{if("datastale"===r)for(s=0;s<e.length;s++)e[s].status===Yo.SENT_NEEDS_ABORT?e[s].status=Yo.NEEDS_ABORT:e[s].status=Yo.RUN;else{pr("transaction at "+l.toString()+" failed: "+r);for(s=0;s<e.length;s++)e[s].status=Yo.NEEDS_ABORT,e[s].abortReason=r}n.rerunTransactions_(t)}},s)},Ko.prototype.rerunTransactions_=function(t){var e=this.getAncestorTransactionNode_(t),n=e.path(),r=this.buildTransactionQueue_(e);return this.rerunTransactionQueue_(r,n),n},Ko.prototype.rerunTransactionQueue_=function(t,e){if(0!==t.length){for(var n,r=[],i=[],o=t.filter(function(t){return t.status===Yo.RUN}).map(function(t){return t.currentWriteId}),s=0;s<t.length;s++){var a=t[s],u=Ar.relativePath(e,a.path),c=!1,h=void 0;if(rn(null!==u,"rerunTransactionsUnderNode_: relativePath should not be null."),a.status===Yo.NEEDS_ABORT)c=!0,h=a.abortReason,i=i.concat(this.serverSyncTree_.ackUserWrite(a.currentWriteId,!0));else if(a.status===Yo.RUN)if(a.retryCount>=Ko.MAX_TRANSACTION_RETRIES_)c=!0,h="maxretry",i=i.concat(this.serverSyncTree_.ackUserWrite(a.currentWriteId,!0));else{var l=this.getLatestState_(a.path,o);a.currentInputSnapshot=l;var f=t[s].update(l.val());if(void 0!==f){Hr("transaction failed: Data returned ",f,a.path);var p=ki(f);"object"==typeof f&&null!=f&&En(f,".priority")||(p=p.updatePriority(l.getPriority()));var d=a.currentWriteId,y=this.generateServerValues(),m=Ki(p,y);a.currentOutputSnapshotRaw=p,a.currentOutputSnapshotResolved=m,a.currentWriteId=this.getNextWriteId_(),o.splice(o.indexOf(d),1),i=(i=i.concat(this.serverSyncTree_.applyUserOverwrite(a.path,m,a.currentWriteId,a.applyLocally))).concat(this.serverSyncTree_.ackUserWrite(d,!0))}else c=!0,h="nodata",i=i.concat(this.serverSyncTree_.ackUserWrite(a.currentWriteId,!0))}if(this.eventQueue_.raiseEventsForChangedPath(e,i),i=[],c&&(t[s].status=Yo.COMPLETED,n=t[s].unwatcher,setTimeout(n,Math.floor(0)),t[s].onComplete))if("nodata"===h){var g=new zo(this,t[s].path),v=t[s].currentInputSnapshot,b=new Mi(v,g,yi);r.push(t[s].onComplete.bind(null,null,!1,b))}else r.push(t[s].onComplete.bind(null,new Error(h),!1,null))}this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);for(s=0;s<r.length;s++)Cr(r[s]);this.sendReadyTransactions_()}},Ko.prototype.getAncestorTransactionNode_=function(t){for(var e,n=this.transactionQueueTree_;null!==(e=t.getFront())&&null===n.getValue();)n=n.subTree(e),t=t.popFront();return n},Ko.prototype.buildTransactionQueue_=function(t){var e=[];return this.aggregateTransactionQueuesForNode_(t,e),e.sort(function(t,e){return t.order-e.order}),e},Ko.prototype.aggregateTransactionQueuesForNode_=function(t,e){var n=this,r=t.getValue();if(null!==r)for(var i=0;i<r.length;i++)e.push(r[i]);t.forEachChild(function(t){n.aggregateTransactionQueuesForNode_(t,e)})},Ko.prototype.pruneCompletedTransactionsBelowNode_=function(t){var e=this,n=t.getValue();if(n){for(var r=0,i=0;i<n.length;i++)n[i].status!==Yo.COMPLETED&&(n[r]=n[i],r++);n.length=r,t.setValue(n.length>0?n:null)}t.forEachChild(function(t){e.pruneCompletedTransactionsBelowNode_(t)})},Ko.prototype.abortTransactions_=function(t){var e=this,n=this.getAncestorTransactionNode_(t).path(),r=this.transactionQueueTree_.subTree(t);return r.forEachAncestor(function(t){e.abortTransactionsOnNode_(t)}),this.abortTransactionsOnNode_(r),r.forEachDescendant(function(t){e.abortTransactionsOnNode_(t)}),n},Ko.prototype.abortTransactionsOnNode_=function(t){var e=t.getValue();if(null!==e){for(var n=[],r=[],i=-1,o=0;o<e.length;o++)if(e[o].status===Yo.SENT_NEEDS_ABORT);else if(e[o].status===Yo.SENT)rn(i===o-1,"All SENT items should be at beginning of queue."),i=o,e[o].status=Yo.SENT_NEEDS_ABORT,e[o].abortReason="set";else if(rn(e[o].status===Yo.RUN,"Unexpected transaction status in abort"),e[o].unwatcher(),r=r.concat(this.serverSyncTree_.ackUserWrite(e[o].currentWriteId,!0)),e[o].onComplete){n.push(e[o].onComplete.bind(null,new Error("set"),!1,null))}-1===i?t.setValue(null):e.length=i+1,this.eventQueue_.raiseEventsForChangedPath(t.path(),r);for(o=0;o<n.length;o++)Cr(n[o])}};var $o,Zo=function(){function t(){this.repos_={},this.useRestClient_=!1}return t.getInstance=function(){return $o||($o=new t),$o},t.prototype.interrupt=function(){for(var t in this.repos_)for(var e in this.repos_[t])this.repos_[t][e].interrupt()},t.prototype.resume=function(){for(var t in this.repos_)for(var e in this.repos_[t])this.repos_[t][e].resume()},t.prototype.databaseFromApp=function(t,e){var n=e||t.options.databaseURL;void 0===n&&fr("Can't determine Firebase Database URL. Be sure to include databaseURL option when calling firebase.initializeApp().");var r=Ur(n),i=r.repoInfo;return Zr("Invalid Firebase Database URL",1,r),r.path.isEmpty()||fr("Database URL must point to the root of a Firebase Database (not including a child path)."),this.createRepo(i,t).database},t.prototype.deleteRepo=function(t){var e=Tn(this.repos_,t.app.name);e&&Tn(e,t.repoInfo_.toURLString())===t||fr("Database "+t.app.name+"("+t.repoInfo_+") has already been deleted."),t.interrupt(),delete e[t.repoInfo_.toURLString()]},t.prototype.createRepo=function(t,e){var n=Tn(this.repos_,e.name);n||(n={},this.repos_[e.name]=n);var r=Tn(n,t.toURLString());return r&&fr("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new Ko(t,this.useRestClient_,e),n[t.toURLString()]=r,r},t.prototype.forceRestClient=function(t){this.useRestClient_=t},t}(),ts=function(){function t(t){this.repo_=t,t instanceof Ko||fr("Don't call new Database() directly - please use firebase.database()."),this.root_=new zo(t,Ar.Empty),this.INTERNAL=new es(this)}return Object.defineProperty(t.prototype,"app",{get:function(){return this.repo_.app},enumerable:!0,configurable:!0}),t.prototype.ref=function(t){return this.checkDeleted_("ref"),Mn("database.ref",0,1,arguments.length),t instanceof zo?this.refFromURL(t.toString()):void 0!==t?this.root_.child(t):this.root_},t.prototype.refFromURL=function(t){var e="database.refFromURL";this.checkDeleted_(e),Mn(e,1,1,arguments.length);var n=Ur(t);Zr(e,1,n);var r=n.repoInfo;return r.host!==this.repo_.repoInfo_.host&&fr(e+": Host name does not match the current database: (found "+r.host+" but expected "+this.repo_.repoInfo_.host+")"),this.ref(n.path.toString())},t.prototype.checkDeleted_=function(t){null===this.repo_&&fr("Cannot call "+t+" on a deleted database.")},t.prototype.goOffline=function(){Mn("database.goOffline",0,0,arguments.length),this.checkDeleted_("goOffline"),this.repo_.interrupt()},t.prototype.goOnline=function(){Mn("database.goOnline",0,0,arguments.length),this.checkDeleted_("goOnline"),this.repo_.resume()},t.ServerValue={TIMESTAMP:{".sv":"timestamp"}},t}(),es=function(){function t(t){this.database=t}return t.prototype.delete=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){return this.database.checkDeleted_("delete"),Zo.getInstance().deleteRepo(this.database.repo_),this.database.repo_=null,this.database.root_=null,this.database.INTERNAL=null,this.database=null,[2]})})},t}(),ns=Object.freeze({forceLongPolling:function(){xo.forceDisallow(),Po.forceAllow()},forceWebSockets:function(){Po.forceDisallow()},isWebSocketsAvailable:function(){return xo.isAvailable()},setSecurityDebugCallback:function(t,e){t.repo.persistentConnection_.securityDebugCallback_=e},stats:function(t,e){t.repo.stats(e)},statsIncrementCounter:function(t,e){t.repo.statsIncrementCounter(e)},dataUpdateCount:function(t){return t.repo.dataUpdateCount},interceptServerData:function(t,e){return t.repo.interceptServerData_(e)}}),rs=Wo;Wo.prototype.simpleListen=function(t,e){this.sendRequest("q",{p:t},e)},Wo.prototype.echo=function(t,e){this.sendRequest("echo",{d:t},e)};var is,os=Uo,ss=Or,as=Object.freeze({DataConnection:rs,RealTimeConnection:os,hijackHash:function(t){var e=Wo.prototype.put;return Wo.prototype.put=function(n,r,i,o){void 0!==o&&(o=t()),e.call(this,n,r,i,o)},function(){Wo.prototype.put=e}},ConnectionTarget:ss,queryIdentifier:function(t){return t.queryIdentifier()},listens:function(t){return t.repo.persistentConnection_.listens_},forceRestClient:function(t){Zo.getInstance().forceRestClient(t)}}),us=ts.ServerValue;is=Gn.INTERNAL.registerService("database",function(t,e,n){return Zo.getInstance().databaseFromApp(t,n)},{Reference:zo,Query:Bi,Database:ts,enableLogging:ur,INTERNAL:ns,ServerValue:us,TEST_ACCESS:as},null,!0),dn()&&(module.exports=is);var cs,hs="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},ls=ls||{},fs=hs;function ps(t){return"string"==typeof t}function ds(t,e){t=t.split("."),e=e||fs;for(var n=0;n<t.length;n++)if(null==(e=e[t[n]]))return null;return e}function ys(){}function ms(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function gs(t){return"array"==ms(t)}function vs(t){var e=ms(t);return"array"==e||"object"==e&&"number"==typeof t.length}function bs(t){return"function"==ms(t)}function _s(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var ws="closure_uid_"+(1e9*Math.random()>>>0),Es=0;function Ts(t,e,n){return t.call.apply(t.bind,arguments)}function Ss(t,e,n){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),t.apply(e,n)}}return function(){return t.apply(e,arguments)}}function Is(t,e,n){return(Is=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Ts:Ss).apply(null,arguments)}function Cs(t,e){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}var Ns=Date.now||function(){return+new Date};function Ds(t,e){function n(){}n.prototype=e.prototype,t.L=e.prototype,t.prototype=new n,t.prototype.constructor=t,t.mh=function(t,n,r){for(var i=Array(arguments.length-2),o=2;o<arguments.length;o++)i[o-2]=arguments[o];return e.prototype[n].apply(t,i)}}function As(t){if(Error.captureStackTrace)Error.captureStackTrace(this,As);else{var e=Error().stack;e&&(this.stack=e)}t&&(this.message=String(t))}function ks(t,e){for(var n="",r=(t=t.split("%s")).length-1,i=0;i<r;i++)n+=t[i]+(i<e.length?e[i]:"%s");As.call(this,n+t[r])}function Rs(){0!=Os&&(Ps[this[ws]||(this[ws]=++Es)]=this),this.Ka=this.Ka,this.Qa=this.Qa}Ds(As,Error),As.prototype.name="CustomError",Ds(ks,As),ks.prototype.name="AssertionError";var Os=0,Ps={};Rs.prototype.Ka=!1,Rs.prototype.bb=function(){if(!this.Ka&&(this.Ka=!0,this.F(),0!=Os)){var t=this[ws]||(this[ws]=++Es);if(0!=Os&&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 Ps[t]}},Rs.prototype.F=function(){if(this.Qa)for(;this.Qa.length;)this.Qa.shift()()};var Ls=Array.prototype.indexOf?function(t,e){return Array.prototype.indexOf.call(t,e,void 0)}:function(t,e){if(ps(t))return ps(e)&&1==e.length?t.indexOf(e,0):-1;for(var n=0;n<t.length;n++)if(n in t&&t[n]===e)return n;return-1},Ms=Array.prototype.lastIndexOf?function(t,e){return Array.prototype.lastIndexOf.call(t,e,t.length-1)}:function(t,e){var n=t.length-1;if(0>n&&(n=Math.max(0,t.length+n)),ps(t))return ps(e)&&1==e.length?t.lastIndexOf(e,n):-1;for(;0<=n;n--)if(n in t&&t[n]===e)return n;return-1},xs=Array.prototype.forEach?function(t,e,n){Array.prototype.forEach.call(t,e,n)}:function(t,e,n){for(var r=t.length,i=ps(t)?t.split(""):t,o=0;o<r;o++)o in i&&e.call(n,i[o],o,t)},Fs=Array.prototype.some?function(t,e){return Array.prototype.some.call(t,e,void 0)}:function(t,e){for(var n=t.length,r=ps(t)?t.split(""):t,i=0;i<n;i++)if(i in r&&e.call(void 0,r[i],i,t))return!0;return!1};function Us(t){if(!gs(t))for(var e=t.length-1;0<=e;e--)delete t[e];t.length=0}function qs(t,e){var n;return(n=0<=(e=Ls(t,e)))&&Array.prototype.splice.call(t,e,1),n}function Bs(t){return Array.prototype.concat.apply([],arguments)}function Vs(t){var e=t.length;if(0<e){for(var n=Array(e),r=0;r<e;r++)n[r]=t[r];return n}return[]}function Ws(t){return/^[\s\xa0]*$/.test(t)}var js,Ks=String.prototype.trim?function(t){return t.trim()}:function(t){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(t)[1]};function Qs(t,e){return t<e?-1:t>e?1:0}t:{var Hs=fs.navigator;if(Hs){var Gs=Hs.userAgent;if(Gs){js=Gs;break t}}js=""}function zs(t){return-1!=js.indexOf(t)}function Ys(t,e,n){for(var r in t)e.call(n,t[r],r,t)}function Xs(t){var e,n=[],r=0;for(e in t)n[r++]=t[e];return n}function Js(t){var e,n=[],r=0;for(e in t)n[r++]=e;return n}function $s(t){var e,n={};for(e in t)n[e]=t[e];return n}var Zs="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ta(t,e){for(var n,r,i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(var o=0;o<Zs.length;o++)n=Zs[o],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function ea(t){return ea[" "](t),t}ea[" "]=ys;var na,ra,ia=zs("Opera"),oa=zs("Trident")||zs("MSIE"),sa=zs("Edge"),aa=sa||oa,ua=zs("Gecko")&&!(-1!=js.toLowerCase().indexOf("webkit")&&!zs("Edge"))&&!(zs("Trident")||zs("MSIE"))&&!zs("Edge"),ca=-1!=js.toLowerCase().indexOf("webkit")&&!zs("Edge");function ha(){var t=fs.document;return t?t.documentMode:void 0}t:{var la="",fa=(ra=js,ua?/rv:([^\);]+)(\)|;)/.exec(ra):sa?/Edge\/([\d\.]+)/.exec(ra):oa?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(ra):ca?/WebKit\/(\S+)/.exec(ra):ia?/(?:Version)[ \/]?(\S+)/.exec(ra):void 0);if(fa&&(la=fa?fa[1]:""),oa){var pa=ha();if(null!=pa&&pa>parseFloat(la)){na=String(pa);break t}}na=la}var da,ya={};function ma(t){return function(t,e){var n=ya;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=e(t)}(t,function(){for(var e=0,n=Ks(String(na)).split("."),r=Ks(String(t)).split("."),i=Math.max(n.length,r.length),o=0;0==e&&o<i;o++){var s=n[o]||"",a=r[o]||"";do{if(s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],a=/(\d*)(\D*)(.*)/.exec(a)||["","","",""],0==s[0].length&&0==a[0].length)break;e=Qs(0==s[1].length?0:parseInt(s[1],10),0==a[1].length?0:parseInt(a[1],10))||Qs(0==s[2].length,0==a[2].length)||Qs(s[2],a[2]),s=s[3],a=a[3]}while(0==e)}return 0<=e})}var ga=fs.document;da=ga&&oa?ha()||("CSS1Compat"==ga.compatMode?parseInt(na,10):5):void 0;var va=Object.freeze||function(t){return t},ba=!oa||9<=Number(da),_a=oa&&!ma("9"),wa=function(){if(!fs.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});try{fs.addEventListener("test",ys,e),fs.removeEventListener("test",ys,e)}catch(t){}return t}();function Ea(t,e){this.type=t,this.currentTarget=this.target=e,this.defaultPrevented=this.Ea=!1,this.Be=!0}function Ta(t,e){Ea.call(this,t?t.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.fb=null,t&&this.Kf(t,e)}Ea.prototype.stopPropagation=function(){this.Ea=!0},Ea.prototype.preventDefault=function(){this.defaultPrevented=!0,this.Be=!1},Ds(Ta,Ea);var Sa=va({2:"touch",3:"pen",4:"mouse"});Ta.prototype.Kf=function(t,e){var n=this.type=t.type,r=t.changedTouches?t.changedTouches[0]:null;if(this.target=t.target||t.srcElement,this.currentTarget=e,e=t.relatedTarget){if(ua){t:{try{ea(e.nodeName);var i=!0;break t}catch(t){}i=!1}i||(e=null)}}else"mouseover"==n?e=t.fromElement:"mouseout"==n&&(e=t.toElement);this.relatedTarget=e,null===r?(this.offsetX=ca||void 0!==t.offsetX?t.offsetX:t.layerX,this.offsetY=ca||void 0!==t.offsetY?t.offsetY:t.layerY,this.clientX=void 0!==t.clientX?t.clientX:t.pageX,this.clientY=void 0!==t.clientY?t.clientY:t.pageY,this.screenX=t.screenX||0,this.screenY=t.screenY||0):(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0),this.button=t.button,this.keyCode=t.keyCode||0,this.key=t.key||"",this.charCode=t.charCode||("keypress"==n?t.keyCode:0),this.ctrlKey=t.ctrlKey,this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.metaKey=t.metaKey,this.pointerId=t.pointerId||0,this.pointerType=ps(t.pointerType)?t.pointerType:Sa[t.pointerType]||"",this.state=t.state,this.fb=t,t.defaultPrevented&&this.preventDefault()},Ta.prototype.stopPropagation=function(){Ta.L.stopPropagation.call(this),this.fb.stopPropagation?this.fb.stopPropagation():this.fb.cancelBubble=!0},Ta.prototype.preventDefault=function(){Ta.L.preventDefault.call(this);var t=this.fb;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,_a)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}};var Ia="closure_listenable_"+(1e6*Math.random()|0);function Ca(t){return!(!t||!t[Ia])}var Na=0;function Da(t,e,n,r,i){this.listener=t,this.proxy=null,this.src=e,this.type=n,this.capture=!!r,this.Ob=i,this.key=++Na,this.Sa=this.Eb=!1}function Aa(t){this.src=t,this.J={},this.xb=0}function ka(t,e,n,r){for(var i=0;i<t.length;++i){var o=t[i];if(!o.Sa&&o.listener==e&&o.capture==!!n&&o.Ob==r)return i}return-1}Da.prototype.Vb=function(){this.Sa=!0,this.Ob=this.src=this.proxy=this.listener=null},(cs=Aa.prototype).add=function(t,e,n,r,i){var o=t.toString();(t=this.J[o])||(t=this.J[o]=[],this.xb++);var s=ka(t,e,r,i);return-1<s?(e=t[s],n||(e.Eb=!1)):((e=new Da(e,this.src,o,!!r,i)).Eb=n,t.push(e)),e},cs.remove=function(t,e,n,r){if(!((t=t.toString())in this.J))return!1;var i=this.J[t];return-1<(e=ka(i,e,n,r))&&(i[e].Vb(),Array.prototype.splice.call(i,e,1),0==i.length&&(delete this.J[t],this.xb--),!0)},cs.ye=function(t){var e=t.type;e in this.J&&qs(this.J[e],t)&&(t.Vb(),0==this.J[e].length&&(delete this.J[e],this.xb--))},cs.pb=function(t){var e;for(e in t=t&&t.toString(),this.J)if(!t||e==t){for(var n=this.J[e],r=0;r<n.length;r++)n[r].Vb();delete this.J[e],this.xb--}},cs.jb=function(t,e,n,r){var i=-1;return(t=this.J[t.toString()])&&(i=ka(t,e,n,r)),-1<i?t[i]:null};var Ra="closure_lm_"+(1e6*Math.random()|0),Oa={};function Pa(t,e,n,r,i){if(r&&r.once)return Ma(t,e,n,r,i);if(gs(e)){for(var o=0;o<e.length;o++)Pa(t,e[o],n,r,i);return null}return n=ja(n),Ca(t)?t.nb(e,n,_s(r)?!!r.capture:!!r,i):La(t,e,n,!1,r,i)}function La(t,e,n,r,i,o){if(!e)throw Error("Invalid event type");var s=_s(i)?!!i.capture:!!i,a=Va(t);if(a||(t[Ra]=a=new Aa(t)),(n=a.add(e,n,r,s,o)).proxy)return n;if(r=function(){var t=Ba,e=ba?function(n){return t.call(e.src,e.listener,n)}:function(n){if(!(n=t.call(e.src,e.listener,n)))return n};return e}(),n.proxy=r,r.src=t,r.listener=n,t.addEventListener)wa||(i=s),void 0===i&&(i=!1),t.addEventListener(e.toString(),r,i);else if(t.attachEvent)t.attachEvent(Fa(e.toString()),r);else{if(!t.addListener||!t.removeListener)throw Error("addEventListener and attachEvent are unavailable.");t.addListener(r)}return n}function Ma(t,e,n,r,i){if(gs(e)){for(var o=0;o<e.length;o++)Ma(t,e[o],n,r,i);return null}return n=ja(n),Ca(t)?t.Oc(e,n,_s(r)?!!r.capture:!!r,i):La(t,e,n,!0,r,i)}function xa(t){if("number"!=typeof t&&t&&!t.Sa){var e=t.src;if(Ca(e))e.Le(t);else{var n=t.type,r=t.proxy;e.removeEventListener?e.removeEventListener(n,r,t.capture):e.detachEvent?e.detachEvent(Fa(n),r):e.addListener&&e.removeListener&&e.removeListener(r),(n=Va(e))?(n.ye(t),0==n.xb&&(n.src=null,e[Ra]=null)):t.Vb()}}}function Fa(t){return t in Oa?Oa[t]:Oa[t]="on"+t}function Ua(t,e,n,r){var i=!0;if((t=Va(t))&&(e=t.J[e.toString()]))for(e=e.concat(),t=0;t<e.length;t++){var o=e[t];o&&o.capture==n&&!o.Sa&&(o=qa(o,r),i=i&&!1!==o)}return i}function qa(t,e){var n=t.listener,r=t.Ob||t.src;return t.Eb&&xa(t),n.call(r,e)}function Ba(t,e){if(t.Sa)return!0;if(!ba){var n=e||ds("window.event");e=new Ta(n,this);var r=!0;if(!(0>n.keyCode||void 0!=n.returnValue)){t:{var i=!1;if(0==n.keyCode)try{n.keyCode=-1;break t}catch(t){i=!0}(i||void 0==n.returnValue)&&(n.returnValue=!0)}for(n=[],i=e.currentTarget;i;i=i.parentNode)n.push(i);for(t=t.type,i=n.length-1;!e.Ea&&0<=i;i--){e.currentTarget=n[i];var o=Ua(n[i],t,!0,e);r=r&&o}for(i=0;!e.Ea&&i<n.length;i++)e.currentTarget=n[i],o=Ua(n[i],t,!1,e),r=r&&o}return r}return qa(t,new Ta(e,this))}function Va(t){return(t=t[Ra])instanceof Aa?t:null}var Wa="__closure_events_fn_"+(1e9*Math.random()>>>0);function ja(t){return bs(t)?t:(t[Wa]||(t[Wa]=function(e){return t.handleEvent(e)}),t[Wa])}function Ka(){Rs.call(this),this.ka=new Aa(this),this.Pe=this,this.Uc=null}Ds(Ka,Rs),Ka.prototype[Ia]=!0,(cs=Ka.prototype).addEventListener=function(t,e,n,r){Pa(this,t,e,n,r)},cs.removeEventListener=function(t,e,n,r){!function t(e,n,r,i,o){if(gs(n))for(var s=0;s<n.length;s++)t(e,n[s],r,i,o);else i=_s(i)?!!i.capture:!!i,r=ja(r),Ca(e)?e.ed(n,r,i,o):e&&(e=Va(e))&&(n=e.jb(n,r,i,o))&&xa(n)}(this,t,e,n,r)},cs.dispatchEvent=function(t){var e,n=this.Uc;if(n)for(e=[];n;n=n.Uc)e.push(n);n=this.Pe;var r=t.type||t;if(ps(t))t=new Ea(t,n);else if(t instanceof Ea)t.target=t.target||n;else{var i=t;ta(t=new Ea(r,n),i)}if(i=!0,e)for(var o=e.length-1;!t.Ea&&0<=o;o--){var s=t.currentTarget=e[o];i=s.Lb(r,!0,t)&&i}if(t.Ea||(i=(s=t.currentTarget=n).Lb(r,!0,t)&&i,t.Ea||(i=s.Lb(r,!1,t)&&i)),e)for(o=0;!t.Ea&&o<e.length;o++)i=(s=t.currentTarget=e[o]).Lb(r,!1,t)&&i;return i},cs.F=function(){Ka.L.F.call(this),this.pg(),this.Uc=null},cs.nb=function(t,e,n,r){return this.ka.add(String(t),e,!1,n,r)},cs.Oc=function(t,e,n,r){return this.ka.add(String(t),e,!0,n,r)},cs.ed=function(t,e,n,r){this.ka.remove(String(t),e,n,r)},cs.Le=function(t){this.ka.ye(t)},cs.pg=function(){this.ka&&this.ka.pb(void 0)},cs.Lb=function(t,e,n){if(!(t=this.ka.J[String(t)]))return!0;t=t.concat();for(var r=!0,i=0;i<t.length;++i){var o=t[i];if(o&&!o.Sa&&o.capture==e){var s=o.listener,a=o.Ob||o.src;o.Eb&&this.Le(o),r=!1!==s.call(a,n)&&r}}return r&&0!=n.Be},cs.jb=function(t,e,n,r){return this.ka.jb(String(t),e,n,r)};var Qa=fs.JSON.stringify;function Ha(t,e){this.Sf=100,this.ef=t,this.ug=e,this.Zb=0,this.Pb=null}function Ga(){this.lc=this.Va=null}Ha.prototype.get=function(){if(0<this.Zb){this.Zb--;var t=this.Pb;this.Pb=t.next,t.next=null}else t=this.ef();return t},Ha.prototype.put=function(t){this.ug(t),this.Zb<this.Sf&&(this.Zb++,t.next=this.Pb,this.Pb=t)};var za,Ya,Xa=new Ha(function(){return new Ja},function(t){t.reset()});function Ja(){this.next=this.scope=this.Gc=null}function $a(t){fs.setTimeout(function(){throw t},0)}function Za(){if(fs.Promise&&fs.Promise.resolve){var t=fs.Promise.resolve(void 0);Ya=function(){t.then(nu)}}else Ya=function(){var t=nu;!bs(fs.setImmediate)||fs.Window&&fs.Window.prototype&&!zs("Edge")&&fs.Window.prototype.setImmediate==fs.setImmediate?(za||(za=function(){var t=fs.MessageChannel;if(void 0===t&&"undefined"!=typeof window&&window.postMessage&&window.addEventListener&&!zs("Presto")&&(t=function(){var t=document.createElement("IFRAME");t.style.display="none",t.src="",document.documentElement.appendChild(t);var e=t.contentWindow;(t=e.document).open(),t.write(""),t.close();var n="callImmediate"+Math.random(),r="file:"==e.location.protocol?"*":e.location.protocol+"//"+e.location.host;t=Is(function(t){"*"!=r&&t.origin!=r||t.data!=n||this.port1.onmessage()},this),e.addEventListener("message",t,!1),this.port1={},this.port2={postMessage:function(){e.postMessage(n,r)}}}),void 0!==t&&!zs("Trident")&&!zs("MSIE")){var e=new t,n={},r=n;return e.port1.onmessage=function(){if(void 0!==n.next){var t=(n=n.next).rd;n.rd=null,t()}},function(t){r.next={rd:t},r=r.next,e.port2.postMessage(0)}}return"undefined"!=typeof document&&"onreadystatechange"in document.createElement("SCRIPT")?function(t){var e=document.createElement("SCRIPT");e.onreadystatechange=function(){e.onreadystatechange=null,e.parentNode.removeChild(e),e=null,t(),t=null},document.documentElement.appendChild(e)}:function(t){fs.setTimeout(t,0)}}()),za(t)):fs.setImmediate(t)}}Ga.prototype.add=function(t,e){var n=this.Af();n.set(t,e),this.lc?this.lc.next=n:this.Va=n,this.lc=n},Ga.prototype.remove=function(){var t=null;return this.Va&&(t=this.Va,this.Va=this.Va.next,this.Va||(this.lc=null),t.next=null),t},Ga.prototype.wg=function(t){Xa.put(t)},Ga.prototype.Af=function(){return Xa.get()},Ja.prototype.set=function(t,e){this.Gc=t,this.scope=e,this.next=null},Ja.prototype.reset=function(){this.next=this.scope=this.Gc=null};var tu=!1,eu=new Ga;function nu(){for(var t;t=eu.remove();){try{t.Gc.call(t.scope)}catch(t){$a(t)}eu.wg(t)}tu=!1}function ru(t,e){Ka.call(this),this.Na=t||1,this.wb=e||fs,this.nd=Is(this.Rg,this),this.ie=Ns()}function iu(t,e,n){if(bs(t))n&&(t=Is(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=Is(t.handleEvent,t)}return 2147483647<Number(e)?-1:fs.setTimeout(t,e||0)}function ou(t,e,n){Rs.call(this),this.Uf=null!=n?Is(t,n):t,this.Na=e,this.Xe=Is(this.fg,this),this.qc=[]}function su(t){Rs.call(this),this.i=t,this.o={}}Ds(ru,Ka),(cs=ru.prototype).enabled=!1,cs.B=null,cs.setInterval=function(t){this.Na=t,this.B&&this.enabled?(this.stop(),this.start()):this.B&&this.stop()},cs.Rg=function(){if(this.enabled){var t=Ns()-this.ie;0<t&&t<.8*this.Na?this.B=this.wb.setTimeout(this.nd,this.Na-t):(this.B&&(this.wb.clearTimeout(this.B),this.B=null),this.ff(),this.enabled&&(this.stop(),this.start()))}},cs.ff=function(){this.dispatchEvent("tick")},cs.start=function(){this.enabled=!0,this.B||(this.B=this.wb.setTimeout(this.nd,this.Na),this.ie=Ns())},cs.stop=function(){this.enabled=!1,this.B&&(this.wb.clearTimeout(this.B),this.B=null)},cs.F=function(){ru.L.F.call(this),this.stop(),delete this.wb},Ds(ou,Rs),(cs=ou.prototype).Ta=!1,cs.ob=0,cs.B=null,cs.mf=function(t){this.qc=arguments,this.B||this.ob?this.Ta=!0:this.Cc()},cs.stop=function(){this.B&&(fs.clearTimeout(this.B),this.B=null,this.Ta=!1,this.qc=[])},cs.pause=function(){this.ob++},cs.resume=function(){this.ob--,this.ob||!this.Ta||this.B||(this.Ta=!1,this.Cc())},cs.F=function(){ou.L.F.call(this),this.stop()},cs.fg=function(){this.B=null,this.Ta&&!this.ob&&(this.Ta=!1,this.Cc())},cs.Cc=function(){this.B=iu(this.Xe,this.Na),this.Uf.apply(null,this.qc)},Ds(su,Rs);var au=[];function uu(t,e,n){this.reset(t,e,n,void 0,void 0)}function cu(t){this.pe=t,this.Zd=this.uc=this.mb=this.$b=null}function hu(t,e){this.name=t,this.value=e}(cs=su.prototype).nb=function(t,e,n,r){return this.Tf(t,e,n,r)},cs.Tf=function(t,e,n,r){gs(e)||(e&&(au[0]=e.toString()),e=au);for(var i=0;i<e.length;i++){var o=Pa(t,e[i],n||this.handleEvent,r||!1,this.i||this);if(!o)break;this.o[o.key]=o}return this},cs.Oc=function(t,e,n,r){return this.je(t,e,n,r)},cs.je=function(t,e,n,r,i){if(gs(e))for(var o=0;o<e.length;o++)this.je(t,e[o],n,r,i);else{if(!(t=Ma(t,e,n||this.handleEvent,r,i||this.i||this)))return this;this.o[t.key]=t}return this},cs.ed=function(t,e,n,r,i){if(gs(e))for(var o=0;o<e.length;o++)this.ed(t,e[o],n,r,i);else n=n||this.handleEvent,r=_s(r)?!!r.capture:!!r,i=i||this.i||this,n=ja(n),r=!!r,(e=Ca(t)?t.jb(e,n,r,i):t&&(t=Va(t))?t.jb(e,n,r,i):null)&&(xa(e),delete this.o[e.key])},cs.pb=function(){Ys(this.o,function(t,e){this.o.hasOwnProperty(e)&&xa(t)},this),this.o={}},cs.F=function(){su.L.F.call(this),this.pb()},cs.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},uu.prototype.Md=null,uu.prototype.reset=function(t,e,n,r,i){this.mb=t,delete this.Md},uu.prototype.Bg=function(t){this.Md=t},uu.prototype.Ge=function(t){this.mb=t},hu.prototype.toString=function(){return this.name};var lu=new hu("SEVERE",1e3),fu=new hu("WARNING",900),pu=new hu("INFO",800),du=new hu("CONFIG",700),yu=new hu("FINE",500);(cs=cu.prototype).getName=function(){return this.pe},cs.getParent=function(){return this.$b},cs.pf=function(){return this.uc||(this.uc={}),this.uc},cs.Ge=function(t){this.mb=t},cs.Qd=function(){return this.mb?this.mb:this.$b?this.$b.Qd():(function(t,e){throw new ks("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}("Root logger has no level set."),null)},cs.Pf=function(t){return t.value>=this.Qd().value},cs.log=function(t,e,n){this.Pf(t)&&(bs(e)&&(e=e()),this.gf(this.uf(t,e,n)))},cs.uf=function(t,e,n){return t=new uu(t,String(e),this.pe),n&&t.Bg(n),t},cs.ca=function(t,e){this.log(lu,t,e)},cs.T=function(t,e){this.log(fu,t,e)},cs.info=function(t,e){this.log(pu,t,e)},cs.lf=function(t){this.log(yu,t,void 0)},cs.gf=function(t){for(var e=this;e;)e.We(t),e=e.getParent()},cs.We=function(t){if(this.Zd)for(var e,n=0;e=this.Zd[n];n++)e(t)},cs.Fg=function(t){this.$b=t},cs.Qe=function(t,e){this.pf()[t]=e};var mu={},gu=null;function vu(t){var e;if(gu||(gu=new cu(""),mu[""]=gu,gu.Ge(du)),!(e=mu[t])){e=new cu(t);var n=t.lastIndexOf("."),r=t.substr(n+1);(n=vu(t.substr(0,n))).Qe(r,e),e.Fg(n),mu[t]=e}return e}function bu(t,e){t&&t.info(e,void 0)}function _u(t,e){t&&t.lf(e)}function wu(){this.s=vu("goog.labs.net.webChannel.WebChannelDebug"),this.Wc=!0}(cs=wu.prototype).Id=function(){this.Wc=!1},cs.Tg=function(t,e,n,r,i){var o=this;this.info(function(){return"XMLHTTP REQ ("+n+") [attempt "+r+"]: "+t+"\n"+e+"\n"+o.Xf(i)})},cs.Ug=function(t,e,n,r,i,o){this.info(function(){return"XMLHTTP RESP ("+n+") [ attempt "+r+"]: "+t+"\n"+e+"\n"+i+" "+o})},cs.Wa=function(t,e,n){var r=this;this.info(function(){return"XMLHTTP TEXT ("+t+"): "+r.ng(e)+(n?" "+n:"")})},cs.Sg=function(t){this.info(function(){return"TIMEOUT: "+t})},cs.debug=function(t){_u(this.s,t)},cs.cb=function(t,e){var n=this.s;n&&n.ca(e||"Exception",t)},cs.info=function(t){bu(this.s,t)},cs.T=function(t){var e=this.s;e&&e.T(t,void 0)},cs.ca=function(t){var e=this.s;e&&e.ca(t,void 0)},cs.ng=function(t){if(!this.Wc)return t;if(!t)return null;try{var e=JSON.parse(t);if(e)for(var n=0;n<e.length;n++)gs(e[n])&&this.Wf(e[n]);return Qa(e)}catch(e){return this.debug("Exception parsing expected JS array - probably was not JS"),t}},cs.Wf=function(t){if(!(2>t.length||(t=t[1],!gs(t)||1>t.length))){var e=t[0];if("noop"!=e&&"stop"!=e&&"close"!=e)for(e=1;e<t.length;e++)t[e]=""}},cs.Xf=function(t){if(!this.Wc)return t;if(!t)return null;var e="";t=t.split("&");for(var n=0;n<t.length;n++){var r=t[n].split("=");if(1<r.length){var i=r[0];r=r[1];var o=i.split("_");e=2<=o.length&&"type"==o[1]?e+(i+"=")+r+"&":e+(i+"=redacted&")}}return e};var Eu=new Ka;function Tu(t){Ea.call(this,"serverreachability",t)}function Su(t){Eu.dispatchEvent(new Tu(Eu,t))}function Iu(t,e){Ea.call(this,"statevent",t),this.stat=e}function Cu(t){Eu.dispatchEvent(new Iu(Eu,t))}function Nu(t,e,n){Ea.call(this,"timingevent",t),this.size=e,this.rtt=n}function Du(t,e){if(!bs(t))throw Error("Fn must not be null and must be a function");return fs.setTimeout(function(){t()},e)}Ds(Tu,Ea),Ds(Iu,Ea),Ds(Nu,Ea);var Au={NO_ERROR:0,Vg:1,bh:2,ah:3,Yg:4,$g:5,dh:6,Ne:7,TIMEOUT:8,gh:9},ku={Xg:"complete",kh:"success",Oe:"error",Ne:"abort",ih:"ready",jh:"readystatechange",TIMEOUT:"timeout",eh:"incrementaldata",hh:"progress",Zg:"downloadprogress",lh:"uploadprogress"};function Ru(){}function Ou(){}Ru.prototype.pd=null,Ru.prototype.Vd=function(){return this.pd||(this.pd=this.Mf())};var Pu,Lu={OPEN:"a",Wg:"b",Oe:"c",fh:"d"};function Mu(){Ea.call(this,"d")}function xu(){Ea.call(this,"c")}function Fu(){}function Uu(t,e,n,r,i){this.b=t,this.a=e,this.ra=n,this.R=r,this.Xc=i||1,this.Fc=new su(this),this.Ua=qu,t=aa?125:void 0,this.Vc=new ru(t),this.A=null,this.S=!1,this.Da=this.pa=this.ua=this.ic=this.qb=this.hd=this.Ga=null,this.ba=[],this.h=null,this.Bb=0,this.I=this.Fa=null,this.w=-1,this.Za=!1,this.Ra=0,this.ac=null,this.lb=this.Ed=this.yc=!1}Ds(Mu,Ea),Ds(xu,Ea),Ds(Fu,Ru),Fu.prototype.Dd=function(){var t=this.Wd();return t?new ActiveXObject(t):new XMLHttpRequest},Fu.prototype.Mf=function(){var t={};return this.Wd()&&(t[0]=!0,t[1]=!0),t},Fu.prototype.Wd=function(){if(!this.be&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var t=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],e=0;e<t.length;e++){var n=t[e];try{return new ActiveXObject(n),this.be=n}catch(t){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed")}return this.be},Pu=new Fu;var qu=45e3;var Bu={},Vu={};function Wu(t){if(t.H&&"function"==typeof t.H)return t.H();if(ps(t))return t.split("");if(vs(t)){for(var e=[],n=t.length,r=0;r<n;r++)e.push(t[r]);return e}return Xs(t)}function ju(t,e,n){if(t.forEach&&"function"==typeof t.forEach)t.forEach(e,n);else if(vs(t)||ps(t))xs(t,e,n);else{if(t.W&&"function"==typeof t.W)var r=t.W();else if(t.H&&"function"==typeof t.H)r=void 0;else if(vs(t)||ps(t)){r=[];for(var i=t.length,o=0;o<i;o++)r.push(o)}else r=Js(t);o=(i=Wu(t)).length;for(var s=0;s<o;s++)e.call(n,i[s],r&&r[s],t)}}function Ku(t,e){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 t&&this.addAll(t)}function Qu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}(cs=Uu.prototype).ga=function(t){this.A=t},cs.setTimeout=function(t){this.Ua=t},cs.He=function(t){this.Ra=t},cs.Gg=function(t){this.ba=t},cs.la=function(){return this.ba},cs.kd=function(t,e){this.ic=1,this.ua=t.clone().Ub(),this.Da=e,this.yc=!0,this.Ce(null)},cs.jd=function(t,e,n){this.ic=1,this.ua=t.clone().Ub(),this.Da=null,this.yc=e,this.Ce(n)},cs.Ce=function(t){this.qb=Ns(),this.eb(),this.pa=this.ua.clone(),this.pa.dc("t",this.Xc),this.Bb=0,this.h=this.b.Jb(this.b.fc()?t:null),0<this.Ra&&(this.ac=new ou(Is(this.Me,this,this.h),this.Ra)),this.Fc.nb(this.h,"readystatechange",this.mg),t=this.A?$s(this.A):{},this.Da?(this.Fa||(this.Fa="POST"),t["Content-Type"]="application/x-www-form-urlencoded",this.h.send(this.pa,this.Fa,this.Da,t)):(this.Fa="GET",this.h.send(this.pa,this.Fa,null,t)),Su(1),this.a.Tg(this.Fa,this.pa,this.R,this.Xc,this.Da)},cs.mg=function(t){t=t.target;var e=this.ac;e&&3==t.ma()?(this.a.debug("Throttling readystatechange."),e.mf()):this.Me(t)},cs.Me=function(t){try{t==this.h?this.hg():this.a.T("Called back with an unexpected xmlhttp")}catch(t){if(this.a.debug("Failed call to OnXmlHttpReadyStateChanged_"),this.h&&this.h.ya()){var e=this;this.a.cb(t,function(){return"ResponseText: "+e.h.ya()})}else this.a.cb(t,"No response text")}},cs.hg=function(){var t=this.h.ma(),e=this.h.Ud(),n=this.h.za();if(!(3>t||3==t&&!aa&&!this.h.ya())){this.Za||4!=t||7==e||Su(8==e||0>=n?3:2),this.Fb();var r=this.h.za();if(this.w=r,!(e=this.h.ya())){var i=this;this.a.debug(function(){return"No response text for uri "+i.pa+" status "+r})}if(this.S=200==r,this.a.Ug(this.Fa,this.pa,this.R,this.Xc,t,r),this.S){if(this.Ig()){if(!(n=this.sf()))return this.S=!1,this.I=3,Cu(12),this.a.T("XMLHTTP Missing X_HTTP_INITIAL_RESPONSE ("+this.R+")"),this.Ia(),void this.Kb();this.a.Wa(this.R,n,"Initial handshake response via X-HTTP-Initial-Response"),this.lb=!0,this.Yc(n)}this.yc?(this.Fd(t,e),aa&&this.S&&3==t&&this.Ng()):(this.a.Wa(this.R,e,null),this.Yc(e)),4==t&&this.Ia(),this.S&&!this.Za&&(4==t?this.b.Tc(this):(this.S=!1,this.eb()))}else 400==r&&0<e.indexOf("Unknown SID")?(this.I=3,Cu(12),this.a.T("XMLHTTP Unknown SID ("+this.R+")")):(this.I=0,Cu(13),this.a.T("XMLHTTP Bad status "+r+" ("+this.R+")")),this.Ia(),this.Kb()}},cs.Ig=function(){return this.Ed&&!this.lb},cs.sf=function(){if(this.h){var t=this.h.kb("X-HTTP-Initial-Response");if(t&&!Ws(t))return t}return null},cs.Ag=function(){this.Ed=!0},cs.Fd=function(t,e){for(var n=!0;!this.Za&&this.Bb<e.length;){var r=this.vf(e);if(r==Vu){4==t&&(this.I=4,Cu(14),n=!1),this.a.Wa(this.R,null,"[Incomplete Response]");break}if(r==Bu){this.I=4,Cu(15),this.a.Wa(this.R,e,"[Invalid Chunk]"),n=!1;break}this.a.Wa(this.R,r,null),this.Yc(r)}4==t&&0==e.length&&(this.I=1,Cu(16),n=!1),this.S=this.S&&n,n||(this.a.Wa(this.R,e,"[Invalid Chunked Response]"),this.Ia(),this.Kb())},cs.kg=function(){if(this.h){var t=this.h.ma(),e=this.h.ya();this.Bb<e.length&&(this.Fb(),this.Fd(t,e),this.S&&4!=t&&this.eb())}},cs.Ng=function(){this.Fc.nb(this.Vc,"tick",this.kg),this.Vc.start()},cs.vf=function(t){var e=this.Bb,n=t.indexOf("\n",e);return-1==n?Vu:(e=Number(t.substring(e,n)),isNaN(e)?Bu:(n+=1)+e>t.length?Vu:(t=t.substr(n,e),this.Bb=n+e,t))},cs.yg=function(t){this.ic=2,this.ua=t.clone().Ub(),t=!1,fs.navigator&&fs.navigator.sendBeacon&&(t=fs.navigator.sendBeacon(this.ua.toString(),"")),!t&&fs.Image&&((new Image).src=this.ua,t=!0),t||(this.h=this.b.Jb(null),this.h.send(this.ua)),this.qb=Ns(),this.eb()},cs.cancel=function(){this.Za=!0,this.Ia()},cs.tg=function(t){t&&this.setTimeout(t),this.Ga&&(this.Fb(),this.eb())},cs.eb=function(){this.hd=Ns()+this.Ua,this.Ke(this.Ua)},cs.Ke=function(t){if(null!=this.Ga)throw Error("WatchDog timer not null");this.Ga=Du(Is(this.gg,this),t)},cs.Fb=function(){this.Ga&&(fs.clearTimeout(this.Ga),this.Ga=null)},cs.gg=function(){this.Ga=null;var t=Ns();0<=t-this.hd?this.Df():(this.a.T("WatchDog timer called too early"),this.Ke(this.hd-t))},cs.Df=function(){this.S&&this.a.ca("Received watchdog timeout even though request loaded successfully"),this.a.Sg(this.pa),2!=this.ic&&(Su(3),Cu(17)),this.Ia(),this.I=2,this.Kb()},cs.Kb=function(){this.b.de()||this.Za||this.b.Tc(this)},cs.Ia=function(){this.Fb();var t=this.ac;t&&"function"==typeof t.bb&&t.bb(),this.ac=null,this.Vc.stop(),this.Fc.pb(),this.h&&(t=this.h,this.h=null,t.abort(),t.bb())},cs.Hc=function(){return this.I},cs.Yc=function(t){try{this.b.ue(this,t),Su(4)}catch(t){this.a.cb(t,"Error in httprequest callback")}},(cs=Ku.prototype).C=function(){return this.j},cs.H=function(){this.wc();for(var t=[],e=0;e<this.o.length;e++)t.push(this.D[this.o[e]]);return t},cs.W=function(){return this.wc(),this.o.concat()},cs.va=function(t){return Qu(this.D,t)},cs.X=function(){return 0==this.j},cs.clear=function(){this.D={},this.j=this.o.length=0},cs.remove=function(t){return!!Qu(this.D,t)&&(delete this.D[t],this.j--,this.o.length>2*this.j&&this.wc(),!0)},cs.wc=function(){if(this.j!=this.o.length){for(var t=0,e=0;t<this.o.length;){var n=this.o[t];Qu(this.D,n)&&(this.o[e++]=n),t++}this.o.length=e}if(this.j!=this.o.length){var r={};for(e=t=0;t<this.o.length;)Qu(r,n=this.o[t])||(this.o[e++]=n,r[n]=1),t++;this.o.length=e}},cs.get=function(t,e){return Qu(this.D,t)?this.D[t]:e},cs.set=function(t,e){Qu(this.D,t)||(this.j++,this.o.push(t)),this.D[t]=e},cs.addAll=function(t){if(t instanceof Ku)for(var e=t.W(),n=0;n<e.length;n++)this.set(e[n],t.get(e[n]));else for(e in t)this.set(e,t[e])},cs.forEach=function(t,e){for(var n=this.W(),r=0;r<n.length;r++){var i=n[r],o=this.get(i);t.call(e,o,i,this)}},cs.clone=function(){return new Ku(this)};var Hu=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Gu(t,e){var n;this.xa=this.zb=this.qa="",this.Ca=null,this.ib=this.K="",this.O=this.Qf=!1,t instanceof Gu?(this.O=void 0!==e?e:t.O,this.tb(t.qa),this.cd(t.zb),this.rb(t.xa),this.sb(t.Ca),this.ec(t.K),this.bd(t.P.clone()),this.$c(t.ib)):t&&(n=String(t).match(Hu))?(this.O=!!e,this.tb(n[1]||"",!0),this.cd(n[2]||"",!0),this.rb(n[3]||"",!0),this.sb(n[4]),this.ec(n[5]||"",!0),this.bd(n[6]||"",!0),this.$c(n[7]||"",!0)):(this.O=!!e,this.P=new nc(null,this.O))}function zu(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function Yu(t,e,n){return ps(t)?(t=encodeURI(t).replace(e,Xu),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function Xu(t){return"%"+((t=t.charCodeAt(0))>>4&15).toString(16)+(15&t).toString(16)}(cs=Gu.prototype).toString=function(){var t=[],e=this.qa;e&&t.push(Yu(e,Ju,!0),":");var n=this.xa;return(n||"file"==e)&&(t.push("//"),(e=this.zb)&&t.push(Yu(e,Ju,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.Ca)&&t.push(":",String(n))),(n=this.K)&&(this.Ic()&&"/"!=n.charAt(0)&&t.push("/"),t.push(Yu(n,"/"==n.charAt(0)?Zu:$u,!0))),(n=this.Rd())&&t.push("?",n),(n=this.ib)&&t.push("#",Yu(n,ec)),t.join("")},cs.resolve=function(t){var e=this.clone(),n=t.Hf();n?e.tb(t.qa):n=t.If(),n?e.cd(t.zb):n=t.Ic(),n?e.rb(t.xa):n=t.Ff();var r=t.K;if(n)e.sb(t.Ca);else if(n=t.ae()){if("/"!=r.charAt(0))if(this.Ic()&&!this.ae())r="/"+r;else{var i=e.K.lastIndexOf("/");-1!=i&&(r=e.K.substr(0,i+1)+r)}if(".."==(i=r)||"."==i)r="";else if(-1!=i.indexOf("./")||-1!=i.indexOf("/.")){r=0==i.lastIndexOf("/",0),i=i.split("/");for(var o=[],s=0;s<i.length;){var a=i[s++];"."==a?r&&s==i.length&&o.push(""):".."==a?((1<o.length||1==o.length&&""!=o[0])&&o.pop(),r&&s==i.length&&o.push("")):(o.push(a),r=!0)}r=o.join("/")}else r=i}return n?e.ec(r):n=t.Gf(),n?e.bd(t.P.clone()):n=t.Ef(),n&&e.$c(t.ib),e},cs.clone=function(){return new Gu(this)},cs.tb=function(t,e){this.U(),(this.qa=e?zu(t,!0):t)&&(this.qa=this.qa.replace(/:$/,""))},cs.Hf=function(){return!!this.qa},cs.cd=function(t,e){this.U(),this.zb=e?zu(t):t},cs.If=function(){return!!this.zb},cs.rb=function(t,e){this.U(),this.xa=e?zu(t,!0):t},cs.Ic=function(){return!!this.xa},cs.sb=function(t){if(this.U(),t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);this.Ca=t}else this.Ca=null},cs.Ff=function(){return null!=this.Ca},cs.ec=function(t,e){this.U(),this.K=e?zu(t,!0):t},cs.ae=function(){return!!this.K},cs.Gf=function(){return""!==this.P.toString()},cs.bd=function(t,e){this.U(),t instanceof nc?(this.P=t,this.P.ad(this.O)):(e||(t=Yu(t,tc)),this.P=new nc(t,this.O))},cs.Rd=function(){return this.P.toString()},cs.getQuery=function(){return this.Rd()},cs.l=function(t,e){this.U(),this.P.set(t,e)},cs.dc=function(t,e){this.U(),gs(e)||(e=[String(e)]),this.P.Ie(t,e)},cs.$c=function(t,e){this.U(),this.ib=e?zu(t):t},cs.Ef=function(){return!!this.ib},cs.Ub=function(){return this.U(),this.l("zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Ns()).toString(36)),this},cs.removeParameter=function(t){return this.U(),this.P.remove(t),this},cs.U=function(){if(this.Qf)throw Error("Tried to modify a read-only Uri")},cs.ad=function(t){this.O=t,this.P&&this.P.ad(t)};var Ju=/[#\/\?@]/g,$u=/[#\?:]/g,Zu=/[#\?]/g,tc=/[#\?@]/g,ec=/#/g;function nc(t,e){this.j=this.m=null,this.ja=t||null,this.O=!!e}function rc(t,e){this.b=t,this.a=e,this.f=this.A=null,this.bc=!1,this.K=null,this.w=-1,this.Ad=this.na=null}function ic(t){this.D=new Ku,t&&this.addAll(t)}function oc(t){var e=typeof t;return"object"==e&&t||"function"==e?"o"+(t[ws]||(t[ws]=++Es)):e.substr(0,1)+t}function sc(t){this.me=t||ac,fs.PerformanceNavigationTiming?t=0<(t=fs.performance.getEntriesByType("navigation")).length&&("hq"==t[0].nextHopProtocol||"h2"==t[0].nextHopProtocol):t=!!(fs.vc&&fs.vc.ke&&fs.vc.ke()&&fs.vc.ke().nh),this.Xb=t?this.me:1,this.v=null,1<this.Xb&&(this.v=new ic),this.f=null,this.ba=[]}(cs=nc.prototype).$=function(){if(!this.m&&(this.m=new Ku,this.j=0,this.ja)){var t=this;!function(t,e){if(t){t=t.split("&");for(var n=0;n<t.length;n++){var r=t[n].indexOf("="),i=null;if(0<=r){var o=t[n].substring(0,r);i=t[n].substring(r+1)}else o=t[n];e(o,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(this.ja,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)})}},cs.C=function(){return this.$(),this.j},cs.add=function(t,e){this.$(),this.Oa(),t=this.Ma(t);var n=this.m.get(t);return n||this.m.set(t,n=[]),n.push(e),this.j+=1,this},cs.remove=function(t){return this.$(),t=this.Ma(t),!!this.m.va(t)&&(this.Oa(),this.j-=this.m.get(t).length,this.m.remove(t))},cs.clear=function(){this.Oa(),this.m=null,this.j=0},cs.X=function(){return this.$(),0==this.j},cs.va=function(t){return this.$(),t=this.Ma(t),this.m.va(t)},cs.forEach=function(t,e){this.$(),this.m.forEach(function(n,r){xs(n,function(n){t.call(e,n,r,this)},this)},this)},cs.W=function(){this.$();for(var t=this.m.H(),e=this.m.W(),n=[],r=0;r<e.length;r++)for(var i=t[r],o=0;o<i.length;o++)n.push(e[r]);return n},cs.H=function(t){this.$();var e=[];if(ps(t))this.va(t)&&(e=Bs(e,this.m.get(this.Ma(t))));else{t=this.m.H();for(var n=0;n<t.length;n++)e=Bs(e,t[n])}return e},cs.set=function(t,e){return this.$(),this.Oa(),t=this.Ma(t),this.va(t)&&(this.j-=this.m.get(t).length),this.m.set(t,[e]),this.j+=1,this},cs.get=function(t,e){return t&&0<(t=this.H(t)).length?String(t[0]):e},cs.Ie=function(t,e){this.remove(t),0<e.length&&(this.Oa(),this.m.set(this.Ma(t),Vs(e)),this.j+=e.length)},cs.toString=function(){if(this.ja)return this.ja;if(!this.m)return"";for(var t=[],e=this.m.W(),n=0;n<e.length;n++){var r=e[n],i=encodeURIComponent(String(r));r=this.H(r);for(var o=0;o<r.length;o++){var s=i;""!==r[o]&&(s+="="+encodeURIComponent(String(r[o]))),t.push(s)}}return this.ja=t.join("&")},cs.Oa=function(){this.ja=null},cs.clone=function(){var t=new nc;return t.ja=this.ja,this.m&&(t.m=this.m.clone(),t.j=this.j),t},cs.Ma=function(t){return t=String(t),this.O&&(t=t.toLowerCase()),t},cs.ad=function(t){t&&!this.O&&(this.$(),this.Oa(),this.m.forEach(function(t,e){var n=e.toLowerCase();e!=n&&(this.remove(e),this.Ie(n,t))},this)),this.O=t},cs.extend=function(t){for(var e=0;e<arguments.length;e++)ju(arguments[e],function(t,e){this.add(e,t)},this)},Ds(function(){},function(){}),(cs=rc.prototype).g=null,cs.ga=function(t){this.A=t},cs.connect=function(t){this.K=t,t=this.b.Sd(this.K),Cu(3);var e=this.b.Ib.$d;null!=e?(this.na=this.b.$a(e[0]),this.g=1,this.xd()):(t.dc("MODE","init"),!this.b.ta&&this.b.aa&&t.dc("X-HTTP-Session-Id",this.b.aa),this.f=new Uu(this,this.a,void 0,void 0,void 0),this.f.ga(this.A),this.f.jd(t,!1,null),this.g=0)},cs.xd=function(){this.a.debug("TestConnection: starting stage 2");var t=this.b.Ib.od;if(null!=t)this.a.debug(function(){return"Buffered"}),Cu(4),t?(Cu(10),this.b.ub(this,!1)):(Cu(11),this.b.ub(this,!0));else{this.f=new Uu(this,this.a,void 0,void 0,void 0),this.f.ga(this.A);var e=this.b.Pd(this.na,this.K);Cu(4),e.dc("TYPE","xmlhttp");var n=this.b.aa,r=this.b.Kc;n&&r&&e.l(n,r),this.f.jd(e,!1,this.na)}},cs.Jb=function(t){return this.b.Jb(t)},cs.abort=function(){this.f&&(this.f.cancel(),this.f=null),this.w=-1},cs.de=function(){return!1},cs.ue=function(t,e){if(this.w=t.w,0==this.g)if(this.a.debug("TestConnection: Got data for stage 1"),this.pc(t),e){try{var n=this.b.kc.zc(e)}catch(t){return this.a.cb(t),void this.b.dd(this)}this.na=this.b.$a(n[0])}else this.a.debug("TestConnection: Null responseText"),this.b.dd(this);else 1==this.g&&(this.bc?Cu(6):"11111"==e?(Cu(5),this.bc=!0,this.Ze()&&(this.w=200,this.f.cancel(),this.a.debug("Test connection succeeded; using streaming connection"),Cu(11),this.b.ub(this,!0))):(Cu(7),this.bc=!1))},cs.Tc=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.xd()):1==this.g&&(this.a.debug("TestConnection: request complete for stage 2"),this.bc?(this.a.debug("Test connection succeeded; using streaming connection"),Cu(11),this.b.ub(this,!0)):(this.a.debug("Test connection failed; not using streaming"),Cu(10),this.b.ub(this,!1))):(this.a.debug("TestConnection: request failed, in state "+this.g),0==this.g?Cu(8):1==this.g&&Cu(9),this.b.dd(this))},cs.pc=function(t){if(!this.b.ta&&(t=t.h)){var e=t.kb("X-Client-Wire-Protocol");this.Ad=e||null,this.b.aa&&((t=t.kb("X-HTTP-Session-Id"))?this.b.Fe(t):this.a.T("Missing X_HTTP_SESSION_ID in the handshake response"))}},cs.fc=function(){return this.b.fc()},cs.Ba=function(){return this.b.Ba()},cs.Ze=function(){return!oa||10<=Number(da)},(cs=ic.prototype).C=function(){return this.D.C()},cs.add=function(t){this.D.set(oc(t),t)},cs.addAll=function(t){for(var e=(t=Wu(t)).length,n=0;n<e;n++)this.add(t[n])},cs.pb=function(t){for(var e=(t=Wu(t)).length,n=0;n<e;n++)this.remove(t[n])},cs.remove=function(t){return this.D.remove(oc(t))},cs.clear=function(){this.D.clear()},cs.X=function(){return this.D.X()},cs.contains=function(t){return this.D.va(oc(t))},cs.H=function(){return this.D.H()},cs.clone=function(){return new ic(this)};var ac=10;function uc(){this.xg=this.rg=void 0}function cc(){this.jg=new uc}function hc(t,e,n,r,i){try{t.debug(n),e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,i(r)}catch(e){t.cb(e)}}(cs=sc.prototype).ld=function(t){this.v||-1==t.indexOf("spdy")&&-1==t.indexOf("quic")&&-1==t.indexOf("h2")||(this.Xb=this.me,this.v=new ic,this.f&&(this.oc(this.f),this.f=null))},cs.ee=function(){return!!this.f||!!this.v&&this.v.C()>=this.Xb},cs.xf=function(){return this.f?1:this.v?this.v.C():0},cs.Jc=function(t){return this.f?this.f==t:!!this.v&&this.v.contains(t)},cs.oc=function(t){this.v?this.v.add(t):this.f=t},cs.ze=function(t){this.f&&this.f==t?this.f=null:this.v&&this.v.contains(t)&&this.v.remove(t)},cs.cancel=function(){this.ba=this.la(),this.f?(this.f.cancel(),this.f=null):this.v&&!this.v.X()&&(xs(this.v.H(),function(t){t.cancel()}),this.v.clear())},cs.la=function(){if(null!=this.f)return this.ba.concat(this.f.la());if(null!=this.v&&!this.v.X()){var t=this.ba;return xs(this.v.H(),function(e){t=t.concat(e.la())}),t}return Vs(this.ba)},cs.Re=function(t){this.ba=this.ba.concat(t)},cs.$e=function(){this.ba.length=0},uc.prototype.stringify=function(t){return fs.JSON.stringify(t,this.rg)},uc.prototype.parse=function(t){return fs.JSON.parse(t,this.xg)},cc.prototype.hf=function(t,e,n){var r=n||"";try{ju(t,function(t,n){var i=t;_s(t)&&(i=Qa(t)),e.push(r+n+"="+encodeURIComponent(i))})}catch(t){throw e.push(r+"type="+encodeURIComponent("_badmap")),t}},cc.prototype.jf=function(t,e,n){for(var r=-1;;){var i=["count="+e];-1==r?0<e?(r=t[0].Pc,i.push("ofs="+r)):r=0:i.push("ofs="+r);for(var o=!0,s=0;s<e;s++){var a=t[s].Pc,u=t[s].map;if(0>(a-=r))r=Math.max(0,t[s].Pc-100),o=!1;else try{this.hf(u,i,"req"+a+"_")}catch(t){n&&n(u)}}if(o)return i.join("&")}},cc.prototype.zc=function(t){return this.jg.parse(t)};var lc=fs.JSON.parse;function fc(t){Ka.call(this),this.headers=new Ku,this.Xa=t||null,this.ha=!1,this.mc=this.c=null,this.ge=this.Tb="",this.Pa=0,this.I="",this.Aa=this.Lc=this.Qb=this.Ec=!1,this.vb=0,this.hc=null,this.Ae=pc,this.jc=this.lg=this.Ab=!1}Ds(fc,Ka);var pc="";fc.prototype.s=vu("goog.net.XhrIo");var dc=/^https?$/i,yc=["POST","PUT"];function mc(t){return"content-type"==t.toLowerCase()}function gc(t,e){return{type:e,lengthComputable:t.lengthComputable,loaded:t.loaded,total:t.total}}function vc(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=function(t){var e="";return Ys(t,function(t,n){e+=n,e+=":",e+=t,e+="\r\n"}),e}(n),ps(t)){if(e=encodeURIComponent(String(e)),e+=n=null!=n?"="+encodeURIComponent(String(n)):""){if(0>(n=t.indexOf("#"))&&(n=t.length),0>(r=t.indexOf("?"))||r>n){r=n;var i=""}else i=t.substring(r+1,n);n=(t=[t.substr(0,r),i,t.substr(n)])[1],t[1]=e?n?n+"&"+e:e:n,t=t[0]+(t[1]?"?"+t[1]:"")+t[2]}return t}return t.l(e,n),t}function bc(t){this.Bd=22,this.De=0,this.M=[],this.a=new wu,this.Ib=new function(){this.od=this.$d=null},this.na=this.md=this.hb=this.K=this.u=this.Kc=this.aa=this.gb=this.N=this.Rb=this.A=null,this.Te=!0,this.ag=this.Yb=0,this.kf=!!ds("internalChannelParams.failFast",t),this.fd=this.Ja=this.wa=this.ia=this.ea=this.i=null,this.Se=!0,this.w=this.he=this.Sb=-1,this.rc=this.Ha=this.La=0,this.Ve=ds("internalChannelParams.baseRetryDelayMs",t)||5e3,this.vg=ds("internalChannelParams.retryDelaySeedMs",t)||1e4,this.nf=ds("internalChannelParams.forwardChannelMaxRetries",t)||2,this.Od=ds("internalChannelParams.forwardChannelRequestTimeoutMs",t)||2e4,this.Xa=t&&t.oh||void 0,this.Db=void 0,this.Ra=0,this.gc=t&&t.supportsCrossDomainXhr||!1,this.ra="",this.G=new sc(t&&t.concurrentRequestLimit),this.kc=new cc,this.ta=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,(this.Nd=t&&t.fastHandshake||!1)&&!this.ta&&(this.a.T("Force backgroundChannelTest when fastHandshake is enabled."),this.ta=!0),t&&t.Id&&this.a.Id()}function _c(){}function wc(){if(oa&&!(10<=Number(da)))throw Error("Environmental error: no available transport.")}function Ec(t,e){Ka.call(this),this.b=new bc(e),this.yb=t,this.Qg=e&&e.testUrl?e.testUrl:function(t){for(var e=arguments[0],n=1;n<arguments.length;n++){var r,i=arguments[n];0==i.lastIndexOf("/",0)?e=i:((r=""==e)||(r=0<=(r=e.length-1)&&e.indexOf("/",r)==r),e=r?e+i:e+"/"+i)}return e}(this.yb,"test"),this.s=vu("goog.labs.net.webChannel.WebChannelBaseTransport"),this.Rc=e&&e.messageUrlParams||null,t=e&&e.messageHeaders||null,e&&e.clientProtocolHeaderRequired&&(t?t["X-Client-Protocol"]="webchannel":t={"X-Client-Protocol":"webchannel"}),this.b.ga(t),t=e&&e.initMessageHeaders||null,e&&e.messageContentType&&(t?t["X-WebChannel-Content-Type"]=e.messageContentType:t={"X-WebChannel-Content-Type":e.messageContentType}),e&&e.zd&&(t?t["X-WebChannel-Client-Profile"]=e.zd:t={"X-WebChannel-Client-Profile":e.zd}),this.b.Eg(t),(t=e&&e.httpHeadersOverwriteParam)&&!Ws(t)&&this.b.Cg(t),this.Og=e&&e.supportsCrossDomainXhr||!1,this.zg=e&&e.sendRawJson||!1,(e=e&&e.httpSessionIdParam)&&!Ws(e)&&(this.b.Dg(e),null!==(t=this.Rc)&&e in t&&(e in(t=this.Rc)&&delete t[e],(t=this.s)&&t.T("Ignore httpSessionIdParam also specified with messageUrlParams: "+e,void 0))),this.vd=new Ic(this)}function Tc(t){Mu.call(this);var e=t.__sm__;if(e){t:{for(var n in e){t=n;break t}t=void 0}(this.ne=t)&&(t=this.ne,e=null!==e&&t in e?e[t]:void 0),this.data=e}else this.data=t}function Sc(t){xu.call(this),this.status=1,this.errorCode=t}function Ic(t){this.b=t}(cs=fc.prototype).Je=function(t){this.Ab=t},cs.send=function(t,e,n,r){if(this.c)throw Error("[goog.net.XhrIo] Object is active with another request="+this.Tb+"; newUri="+t);e=e?e.toUpperCase():"GET",this.Tb=t,this.I="",this.Pa=0,this.ge=e,this.Ec=!1,this.ha=!0,this.c=this.df(),this.mc=this.Xa?this.Xa.Vd():Pu.Vd(),this.c.onreadystatechange=Is(this.te,this),this.lg&&"onprogress"in this.c&&(this.c.onprogress=Is(function(t){this.re(t,!0)},this),this.c.upload&&(this.c.upload.onprogress=Is(this.re,this)));try{_u(this.s,this.da("Opening Xhr")),this.Lc=!0,this.c.open(e,String(t),!0),this.Lc=!1}catch(t){return _u(this.s,this.da("Error opening Xhr: "+t.message)),void this.Ld(t)}t=n||"";var i=this.headers.clone();r&&ju(r,function(t,e){i.set(e,t)}),r=function(t){t:{for(var e=mc,n=t.length,r=ps(t)?t.split(""):t,i=0;i<n;i++)if(i in r&&e.call(void 0,r[i],i,t)){e=i;break t}e=-1}return 0>e?null:ps(t)?t.charAt(e):t[e]}(i.W()),n=fs.FormData&&t instanceof fs.FormData,!(0<=Ls(yc,e))||r||n||i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach(function(t,e){this.c.setRequestHeader(e,t)},this),this.Ae&&(this.c.responseType=this.Ae),"withCredentials"in this.c&&this.c.withCredentials!==this.Ab&&(this.c.withCredentials=this.Ab);try{this.yd(),0<this.vb&&(this.jc=function(t){return oa&&ma(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}(this.c),_u(this.s,this.da("Will abort after "+this.vb+"ms if incomplete, xhr2 "+this.jc)),this.jc?(this.c.timeout=this.vb,this.c.ontimeout=Is(this.Ua,this)):this.hc=iu(this.Ua,this.vb,this)),_u(this.s,this.da("Sending request")),this.Qb=!0,this.c.send(t),this.Qb=!1}catch(t){_u(this.s,this.da("Send error: "+t.message)),this.Ld(t)}},cs.df=function(){return this.Xa?this.Xa.Dd():Pu.Dd()},cs.Ua=function(){void 0!==ls&&this.c&&(this.I="Timed out after "+this.vb+"ms, aborting",this.Pa=8,_u(this.s,this.da(this.I)),this.dispatchEvent("timeout"),this.abort(8))},cs.Ld=function(t){this.ha=!1,this.c&&(this.Aa=!0,this.c.abort(),this.Aa=!1),this.I=t,this.Pa=5,this.Jd(),this.Gb()},cs.Jd=function(){this.Ec||(this.Ec=!0,this.dispatchEvent("complete"),this.dispatchEvent("error"))},cs.abort=function(t){this.c&&this.ha&&(_u(this.s,this.da("Aborting")),this.ha=!1,this.Aa=!0,this.c.abort(),this.Aa=!1,this.Pa=t||7,this.dispatchEvent("complete"),this.dispatchEvent("abort"),this.Gb())},cs.F=function(){this.c&&(this.ha&&(this.ha=!1,this.Aa=!0,this.c.abort(),this.Aa=!1),this.Gb(!0)),fc.L.F.call(this)},cs.te=function(){this.Ka||(this.Lc||this.Qb||this.Aa?this.se():this.eg())},cs.eg=function(){this.se()},cs.se=function(){if(this.ha&&void 0!==ls)if(this.mc[1]&&4==this.ma()&&2==this.za())_u(this.s,this.da("Local request error detected and ignored"));else if(this.Qb&&4==this.ma())iu(this.te,0,this);else if(this.dispatchEvent("readystatechange"),this.Mc()){_u(this.s,this.da("Request complete")),this.ha=!1;try{this.Rf()?(this.dispatchEvent("complete"),this.dispatchEvent("success")):(this.Pa=6,this.I=this.Yd()+" ["+this.za()+"]",this.Jd())}finally{this.Gb()}}},cs.re=function(t,e){this.dispatchEvent(gc(t,"progress")),this.dispatchEvent(gc(t,e?"downloadprogress":"uploadprogress"))},cs.Gb=function(t){if(this.c){this.yd();var e=this.c,n=this.mc[0]?ys:null;this.mc=this.c=null,t||this.dispatchEvent("ready");try{e.onreadystatechange=n}catch(e){(t=this.s)&&t.ca("Problem encountered resetting onreadystatechange: "+e.message,void 0)}}},cs.yd=function(){this.c&&this.jc&&(this.c.ontimeout=null),this.hc&&(fs.clearTimeout(this.hc),this.hc=null)},cs.Ba=function(){return!!this.c},cs.Mc=function(){return 4==this.ma()},cs.Rf=function(){var t=this.za();t:switch(t){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var e=!0;break t;default:e=!1}return e||0===t&&!this.Of()},cs.Of=function(){var t=String(this.Tb).match(Hu)[1]||null;return!t&&fs.self&&fs.self.location&&(t=(t=fs.self.location.protocol).substr(0,t.length-1)),dc.test(t?t.toLowerCase():"")},cs.ma=function(){return this.c?this.c.readyState:0},cs.za=function(){try{return 2<this.ma()?this.c.status:-1}catch(t){return-1}},cs.Yd=function(){try{return 2<this.ma()?this.c.statusText:""}catch(t){return _u(this.s,"Can not get status: "+t.message),""}},cs.ya=function(){try{return this.c?this.c.responseText:""}catch(t){return _u(this.s,"Can not get responseText: "+t.message),""}},cs.yf=function(t){if(this.c){var e=this.c.responseText;return t&&0==e.indexOf(t)&&(e=e.substring(t.length)),lc(e)}},cs.getResponseHeader=function(t){if(this.c&&this.Mc())return null===(t=this.c.getResponseHeader(t))?void 0:t},cs.getAllResponseHeaders=function(){return this.c&&this.Mc()&&this.c.getAllResponseHeaders()||""},cs.kb=function(t){return this.c?this.c.getResponseHeader(t):null},cs.Ud=function(){return this.Pa},cs.Hc=function(){return ps(this.I)?this.I:String(this.I)},cs.da=function(t){return t+" ["+this.ge+" "+this.Tb+" "+this.za()+"]"},(cs=bc.prototype).tc=8,cs.g=1,cs.connect=function(t,e,n,r,i){this.a.debug("connect()"),Cu(0),this.K=e,this.gb=n||{},r&&void 0!==i&&(this.gb.OSID=r,this.gb.OAID=i),this.ta&&(this.a.debug("connect() bypassed channel-test."),this.Ib.$d=[],this.Ib.od=!1),this.bf(t)},cs.disconnect=function(){if(this.a.debug("disconnect()"),this.qd(),3==this.g){var t=this.Yb++,e=this.hb.clone();e.l("SID",this.ra),e.l("RID",t),e.l("TYPE","terminate"),this.Ya(e),new Uu(this,this.a,this.ra,t,void 0).yg(e)}this.qe()},cs.bf=function(t){this.a.debug("connectTest_()"),this.Ja=new rc(this,this.a),null===this.N&&this.Ja.ga(this.A);var e=t;this.N&&this.A&&(e=vc(t,this.N,this.A)),this.Ja.connect(e)},cs.af=function(){this.a.debug("connectChannel_()"),this.hb=this.Sd(this.K),this.Dc()},cs.qd=function(){this.Ja&&(this.Ja.abort(),this.Ja=null),this.u&&(this.u.cancel(),this.u=null),this.ia&&(fs.clearTimeout(this.ia),this.ia=null),this.Hb(),this.G.cancel(),this.ea&&(fs.clearTimeout(this.ea),this.ea=null)},cs.ga=function(t){this.A=t},cs.Eg=function(t){this.Rb=t},cs.Cg=function(t){this.N=t},cs.Dg=function(t){this.aa=t},cs.Fe=function(t){this.Kc=t},cs.He=function(t){this.Ra=t},cs.Hg=function(){this.gc=!0},cs.Ee=function(t){this.i=t},cs.Nf=function(){return!this.fd},cs.Zc=function(t){1e3==this.M.length&&this.a.ca(function(){return"Already have 1000 queued maps upon queueing "+Qa(t)}),this.M.push(new function(t,e){this.Pc=t,this.map=e,this.context=null}(this.ag++,t)),3==this.g&&this.Dc()},cs.qf=function(){return this.kf?0:this.nf},cs.de=function(){return 0==this.g},cs.getState=function(){return this.g},cs.Dc=function(){this.G.ee()||this.ea||(this.ea=Du(Is(this.we,this),0),this.La=0)},cs.Yf=function(t){return this.G.xf()>=this.G.Xb-(this.ea?1:0)?(this.a.ca("Unexpected retry request is scheduled."),!1):this.ea?(this.a.debug("Use the retry request that is already scheduled."),this.M=t.la().concat(this.M),!0):!(1==this.g||2==this.g||this.La>=this.qf())&&(this.a.debug("Going to retry POST"),this.ea=Du(Is(this.we,this,t),this.Xd(this.La)),this.La++,!0)},cs.we=function(t){this.ea=null,this.Mg(t)},cs.Mg=function(t){this.a.debug("startForwardChannel_"),1==this.g?t?this.a.ca("Not supposed to retry the open"):(this.ig(),this.g=2):3==this.g&&(t?this.le(t):0==this.M.length?this.a.debug("startForwardChannel_ returned: nothing to send"):this.G.ee()?this.a.ca("startForwardChannel_ returned: connection already in progress"):(this.le(),this.a.debug("startForwardChannel_ finished, sent request")))},cs.ig=function(){this.a.debug("open_()"),this.Yb=Math.floor(1e5*Math.random());var t=this.Yb++,e=new Uu(this,this.a,"",t,void 0),n=this.A;this.Rb&&(n?ta(n=$s(n),this.Rb):n=this.Rb),null===this.N&&e.ga(n);var r=this.Hd(e),i=this.hb.clone();i.l("RID",t),0<this.Bd&&i.l("CVER",this.Bd),this.ta&&this.aa&&i.l("X-HTTP-Session-Id",this.aa),this.Ya(i),this.N&&n&&vc(i,this.N,n),this.G.oc(e),this.Nd?(i.l("$req",r),i.l("SID","null"),e.Ag(),e.kd(i,null)):e.kd(i,r)},cs.le=function(t){var e=t?t.R:this.Yb++,n=this.hb.clone();n.l("SID",this.ra),n.l("RID",e),n.l("AID",this.Sb),this.Ya(n),this.N&&this.A&&vc(n,this.N,this.A),e=new Uu(this,this.a,this.ra,e,this.La+1),null===this.N&&e.ga(this.A),t&&this.sg(t),t=this.Hd(e),e.setTimeout(Math.round(.5*this.Od)+Math.round(.5*this.Od*Math.random())),this.G.oc(e),e.kd(n,t)},cs.Ya=function(t){this.i&&ju({},function(e,n){t.l(n,e)})},cs.Hd=function(t){var e=Math.min(this.M.length,1e3),n=this.i?Is(this.i.Ue,this.i,this):null;return n=this.kc.jf(this.M,e,n),t.Gg(this.M.splice(0,e)),n},cs.sg=function(t){this.M=t.la().concat(this.M)},cs.Kd=function(){if(!this.u&&!this.ia){this.rc=1;var t=this.ve;Ya||Za(),tu||(Ya(),tu=!0),eu.add(t,this),this.Ha=0}},cs.Qc=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.rc++,this.ia=Du(Is(this.ve,this),this.Xd(this.Ha)),this.Ha++,!0)},cs.ve=function(){this.ia=null,this.Kg()},cs.Kg=function(){this.a.debug("Creating new HttpRequest"),this.u=new Uu(this,this.a,this.ra,"rpc",this.rc),null===this.N&&this.u.ga(this.A),this.u.He(this.Ra);var t=this.md.clone();t.l("RID","rpc"),t.l("SID",this.ra),t.l("CI",this.fd?"0":"1"),t.l("AID",this.Sb),this.Ya(t),t.l("TYPE","xmlhttp"),this.N&&this.A&&vc(t,this.N,this.A),this.Db&&this.u.setTimeout(this.Db),this.u.jd(t,!0,this.na),this.a.debug("New Request created")},cs.ub=function(t,e){this.a.debug("Test Connection Finished");var n=t.Ad;n&&this.G.ld(n),this.fd=this.Se&&e,this.w=t.w,this.af()},cs.dd=function(t){this.a.debug("Test Connection Failed"),this.w=t.w,this.sa(2)},cs.ue=function(t,e){if(0!=this.g&&(this.u==t||this.G.Jc(t)))if(this.w=t.w,!t.lb&&this.G.Jc(t)&&3==this.g){try{var n=this.kc.zc(e)}catch(t){n=null}gs(n)&&3==n.length?this.Cf(n,t):(this.a.debug("Bad POST response data returned"),this.sa(11))}else(t.lb||this.u==t)&&this.Hb(),Ws(e)||(n=this.kc.zc(e),this.dg(n,t))},cs.Cf=function(t,e){0==t[0]?this.Bf(e):(this.he=t[1],0<(e=this.he-this.Sb)&&(t=t[2],this.a.debug(t+" bytes (in "+e+" arrays) are outstanding on the BackChannel"),this.Jg(t)&&!this.wa&&(this.wa=Du(Is(this.bg,this),6e3))))},cs.Bf=function(t){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.qb+3e3<t.qb))return;this.Hb(),this.u.cancel(),this.u=null}else this.a.T("We do not have a BackChannel established");this.Qc(),Cu(18)}},cs.Jg=function(t){return 37500>t&&!this.Nf()&&0==this.Ha},cs.$a=function(t){return this.Te?this.i?this.i.$a(t):t:null},cs.bg=function(){null!=this.wa&&(this.wa=null,this.u.cancel(),this.u=null,this.Qc(),Cu(19))},cs.Hb=function(){null!=this.wa&&(fs.clearTimeout(this.wa),this.wa=null)},cs.Tc=function(t){this.a.debug("Request complete");var e=null;if(this.u==t){this.Hb(),this.u=null;var n=2}else{if(!this.G.Jc(t))return;e=t.la(),this.G.ze(t),n=1}if(this.w=t.w,0!=this.g)if(t.S)1==n?(function(t,e,n){Eu.dispatchEvent(new Nu(Eu,t,e,n))}(t.Da?t.Da.length:0,Ns()-t.qb,this.La),this.Dc()):this.Kd();else{var r=t.Hc();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: "+function(t,e){switch(t){case 0:return"Non-200 return code ("+e+")";case 1:return"XMLHTTP failure (no data)";case 2:return"HttpConnection timeout";default:return"Unknown error"}}(r,i.w)}),1==n&&this.Yf(t)||2==n&&this.Qc())return;this.a.debug("Exceeded max number of retries")}switch(e&&0<e.length&&this.G.Re(e),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)}}},cs.Xd=function(t){var e=this.Ve+Math.floor(Math.random()*this.vg);return this.Ba()||(this.a.debug("Inactive channel"),e*=2),e*t},cs.pc=function(t){if(this.ta&&(t=t.h)){var e=t.kb("X-Client-Wire-Protocol");e&&this.G.ld(e),this.aa&&((t=t.kb("X-HTTP-Session-Id"))?(this.Fe(t),this.hb.l(this.aa,t)):this.a.T("Missing X_HTTP_SESSION_ID in the handshake response"))}},cs.dg=function(t,e){for(var n=this.i&&this.i.sc?[]:null,r=0;r<t.length;r++){var i=t[r];if(this.Sb=i[0],i=i[1],2==this.g)if("c"==i[0]){this.ra=i[1],this.na=this.$a(i[2]);var o=i[3];null!=o&&(this.tc=o,this.a.info("VER="+this.tc)),null!=(o=i[4])&&(this.De=o,this.a.info("SVER="+this.De)),null!=(i=i[5])&&"number"==typeof i&&0<i&&(this.Db=i*=1.5,this.a.info("backChannelRequestTimeoutMs_="+i)),this.pc(e),this.g=3,this.i&&this.i.wd(),this.Lg(e)}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.sc(this,n),n.length=0),"stop"==i[0]?this.sa(7):this.disconnect()):"noop"!=i[0]&&(n?n.push(i):this.i&&this.i.ud(i)),this.Ha=0)}n&&0!=n.length&&this.i.sc(this,n)},cs.Lg=function(t){this.md=this.Pd(this.na,this.K),t.lb?(this.a.debug("Upgrade the handshake request to a backchannel."),this.G.ze(t),t.tg(this.Db),this.u=t):this.Kd()},cs.sa=function(t){if(this.a.info("Error code "+t),2==t){var e=null;this.i&&(e=null);var n=Is(this.Pg,this);e||(e=new Gu("//www.google.com/images/cleardot.gif"),fs.location&&"http"==fs.location.protocol||e.tb("https"),e.Ub()),function(t,e){var n=new wu;n.debug("TestLoadImage: loading "+t);var r=new Image;r.onload=Cs(hc,n,r,"TestLoadImage: loaded",!0,e),r.onerror=Cs(hc,n,r,"TestLoadImage: error",!1,e),r.onabort=Cs(hc,n,r,"TestLoadImage: abort",!1,e),r.ontimeout=Cs(hc,n,r,"TestLoadImage: timeout",!1,e),fs.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=t}(e.toString(),n)}else Cu(2);this.cg(t)},cs.Pg=function(t){t?(this.a.info("Successfully pinged google.com"),Cu(2)):(this.a.info("Failed to ping google.com"),Cu(1))},cs.cg=function(t){this.a.debug("HttpChannel: error - "+t),this.g=0,this.i&&this.i.td(t),this.qe(),this.qd()},cs.qe=function(){if(this.g=0,this.w=-1,this.i){var t=this.G.la();if(0!=t.length||0!=this.M.length){var e=this;this.a.debug(function(){return"Number of undelivered maps, pending: "+t.length+", outgoing: "+e.M.length}),this.G.$e(),Vs(this.M),this.M.length=0}this.i.sd()}},cs.Sd=function(t){return t=this.Cd(null,t),this.a.debug("GetForwardChannelUri: "+t),t},cs.Pd=function(t,e){return t=this.Cd(this.fc()?t:null,e),this.a.debug("GetBackChannelUri: "+t),t},cs.Cd=function(t,e){var n=function(t){return t instanceof Gu?t.clone():new Gu(t,void 0)}(e);if(""!=n.xa)t&&n.rb(t+"."+n.xa),n.sb(n.Ca);else{var r=fs.location;n=function(t,e,n,r){var i=new Gu(null,void 0);return t&&i.tb(t),e&&i.rb(e),n&&i.sb(n),r&&i.ec(r),i}(r.protocol,t?t+"."+r.hostname:r.hostname,+r.port,e)}return this.gb&&Ys(this.gb,function(t,e){n.l(e,t)}),t=this.aa,e=this.Kc,t&&e&&n.l(t,e),n.l("VER",this.tc),this.Ya(n),n},cs.Jb=function(t){if(t&&!this.gc)throw Error("Can't create secondary domain capable XhrIo object.");return(t=new fc(this.Xa)).Je(this.gc),t},cs.Ba=function(){return!!this.i&&this.i.Ba()},cs.fc=function(){return this.gc},(cs=_c.prototype).sc=null,cs.wd=function(){},cs.ud=function(){},cs.td=function(){},cs.sd=function(){},cs.Ba=function(){return!0},cs.Ue=function(){},cs.$a=function(t){return t},wc.prototype.cf=function(t,e){return new Ec(t,e)},Ds(Ec,Ka),(cs=Ec.prototype).addEventListener=function(t,e,n,r){Ec.L.addEventListener.call(this,t,e,n,r)},cs.removeEventListener=function(t,e,n,r){Ec.L.removeEventListener.call(this,t,e,n,r)},cs.open=function(){this.b.Ee(this.vd),this.Og&&this.b.Hg(),this.b.connect(this.Qg,this.yb,this.Rc||void 0)},cs.close=function(){this.b.disconnect()},cs.send=function(t){if(ps(t)){var e={};e.__data__=t,this.b.Zc(e)}else this.zg?((e={}).__data__=Qa(t),this.b.Zc(e)):this.b.Zc(t)},cs.F=function(){this.b.Ee(null),delete this.vd,this.b.disconnect(),delete this.b,Ec.L.F.call(this)},Ds(Tc,Mu),Ds(Sc,xu),Ds(Ic,_c),Ic.prototype.wd=function(){bu(this.b.s,"WebChannel opened on "+this.b.yb),this.b.dispatchEvent("a")},Ic.prototype.ud=function(t){this.b.dispatchEvent(new Tc(t))},Ic.prototype.td=function(t){bu(this.b.s,"WebChannel aborted on "+this.b.yb+" due to channel error: "+t),this.b.dispatchEvent(new Sc(t))},Ic.prototype.sd=function(){bu(this.b.s,"WebChannel closed on "+this.b.yb),this.b.dispatchEvent("b")};var Cc=Cs(function(t,e){function n(){}n.prototype=t.prototype;var r=new n;return t.apply(r,Array.prototype.slice.call(arguments,1)),r},wc);function Nc(){this.V=[],this.Z=[]}function Dc(t,e){if(Rs.call(this),this.oe=t||0,this.Wb=e||10,this.oe>this.Wb)throw Error(Ac);this.fa=new Nc,this.oa=new ic,this.Ac=0,this.Nc=null,this.Cb()}(cs=Nc.prototype).Vf=function(){0==this.V.length&&(this.V=this.Z,this.V.reverse(),this.Z=[])},cs.enqueue=function(t){this.Z.push(t)},cs.ab=function(){return this.Vf(),this.V.pop()},cs.C=function(){return this.V.length+this.Z.length},cs.X=function(){return 0==this.V.length&&0==this.Z.length},cs.clear=function(){this.V=[],this.Z=[]},cs.contains=function(t){return 0<=Ls(this.V,t)||0<=Ls(this.Z,t)},cs.remove=function(t){var e=this.V,n=Ms(e,t);return 0<=n?(Array.prototype.splice.call(e,n,1),e=!0):e=!1,e||qs(this.Z,t)},cs.H=function(){for(var t=[],e=this.V.length-1;0<=e;--e)t.push(this.V[e]);var n=this.Z.length;for(e=0;e<n;++e)t.push(this.Z[e]);return t},Ds(Dc,Rs);var Ac="[goog.structs.Pool] Min can not be greater than max";function kc(t,e){this.fe=t,this.gd=e}function Rc(t){this.Y=[],t&&this.Lf(t)}function Oc(){Rc.call(this)}function Pc(t,e){this.Gd=void 0,this.cc=new Oc,Dc.call(this,t,e)}function Lc(t,e,n,r){this.Jf=t,this.Ab=!!r,Pc.call(this,e,n)}(cs=Dc.prototype).Mb=function(){var t=Ns();if(!(null!=this.Nc&&t-this.Nc<this.Ac)){var e=this.qg();return e&&(this.Nc=t,this.oa.add(e)),e}},cs.og=function(t){return!!this.oa.remove(t)&&(this.nc(t),!0)},cs.qg=function(){for(var t;0<this.Td()&&(t=this.fa.ab(),!this.Sc(t));)this.Cb();return!t&&this.C()<this.Wb&&(t=this.xc()),t},cs.nc=function(t){this.oa.remove(t),this.Sc(t)&&this.C()<this.Wb?this.fa.enqueue(t):this.Bc(t)},cs.Cb=function(){for(var t=this.fa;this.C()<this.oe;)t.enqueue(this.xc());for(;this.C()>this.Wb&&0<this.Td();)this.Bc(t.ab())},cs.xc=function(){return{}},cs.Bc=function(t){if("function"==typeof t.bb)t.bb();else for(var e in t)t[e]=null},cs.Sc=function(t){return"function"!=typeof t.Ye||t.Ye()},cs.contains=function(t){return this.fa.contains(t)||this.oa.contains(t)},cs.C=function(){return this.fa.C()+this.oa.C()},cs.rf=function(){return this.oa.C()},cs.Td=function(){return this.fa.C()},cs.X=function(){return this.fa.X()&&this.oa.X()},cs.F=function(){if(Dc.L.F.call(this),0<this.rf())throw Error("[goog.structs.Pool] Objects not released");delete this.oa;for(var t=this.fa;!t.X();)this.Bc(t.ab());delete this.fa},kc.prototype.getKey=function(){return this.fe},kc.prototype.clone=function(){return new kc(this.fe,this.gd)},(cs=Rc.prototype).ce=function(t,e){var n=this.Y;n.push(new kc(t,e)),this.$f(n.length-1)},cs.Lf=function(t){if(t instanceof Rc){var e=t.W();if(t=t.H(),0>=this.C()){for(var n=this.Y,r=0;r<e.length;r++)n.push(new kc(e[r],t[r]));return}}else e=Js(t),t=Xs(t);for(r=0;r<e.length;r++)this.ce(e[r],t[r])},cs.remove=function(){var t=this.Y,e=t.length,n=t[0];if(!(0>=e))return 1==e?Us(t):(t[0]=t.pop(),this.Zf()),n.gd},cs.Zf=function(){for(var t=0,e=this.Y,n=e.length,r=e[t];t<n>>1;){var i=this.tf(t),o=this.zf(t);if(e[i=o<n&&e[o].getKey()<e[i].getKey()?o:i].getKey()>r.getKey())break;e[t]=e[i],t=i}e[t]=r},cs.$f=function(t){for(var e=this.Y,n=e[t];0<t;){var r=this.wf(t);if(!(e[r].getKey()>n.getKey()))break;e[t]=e[r],t=r}e[t]=n},cs.tf=function(t){return 2*t+1},cs.zf=function(t){return 2*t+2},cs.wf=function(t){return t-1>>1},cs.H=function(){for(var t=this.Y,e=[],n=t.length,r=0;r<n;r++)e.push(t[r].gd);return e},cs.W=function(){for(var t=this.Y,e=[],n=t.length,r=0;r<n;r++)e.push(t[r].getKey());return e},cs.va=function(t){return Fs(this.Y,function(e){return e.getKey()==t})},cs.clone=function(){return new Rc(this)},cs.C=function(){return this.Y.length},cs.X=function(){return 0==this.Y.length},cs.clear=function(){Us(this.Y)},Ds(Oc,Rc),Oc.prototype.enqueue=function(t,e){this.ce(t,e)},Oc.prototype.ab=function(){return this.remove()},Ds(Pc,Dc),(cs=Pc.prototype).Mb=function(t,e){if(!t)return(t=Pc.L.Mb.call(this))&&this.Ac&&(this.Gd=fs.setTimeout(Is(this.Nb,this),this.Ac)),t;this.cc.enqueue(void 0!==e?e:100,t),this.Nb()},cs.Nb=function(){for(var t=this.cc;0<t.C();){var e=this.Mb();if(!e)break;t.ab().apply(this,[e])}},cs.nc=function(t){Pc.L.nc.call(this,t),this.Nb()},cs.Cb=function(){Pc.L.Cb.call(this),this.Nb()},cs.F=function(){Pc.L.F.call(this),fs.clearTimeout(this.Gd),this.cc.clear(),this.cc=null},Ds(Lc,Pc),Lc.prototype.xc=function(){var t=new fc,e=this.Jf;return e&&e.forEach(function(e,n){t.headers.set(n,e)}),this.Ab&&t.Je(!0),t},Lc.prototype.Sc=function(t){return!t.Ka&&!t.Ba()},wc.prototype.createWebChannel=wc.prototype.cf,Ec.prototype.send=Ec.prototype.send,Ec.prototype.open=Ec.prototype.open,Ec.prototype.close=Ec.prototype.close,Au.NO_ERROR=0,Au.TIMEOUT=8,Au.HTTP_ERROR=6,ku.COMPLETE="complete",Ou.EventType=Lu,Lu.OPEN="a",Lu.CLOSE="b",Lu.ERROR="c",Lu.MESSAGE="d",Ka.prototype.listen=Ka.prototype.nb,Lc.prototype.getObject=Lc.prototype.Mb,Lc.prototype.releaseObject=Lc.prototype.og,fc.prototype.listenOnce=fc.prototype.Oc,fc.prototype.getLastError=fc.prototype.Hc,fc.prototype.getLastErrorCode=fc.prototype.Ud,fc.prototype.getStatus=fc.prototype.za,fc.prototype.getStatusText=fc.prototype.Yd,fc.prototype.getResponseJson=fc.prototype.yf,fc.prototype.getResponseText=fc.prototype.ya,fc.prototype.getResponseText=fc.prototype.ya,fc.prototype.send=fc.prototype.send;var Mc,xc,Fc={createWebChannelTransport:Cc,ErrorCode:Au,EventType:ku,WebChannel:Ou,XhrIoPool:Lc},Uc=Fc.createWebChannelTransport,qc=Fc.ErrorCode,Bc=Fc.EventType,Vc=Fc.WebChannel,Wc=Fc.XhrIoPool,jc=Gn.SDK_VERSION,Kc=new Xn("@firebase/firestore");function Qc(){return Kc.logLevel===Qn.DEBUG?Mc.DEBUG:Kc.logLevel===Qn.SILENT?Mc.SILENT:Mc.ERROR}function Hc(t){switch(t){case Mc.DEBUG:Kc.logLevel=Qn.DEBUG;break;case Mc.ERROR:Kc.logLevel=Qn.ERROR;break;case Mc.SILENT:Kc.logLevel=Qn.SILENT;break;default:Kc.error("Firestore ("+jc+"): Invalid value passed to `setLogLevel`")}}function Gc(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(Kc.logLevel<=Qn.DEBUG){var i=n.map(Yc);Kc.debug.apply(Kc,["Firestore ("+jc+") ["+t+"]: "+e].concat(i))}}function zc(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(Kc.logLevel<=Qn.ERROR){var r=e.map(Yc);Kc.error.apply(Kc,["Firestore ("+jc+"): "+t].concat(r))}}function Yc(t){if("string"==typeof t)return t;var e=$c.getPlatform();try{return e.formatJSON(t)}catch(e){return t}}function Xc(t){var e="FIRESTORE ("+jc+") INTERNAL ASSERTION FAILED: "+t;throw zc(e),new Error(e)}function Jc(t,e){t||Xc(e)}(xc=Mc||(Mc={}))[xc.DEBUG=0]="DEBUG",xc[xc.ERROR=1]="ERROR",xc[xc.SILENT=2]="SILENT";var $c=function(){function t(){}return t.setPlatform=function(e){t.platform&&Xc("Platform already defined"),t.platform=e},t.getPlatform=function(){return t.platform||Xc("Platform not set"),t.platform},t}();function Zc(){return $c.getPlatform().emptyByteString}var th={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"},eh=function(t){function e(e,n){var r=t.call(this,n)||this;return r.code=e,r.message=n,r.name="FirebaseError",r.toString=function(){return r.name+": [code="+r.code+"]: "+r.message},r}return Xe(e,t),e}(Error);function nh(t,e){function n(){var t="This constructor is private.";throw e&&(t+=" ",t+=e),new eh(th.INVALID_ARGUMENT,t)}for(var r in n.prototype=t.prototype,t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}function rh(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ih(t,e){return void 0!==t?t:e}function oh(t,e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var r=Number(n);isNaN(r)||e(r,t[n])}}function sh(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])}function ah(t){for(var e in Jc(null!=t&&"object"==typeof t,"isEmpty() expects object parameter."),t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function uh(t,e,n){if(e.length!==n)throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires "+Sh(n,"argument")+", but was called with "+Sh(e.length,"argument")+".")}function ch(t,e,n){if(e.length<n)throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires at least "+Sh(n,"argument")+", but was called with "+Sh(e.length,"argument")+".")}function hh(t,e,n,r){if(e.length<n||e.length>r)throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+Sh(e.length,"argument")+".")}function lh(t,e,n,r){gh(t,e,Th(n)+" argument",r)}function fh(t,e,n,r){void 0!==r&&lh(t,e,n,r)}function ph(t,e,n,r){gh(t,e,n+" option",r)}function dh(t,e,n,r){void 0!==r&&ph(t,e,n,r)}function yh(t,e,n,r,i){void 0!==r&&function(t,e,n,r,i){if(!(r instanceof Array))throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires its "+e+" option to be an array, but it was: "+bh(r));for(var o=0;o<r.length;++o)if(!i(r[o]))throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires all "+e+" elements to be "+n+", but the value at index "+o+" was: "+bh(r[o]))}(t,e,n,r,i)}function mh(t,e,n,r,i){void 0!==r&&function(t,e,n,r,i){for(var o=[],s=0,a=i;s<a.length;s++){var u=a[s];if(u===r)return;o.push(bh(u))}var c=bh(r);throw new eh(th.INVALID_ARGUMENT,"Invalid value "+c+" provided to function "+t+'() for option "'+n+'". Acceptable values: '+o.join(", "))}(t,0,n,r,i)}function gh(t,e,n,r){if(!("object"===e?vh(r):"non-empty string"===e?"string"==typeof r&&""!==r:typeof r===e)){var i=bh(r);throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires its "+n+" to be of type "+e+", but it was: "+i)}}function vh(t){return"object"==typeof t&&null!==t&&(Object.getPrototypeOf(t)===Object.prototype||null===Object.getPrototypeOf(t))}function bh(t){if(void 0===t)return"undefined";if(null===t)return"null";if("string"==typeof t)return t.length>20&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";var e=function(t){if(t.constructor){var e=/function\s+([^\s(]+)\s*\(/.exec(t.constructor.toString());if(e&&e.length>1)return e[1]}return null}(t);return e?"a custom "+e+" object":"an object"}return"function"==typeof t?"a function":Xc("Unknown wrong type: "+typeof t)}function _h(t,e,n){if(void 0===n)throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+Th(e)+" argument, but it was undefined.")}function wh(t,e,n){sh(e,function(e,r){if(n.indexOf(e)<0)throw new eh(th.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function Eh(t,e,n,r){var i=bh(r);return new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires its "+Th(n)+" argument to be a "+e+", but it was: "+i)}function Th(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function Sh(t,e){return t+" "+e+(1===t?"":"s")}var Ih=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return Jc(20===e.length,"Invalid auto ID: "+e),e},t}();function Ch(t,e){return t<e?-1:t>e?1:0}function Nh(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(!t[n].isEqual(e[n]))return!1;return!0}function Dh(){if("undefined"==typeof Uint8Array)throw new eh(th.UNIMPLEMENTED,"Uint8Arrays are not available in this environment.")}function Ah(){if(!$c.getPlatform().base64Available)throw new eh(th.UNIMPLEMENTED,"Blobs are unavailable in Firestore in this environment.")}var kh,Rh,Oh=function(){function t(t){Ah(),this._binaryString=t}return t.fromBase64String=function(e){uh("Blob.fromBase64String",arguments,1),lh("Blob.fromBase64String","string",1,e),Ah();try{return new t($c.getPlatform().atob(e))}catch(t){throw new eh(th.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},t.fromUint8Array=function(e){if(uh("Blob.fromUint8Array",arguments,1),Dh(),!(e instanceof Uint8Array))throw Eh("Blob.fromUint8Array","Uint8Array",1,e);return new t(Array.prototype.map.call(e,function(t){return String.fromCharCode(t)}).join(""))},t.prototype.toBase64=function(){return uh("Blob.toBase64",arguments,0),Ah(),$c.getPlatform().btoa(this._binaryString)},t.prototype.toUint8Array=function(){uh("Blob.toUint8Array",arguments,0),Dh();for(var t=new Uint8Array(this._binaryString.length),e=0;e<this._binaryString.length;e++)t[e]=this._binaryString.charCodeAt(e);return t},t.prototype.toString=function(){return"Blob(base64: "+this.toBase64()+")"},t.prototype.isEqual=function(t){return this._binaryString===t._binaryString},t.prototype._compareTo=function(t){return Ch(this._binaryString,t._binaryString)},t}(),Ph=nh(Oh,"Use Blob.fromUint8Array() or Blob.fromBase64String() instead."),Lh=function(){function t(t,e){if(uh("GeoPoint",arguments,2),lh("GeoPoint","number",1,t),lh("GeoPoint","number",2,e),!isFinite(t)||t<-90||t>90)throw new eh(th.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new eh(th.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this._long},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){return this._lat===t._lat&&this._long===t._long},t.prototype._compareTo=function(t){return Ch(this._lat,t._lat)||Ch(this._long,t._long)},t}(),Mh=function(){function t(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new eh(th.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new eh(th.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new eh(th.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new eh(th.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}return t.now=function(){return t.fromMillis(Date.now())},t.fromDate=function(e){return t.fromMillis(e.getTime())},t.fromMillis=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.prototype.toDate=function(){return new Date(this.toMillis())},t.prototype.toMillis=function(){return 1e3*this.seconds+this.nanoseconds/1e6},t.prototype._compareTo=function(t){return this.seconds===t.seconds?Ch(this.nanoseconds,t.nanoseconds):Ch(this.seconds,t.seconds)},t.prototype.isEqual=function(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"},t}(),xh=function(){return function(t,e,n,r){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r}}(),Fh="(default)",Uh=function(){function t(t,e){this.projectId=t,this.database=e||Fh}return Object.defineProperty(t.prototype,"isDefaultDatabase",{get:function(){return this.database===Fh},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return e instanceof t&&e.projectId===this.projectId&&e.database===this.database},t.prototype.compareTo=function(t){return Ch(this.projectId,t.projectId)||Ch(this.database,t.database)},t}(),qh=function(){function t(t,e,n){this.init(t,e,n)}return t.prototype.init=function(t,e,n){void 0===e?e=0:e>t.length&&Xc("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&Xc("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n},t.prototype.construct=function(t,e,n){var r=Object.create(Object.getPrototypeOf(this));return r.init(t,e,n),r},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return 0===t.comparator(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach(function(t){n.push(t)}):"string"==typeof e?n.push(e):Xc("Unknown parameter type for Path.child(): "+e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,Jc(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return Jc(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return Jc(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return Jc(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},t.prototype.get=function(t){return Jc(t<this.length,"Index out of range"),this.segments[this.offset+t]},t.prototype.isEmpty=function(){return 0===this.length},t.prototype.isPrefixOf=function(t){if(t.length<this.length)return!1;for(var e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0},t.prototype.isImmediateParentOf=function(t){if(this.length+1!==t.length)return!1;for(var e=0;e<this.length;e++)if(this.get(e)!==t.get(e))return!1;return!0},t.prototype.forEach=function(t){for(var e=this.offset,n=this.limit();e<n;e++)t(this.segments[e])},t.prototype.toArray=function(){return this.segments.slice(this.offset,this.limit())},t.comparator=function(t,e){for(var n=Math.min(t.length,e.length),r=0;r<n;r++){var i=t.get(r),o=e.get(r);if(i<o)return-1;if(i>o)return 1}return t.length<e.length?-1:t.length>e.length?1:0},t}(),Bh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Xe(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(t){if(t.indexOf("//")>=0)throw new eh(th.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(qh),Vh=/^[_a-zA-Z][_a-zA-Z0-9]*$/,Wh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Xe(e,t),e.isValidIdentifier=function(t){return Vh.test(t)},e.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(t){for(var n=[],r="",i=0,o=function(){if(0===r.length)throw new eh(th.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},s=!1;i<t.length;){var a=t[i];if("\\"===a){if(i+1===t.length)throw new eh(th.INVALID_ARGUMENT,"Path has trailing escape character: "+t);var u=t[i+1];if("\\"!==u&&"."!==u&&"`"!==u)throw new eh(th.INVALID_ARGUMENT,"Path has invalid escape sequence: "+t);r+=u,i+=2}else"`"===a?(s=!s,i++):"."!==a||s?(r+=a,i++):(o(),i++)}if(o(),s)throw new eh(th.INVALID_ARGUMENT,"Unterminated ` in path: "+t);return new e(n)},e.EMPTY_PATH=new e([]),e}(qh),jh=function(){function t(e){this.path=e,Jc(t.isDocumentKey(e),"Invalid DocumentKey with an odd number of segments: "+e.toArray().join("/"))}return t.prototype.isEqual=function(t){return null!==t&&0===Bh.comparator(this.path,t.path)},t.prototype.toString=function(){return this.path.toString()},t.comparator=function(t,e){return Bh.comparator(t.path,e.path)},t.isDocumentKey=function(t){return t.length%2==0},t.fromSegments=function(e){return new t(new Bh(e.slice()))},t.fromPathString=function(e){return new t(Bh.fromString(e))},t.EMPTY=new t(new Bh([])),t}(),Kh=function(){function t(t,e){this.key=t,this.version=e}return t.compareByKey=function(t,e){return jh.comparator(t.key,e.key)},t}(),Qh=function(t){function e(e,n,r,i){var o=t.call(this,e,n)||this;return o.data=r,o.hasLocalMutations=!!i.hasLocalMutations,o.hasCommittedMutations=!!i.hasCommittedMutations,o}return Xe(e,t),e.prototype.field=function(t){return this.data.field(t)},e.prototype.fieldValue=function(t){var e=this.field(t);return e?e.value():void 0},e.prototype.value=function(){return this.data.value()},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.data.isEqual(t.data)&&this.hasLocalMutations===t.hasLocalMutations&&this.hasCommittedMutations===t.hasCommittedMutations},e.prototype.toString=function(){return"Document("+this.key+", "+this.version+", "+this.data.toString()+", {hasLocalMutations: "+this.hasLocalMutations+"}), {hasCommittedMutations: "+this.hasCommittedMutations+"})"},Object.defineProperty(e.prototype,"hasPendingWrites",{get:function(){return this.hasLocalMutations||this.hasCommittedMutations},enumerable:!0,configurable:!0}),e.compareByField=function(t,e,n){var r=e.field(t),i=n.field(t);return void 0!==r&&void 0!==i?r.compareTo(i):Xc("Trying to compare documents on fields that don't exist")},e}(Kh),Hh=function(t){function e(e,n,r){var i=t.call(this,e,n)||this;return i.hasCommittedMutations=!(!r||!r.hasCommittedMutations),i}return Xe(e,t),e.prototype.toString=function(){return"NoDocument("+this.key+", "+this.version+")"},Object.defineProperty(e.prototype,"hasPendingWrites",{get:function(){return this.hasCommittedMutations},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){return t instanceof e&&t.hasCommittedMutations===this.hasCommittedMutations&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)},e}(Kh),Gh=function(t){function e(e,n){return t.call(this,e,n)||this}return Xe(e,t),e.prototype.toString=function(){return"UnknownDocument("+this.key+", "+this.version+")"},Object.defineProperty(e.prototype,"hasPendingWrites",{get:function(){return!0},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){return t instanceof e&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)},e}(Kh),zh=function(){function t(t,e){this.comparator=t,this.root=e||Xh.EMPTY}return t.prototype.insert=function(e,n){return new t(this.comparator,this.root.insert(e,n,this.comparator).copy(null,null,Xh.BLACK,null,null))},t.prototype.remove=function(e){return new t(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Xh.BLACK,null,null))},t.prototype.get=function(t){for(var e=this.root;!e.isEmpty();){var n=this.comparator(t,e.key);if(0===n)return e.value;n<0?e=e.left:n>0&&(e=e.right)}return null},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.isEmpty();){var r=this.comparator(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal(function(e,n){return t(e,n),!1})},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(){return new Yh(this.root,null,this.comparator,!1)},t.prototype.getIteratorFrom=function(t){return new Yh(this.root,t,this.comparator,!1)},t.prototype.getReverseIterator=function(){return new Yh(this.root,null,this.comparator,!0)},t.prototype.getReverseIteratorFrom=function(t){return new Yh(this.root,t,this.comparator,!0)},t}(),Yh=function(){function t(t,e,n,r){this.isReverse=r,this.nodeStack=[];for(var i=1;!t.isEmpty();)if(i=e?n(t.key,e):1,r&&(i*=-1),i<0)t=this.isReverse?t.left:t.right;else{if(0===i){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){Jc(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t=this.nodeStack.pop(),e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}},t}(),Xh=function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:t.EMPTY,this.right=null!=o?o:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,i=n(t,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===i?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n))).fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()},t.prototype.remove=function(e,n){var r,i=this;if(n(e,i.key)<0)i.left.isEmpty()||i.left.isRed()||i.left.left.isRed()||(i=i.moveRedLeft()),i=i.copy(null,null,null,i.left.remove(e,n),null);else{if(i.left.isRed()&&(i=i.rotateRight()),i.right.isEmpty()||i.right.isRed()||i.right.left.isRed()||(i=i.moveRedRight()),0===n(e,i.key)){if(i.right.isEmpty())return t.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.removeMin())}i=i.copy(null,null,null,null,i.right.remove(e,n))}return i.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=(t=(t=t.copy(null,null,null,null,t.right.rotateRight())).rotateLeft()).colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=(t=t.rotateRight()).colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw Xc("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw Xc("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw Xc("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),Jh=function(){function t(){this.size=0}return t.prototype.copy=function(t,e,n,r,i){return this},t.prototype.insert=function(t,e,n){return new Xh(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();Xh.EMPTY=new Jh,function(t){t[t.NullValue=0]="NullValue",t[t.BooleanValue=1]="BooleanValue",t[t.NumberValue=2]="NumberValue",t[t.TimestampValue=3]="TimestampValue",t[t.StringValue=4]="StringValue",t[t.BlobValue=5]="BlobValue",t[t.RefValue=6]="RefValue",t[t.GeoPointValue=7]="GeoPointValue",t[t.ArrayValue=8]="ArrayValue",t[t.ObjectValue=9]="ObjectValue"}(kh||(kh={})),function(t){t[t.Default=0]="Default",t[t.Estimate=1]="Estimate",t[t.Previous=2]="Previous"}(Rh||(Rh={}));var $h=function(){function t(t,e){this.serverTimestampBehavior=t,this.timestampsInSnapshots=e}return t.fromSnapshotOptions=function(e,n){switch(e.serverTimestamps){case"estimate":return new t(Rh.Estimate,n);case"previous":return new t(Rh.Previous,n);case"none":case void 0:return new t(Rh.Default,n);default:return Xc("fromSnapshotOptions() called with invalid options.")}},t}(),Zh=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":t.toString()},t.prototype.defaultCompareTo=function(t){return Jc(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),Ch(this.typeOrder,t.typeOrder)},t}(),tl=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=kh.NullValue,e.internalValue=null,e}return Xe(e,t),e.prototype.value=function(t){return null},e.prototype.isEqual=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(Zh),el=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.BooleanValue,n}return Xe(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?Ch(this,t):this.defaultCompareTo(t)},e.of=function(t){return t?e.TRUE:e.FALSE},e.TRUE=new e(!0),e.FALSE=new e(!1),e}(Zh),nl=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.NumberValue,n}return Xe(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?(n=this.internalValue,r=t.internalValue,n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1):this.defaultCompareTo(t);var n,r},e}(Zh);function rl(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}var il=function(t){function e(e){return t.call(this,e)||this}return Xe(e,t),e.prototype.isEqual=function(t){return t instanceof e&&rl(this.internalValue,t.internalValue)},e}(nl),ol=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return Xe(e,t),e.prototype.isEqual=function(t){return t instanceof e&&rl(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(nl),sl=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.StringValue,n}return Xe(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?Ch(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(Zh),al=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.TimestampValue,n}return Xe(e,t),e.prototype.value=function(t){return t&&t.timestampsInSnapshots?this.internalValue:this.internalValue.toDate()},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):t instanceof ul?-1:this.defaultCompareTo(t)},e}(Zh),ul=function(t){function e(e,n){var r=t.call(this)||this;return r.localWriteTime=e,r.previousValue=n,r.typeOrder=kh.TimestampValue,r}return Xe(e,t),e.prototype.value=function(t){return t&&t.serverTimestampBehavior===Rh.Estimate?new al(this.localWriteTime).value(t):t&&t.serverTimestampBehavior===Rh.Previous&&this.previousValue?this.previousValue.value(t):null},e.prototype.isEqual=function(t){return t instanceof e&&this.localWriteTime.isEqual(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime._compareTo(t.localWriteTime):t instanceof al?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return"<ServerTimestamp localTime="+this.localWriteTime.toString()+">"},e}(Zh),cl=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.BlobValue,n}return Xe(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(Zh),hl=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=kh.RefValue,r}return Xe(e,t),e.prototype.value=function(t){return this.key},e.prototype.isEqual=function(t){return t instanceof e&&(this.key.isEqual(t.key)&&this.databaseId.isEqual(t.databaseId))},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:jh.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(Zh),ll=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.GeoPointValue,n}return Xe(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(Zh),fl=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.ObjectValue,n}return Xe(e,t),e.prototype.value=function(t){var e={};return this.internalValue.inorderTraversal(function(n,r){e[n]=r.value(t)}),e},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.isEqual=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext();if(i.key!==o.key||!i.value.isEqual(o.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var i=n.getNext(),o=r.getNext(),s=Ch(i.key,o.key)||i.value.compareTo(o.value);if(s)return s}return Ch(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(t,n){if(Jc(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),n);var r=this.child(t.firstSegment());r instanceof e||(r=e.EMPTY);var i=r.set(t.popFirst(),n);return this.setChild(t.firstSegment(),i)},e.prototype.delete=function(t){if(Jc(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.internalValue.remove(t.firstSegment()));var n=this.child(t.firstSegment());if(n instanceof e){var r=n.delete(t.popFirst());return new e(this.internalValue.insert(t.firstSegment(),r))}return this},e.prototype.contains=function(t){return void 0!==this.field(t)},e.prototype.field=function(t){Jc(!t.isEmpty(),"Can't get field of empty path");var n=this;return t.forEach(function(t){n=n instanceof e&&n.internalValue.get(t)||void 0}),n},e.prototype.toString=function(){return JSON.stringify(this.value())},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new zh(Ch)),e}(Zh),pl=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=kh.ArrayValue,n}return Xe(e,t),e.prototype.value=function(t){return this.internalValue.map(function(e){return e.value(t)})},e.prototype.forEach=function(t){this.internalValue.forEach(t)},e.prototype.isEqual=function(t){if(t instanceof e){if(this.internalValue.length!==t.internalValue.length)return!1;for(var n=0;n<this.internalValue.length;n++)if(!this.internalValue[n].isEqual(t.internalValue[n]))return!1;return!0}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=Math.min(this.internalValue.length,t.internalValue.length),r=0;r<n;r++){var i=this.internalValue[r].compareTo(t.internalValue[r]);if(i)return i}return Ch(this.internalValue.length,t.internalValue.length)}return this.defaultCompareTo(t)},e.prototype.toString=function(){return JSON.stringify(this.value())},e}(Zh),dl=Number,yl=dl.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),ml=dl.MAX_SAFE_INTEGER||Math.pow(2,53)-1,gl=dl.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function vl(t){return null===t||void 0===t}function bl(t){return gl(t)&&t<=ml&&t>=yl}var _l,wl=function(){function t(t,e,n,r,i,o){void 0===e&&(e=[]),void 0===n&&(n=[]),void 0===r&&(r=null),void 0===i&&(i=null),void 0===o&&(o=null),this.path=t,this.explicitOrderBy=e,this.filters=n,this.limit=r,this.startAt=i,this.endAt=o,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}return t.atPath=function(e){return new t(e)},Object.defineProperty(t.prototype,"orderBy",{get:function(){if(null===this.memoizedOrderBy){var t=this.getInequalityFilterField(),e=this.getFirstOrderByField();if(null!==t&&null===e)t.isKeyField()?this.memoizedOrderBy=[kl]:this.memoizedOrderBy=[new Al(t),kl];else{Jc(null===t||null!==e&&t.isEqual(e),"First orderBy should match inequality field."),this.memoizedOrderBy=[];for(var n=!1,r=0,i=this.explicitOrderBy;r<i.length;r++){var o=i[r];this.memoizedOrderBy.push(o),o.field.isKeyField()&&(n=!0)}if(!n){var s=this.explicitOrderBy.length>0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:Nl.ASCENDING;this.memoizedOrderBy.push(s===Nl.ASCENDING?kl:Rl)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(e){Jc(null==this.getInequalityFilterField()||!(e instanceof Sl)||!e.isInequality()||e.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),Jc(!jh.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){Jc(!jh.isDocumentKey(this.path),"No ordering allowed for document query"),Jc(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();t+="|f:";for(var e=0,n=this.filters;e<n.length;e++){t+=n[e].canonicalId(),t+=","}t+="|ob:";for(var r=0,i=this.orderBy;r<i.length;r++){t+=i[r].canonicalId(),t+=","}vl(this.limit)||(t+="|l:",t+=this.limit),this.startAt&&(t+="|lb:",t+=this.startAt.canonicalId()),this.endAt&&(t+="|ub:",t+=this.endAt.canonicalId()),this.memoizedCanonicalId=t}return this.memoizedCanonicalId},t.prototype.toString=function(){var t="Query("+this.path.canonicalString();return this.filters.length>0&&(t+=", filters: ["+this.filters.join(", ")+"]"),vl(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.isEqual=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e<this.orderBy.length;e++)if(!this.orderBy[e].isEqual(t.orderBy[e]))return!1;if(this.filters.length!==t.filters.length)return!1;for(e=0;e<this.filters.length;e++)if(!this.filters[e].isEqual(t.filters[e]))return!1;return!!this.path.isEqual(t.path)&&(!(null!==this.startAt?!this.startAt.isEqual(t.startAt):null!==t.startAt)&&(null!==this.endAt?this.endAt.isEqual(t.endAt):null===t.endAt))},t.prototype.docComparator=function(t,e){for(var n=!1,r=0,i=this.orderBy;r<i.length;r++){var o=i[r],s=o.compare(t,e);if(0!==s)return s;n=n||o.field.isKeyField()}return Jc(n,"orderBy used that doesn't compare on key field"),0},t.prototype.matches=function(t){return this.matchesAncestor(t)&&this.matchesOrderBy(t)&&this.matchesFilters(t)&&this.matchesBounds(t)},t.prototype.hasLimit=function(){return!vl(this.limit)},t.prototype.getFirstOrderByField=function(){return this.explicitOrderBy.length>0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t<e.length;t++){var n=e[t];if(n instanceof Sl&&n.isInequality())return n.field}return null},t.prototype.hasArrayContainsFilter=function(){return void 0!==this.filters.find(function(t){return t instanceof Sl&&t.op===Tl.ARRAY_CONTAINS})},t.prototype.isDocumentQuery=function(){return jh.isDocumentKey(this.path)&&0===this.filters.length},t.prototype.matchesAncestor=function(t){var e=t.key.path;return jh.isDocumentKey(this.path)?this.path.isEqual(e):this.path.isPrefixOf(e)&&this.path.length===e.length-1},t.prototype.matchesOrderBy=function(t){for(var e=0,n=this.explicitOrderBy;e<n.length;e++){var r=n[e];if(!r.field.isKeyField()&&void 0===t.field(r.field))return!1}return!0},t.prototype.matchesFilters=function(t){for(var e=0,n=this.filters;e<n.length;e++){if(!n[e].matches(t))return!1}return!0},t.prototype.matchesBounds=function(t){return!(this.startAt&&!this.startAt.sortsBeforeDocument(this.orderBy,t))&&(!this.endAt||!this.endAt.sortsBeforeDocument(this.orderBy,t))},t.prototype.assertValidBound=function(t){Jc(t.position.length<=this.orderBy.length,"Bound is longer than orderBy")},t}(),El=function(){function t(){}return t.create=function(t,e,n){if(n.isEqual(tl.INSTANCE)){if(e!==Tl.EQUAL)throw new eh(th.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new Il(t)}if(n.isEqual(ol.NAN)){if(e!==Tl.EQUAL)throw new eh(th.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new Cl(t)}return new Sl(t,e,n)},t}(),Tl=function(){function t(t){this.name=t}return t.fromString=function(e){switch(e){case"<":return t.LESS_THAN;case"<=":return t.LESS_THAN_OR_EQUAL;case"==":return t.EQUAL;case">=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;case"array-contains":return t.ARRAY_CONTAINS;default:return Xc("Unknown relation: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.isEqual=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t.ARRAY_CONTAINS=new t("array-contains"),t}(),Sl=function(t){function e(e,n,r){var i=t.call(this)||this;return i.field=e,i.op=n,i.value=r,i}return Xe(e,t),e.prototype.matches=function(t){if(this.field.isKeyField()){Jc(this.value instanceof hl,"Comparing on key, but filter value not a RefValue"),Jc(this.op!==Tl.ARRAY_CONTAINS,"array-contains queries don't make sense on document keys.");var e=this.value,n=jh.comparator(t.key,e.key);return this.matchesComparison(n)}var r=t.field(this.field);return void 0!==r&&this.matchesValue(r)},e.prototype.matchesValue=function(t){var e=this;return this.op===Tl.ARRAY_CONTAINS?t instanceof pl&&void 0!==t.internalValue.find(function(t){return t.isEqual(e.value)}):this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},e.prototype.matchesComparison=function(t){switch(this.op){case Tl.LESS_THAN:return t<0;case Tl.LESS_THAN_OR_EQUAL:return t<=0;case Tl.EQUAL:return 0===t;case Tl.GREATER_THAN:return t>0;case Tl.GREATER_THAN_OR_EQUAL:return t>=0;default:return Xc("Unknown relation op"+this.op)}},e.prototype.isInequality=function(){return this.op!==Tl.EQUAL&&this.op!==Tl.ARRAY_CONTAINS},e.prototype.canonicalId=function(){return this.field.canonicalString()+this.op.toString()+this.value.toString()},e.prototype.isEqual=function(t){return t instanceof e&&(this.op.isEqual(t.op)&&this.field.isEqual(t.field)&&this.value.isEqual(t.value))},e.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},e}(El),Il=function(t){function e(e){var n=t.call(this)||this;return n.field=e,n}return Xe(e,t),e.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&null===e.value()},e.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},e.prototype.toString=function(){return this.field.canonicalString()+" IS null"},e.prototype.isEqual=function(t){return t instanceof e&&this.field.isEqual(t.field)},e}(El),Cl=function(t){function e(e){var n=t.call(this)||this;return n.field=e,n}return Xe(e,t),e.prototype.matches=function(t){var e=t.field(this.field),n=e&&e.value();return"number"==typeof n&&isNaN(n)},e.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},e.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},e.prototype.isEqual=function(t){return t instanceof e&&this.field.isEqual(t.field)},e}(El),Nl=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),Dl=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e<n.length;e++){t+=n[e].toString()}return t},t.prototype.sortsBeforeDocument=function(t,e){Jc(this.position.length<=t.length,"Bound has more components than query's orderBy");for(var n=0,r=0;r<this.position.length;r++){var i=t[r],o=this.position[r];if(i.field.isKeyField())Jc(o instanceof hl,"Bound has a non-key value where the key path is being used."),n=jh.comparator(o.key,e.key);else{var s=e.field(i.field);Jc(void 0!==s,"Field should exist since document matched the orderBy already."),n=o.compareTo(s)}if(i.dir===Nl.DESCENDING&&(n*=-1),0!==n)break}return this.before?n<=0:n<0},t.prototype.isEqual=function(t){if(null===t)return!1;if(this.before!==t.before||this.position.length!==t.position.length)return!1;for(var e=0;e<this.position.length;e++){var n=this.position[e],r=t.position[e];return n.isEqual(r)}return!0},t}(),Al=function(){function t(t,e){this.field=t,void 0===e&&(e=Nl.ASCENDING),this.dir=e,this.isKeyOrderBy=t.isKeyField()}return t.prototype.compare=function(t,e){var n=this.isKeyOrderBy?Qh.compareByKey(t,e):Qh.compareByField(this.field,t,e);switch(this.dir){case Nl.ASCENDING:return n;case Nl.DESCENDING:return-1*n;default:return Xc("Unknown direction: "+this.dir)}},t.prototype.canonicalId=function(){return this.field.canonicalString()+this.dir.toString()},t.prototype.toString=function(){return this.field.canonicalString()+" ("+this.dir+")"},t.prototype.isEqual=function(t){return this.dir===t.dir&&this.field.isEqual(t.field)},t}(),kl=new Al(Wh.keyField(),Nl.ASCENDING),Rl=new Al(Wh.keyField(),Nl.DESCENDING),Ol=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new Mh(n,e%1e6*1e3))},t.fromTimestamp=function(e){return new t(e)},t.forDeletedDoc=function(){return t.MIN},t.prototype.compareTo=function(t){return this.timestamp._compareTo(t.timestamp)},t.prototype.isEqual=function(t){return this.timestamp.isEqual(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp.toString()+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new Mh(0,0)),t}();!function(t){t[t.Listen=0]="Listen",t[t.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",t[t.LimboResolution=2]="LimboResolution"}(_l||(_l={}));var Pl,Ll=function(){function t(t,e,n,r,i,o){void 0===i&&(i=Ol.MIN),void 0===o&&(o=Zc()),this.query=t,this.targetId=e,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.resumeToken=o}return t.prototype.copy=function(e){return new t(this.query,this.targetId,this.purpose,void 0===e.sequenceNumber?this.sequenceNumber:e.sequenceNumber,void 0===e.snapshotVersion?this.snapshotVersion:e.snapshotVersion,void 0===e.resumeToken?this.resumeToken:e.resumeToken)},t.prototype.isEqual=function(t){return this.targetId===t.targetId&&this.purpose===t.purpose&&this.sequenceNumber===t.sequenceNumber&&this.snapshotVersion.isEqual(t.snapshotVersion)&&this.resumeToken===t.resumeToken&&this.query.isEqual(t.query)},t}(),Ml=function(){function t(t){this.comparator=t,this.data=new zh(this.comparator)}return t.fromMapKeys=function(e){var n=new t(e.comparator);return e.forEach(function(t){n=n.add(t)}),n},t.prototype.has=function(t){return null!==this.data.get(t)},t.prototype.first=function(){return this.data.minKey()},t.prototype.last=function(){return this.data.maxKey()},Object.defineProperty(t.prototype,"size",{get:function(){return this.data.size},enumerable:!0,configurable:!0}),t.prototype.indexOf=function(t){return this.data.indexOf(t)},t.prototype.forEach=function(t){this.data.inorderTraversal(function(e,n){return t(e),!1})},t.prototype.forEachInRange=function(t,e){for(var n=this.data.getIteratorFrom(t[0]);n.hasNext();){var r=n.getNext();if(this.comparator(r.key,t[1])>=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();){if(!t(n.getNext().key))return}},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=function(t){var e=this;return t.forEach(function(t){e=e.add(t)}),e},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.getIterator(),r=e.data.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(0!==this.comparator(i,o))return!1}return!0},t.prototype.toArray=function(){var t=[];return this.forEach(function(e){t.push(e)}),t},t.prototype.toString=function(){var t=[];return this.forEach(function(e){return t.push(e)}),"SortedSet("+t.toString()+")"},t.prototype.copy=function(e){var n=new t(this.comparator);return n.data=e,n},t}(),xl=function(){function t(t){this.fields=t}return t.fromArray=function(e){var n=new Ml(Wh.comparator);return e.forEach(function(t){return n=n.add(t)}),new t(n)},t.prototype.covers=function(t){var e=!1;return this.fields.forEach(function(n){n.isPrefixOf(t)&&(e=!0)}),e},t.prototype.isEqual=function(t){return this.fields.isEqual(t.fields)},t}(),Fl=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.isEqual=function(t){return this.field.isEqual(t.field)&&this.transform.isEqual(t.transform)},t}(),Ul=function(){return function(t,e){this.version=t,this.transformResults=e}}();!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(Pl||(Pl={}));var ql=function(){function t(t,e){this.updateTime=t,this.exists=e,Jc(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof Qh&&t.version.isEqual(this.updateTime):void 0!==this.exists?this.exists===t instanceof Qh:(Jc(this.isNone,"Precondition should be empty"),!0)},t.prototype.isEqual=function(t){return e=this.updateTime,n=t.updateTime,(null!==e&&void 0!==e?!(!n||!e.isEqual(n)):e===n)&&this.exists===t.exists;var e,n},t.NONE=new t,t}(),Bl=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&Jc(t.key.isEqual(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof Qh?t.version:Ol.MIN},t}(),Vl=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.value=n,i.precondition=r,i.type=Pl.Set,i}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),Jc(null==e.transformResults,"Transform results received by SetMutation.");var n=e.version;return new Qh(this.key,n,this.value,{hasCommittedMutations:!0})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Bl.getPostMutationVersion(t);return new Qh(this.key,r,this.value,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.value.isEqual(t.value)&&this.precondition.isEqual(t.precondition)},e}(Bl),Wl=function(t){function e(e,n,r,i){var o=t.call(this)||this;return o.key=e,o.data=n,o.fieldMask=r,o.precondition=i,o.type=Pl.Patch,o}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),Jc(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return new Gh(this.key,e.version);var n=this.patchDocument(t);return new Qh(this.key,e.version,n,{hasCommittedMutations:!0})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=Bl.getPostMutationVersion(t),i=this.patchDocument(t);return new Qh(this.key,r,i,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.fieldMask.isEqual(t.fieldMask)&&this.precondition.isEqual(t.precondition)},e.prototype.patchDocument=function(t){var e;return e=t instanceof Qh?t.data:fl.EMPTY,this.patchObject(e)},e.prototype.patchObject=function(t){var e=this;return this.fieldMask.fields.forEach(function(n){if(!n.isEmpty()){var r=e.data.field(n);t=void 0!==r?t.set(n,r):t.delete(n)}}),t},e}(Bl),jl=function(t){function e(e,n){var r=t.call(this)||this;return r.key=e,r.fieldTransforms=n,r.type=Pl.Transform,r.precondition=ql.exists(!0),r}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),Jc(null!=e.transformResults,"Transform results missing for TransformMutation."),!this.precondition.isValidFor(t))return new Gh(this.key,e.version);var n=this.requireDocument(t),r=this.serverTransformResults(t,e.transformResults),i=e.version,o=this.transformObject(n.data,r);return new Qh(this.key,i,o,{hasCommittedMutations:!0})},e.prototype.applyToLocalView=function(t,e,n){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var r=this.requireDocument(t),i=this.localTransformResults(n,e),o=this.transformObject(r.data,i);return new Qh(this.key,r.version,o,{hasLocalMutations:!0})},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&Nh(this.fieldTransforms,t.fieldTransforms)&&this.precondition.isEqual(t.precondition)},e.prototype.requireDocument=function(t){Jc(t instanceof Qh,"Unknown MaybeDocument type "+t);var e=t;return Jc(e.key.isEqual(this.key),"Can only transform a document with the same key"),e},e.prototype.serverTransformResults=function(t,e){var n=[];Jc(this.fieldTransforms.length===e.length,"server transform result count ("+e.length+") should match field transform count ("+this.fieldTransforms.length+")");for(var r=0;r<e.length;r++){var i=this.fieldTransforms[r],o=i.transform,s=null;t instanceof Qh&&(s=t.field(i.field)||null),n.push(o.applyToRemoteDocument(s,e[r]))}return n},e.prototype.localTransformResults=function(t,e){for(var n=[],r=0,i=this.fieldTransforms;r<i.length;r++){var o=i[r],s=o.transform,a=null;e instanceof Qh&&(a=e.field(o.field)||null),n.push(s.applyToLocalView(a,t))}return n},e.prototype.transformObject=function(t,e){Jc(e.length===this.fieldTransforms.length,"TransformResults length mismatch.");for(var n=0;n<this.fieldTransforms.length;n++){var r=this.fieldTransforms[n].field;t=t.set(r,e[n])}return t},e}(Bl),Kl=function(t){function e(e,n){var r=t.call(this)||this;return r.key=e,r.precondition=n,r.type=Pl.Delete,r}return Xe(e,t),e.prototype.applyToRemoteDocument=function(t,e){return this.verifyKeyMatches(t),Jc(null==e.transformResults,"Transform results received by DeleteMutation."),new Hh(this.key,e.version,{hasCommittedMutations:!0})},e.prototype.applyToLocalView=function(t,e,n){return this.verifyKeyMatches(t),this.precondition.isValidFor(t)?(t&&Jc(t.key.isEqual(this.key),"Can only apply mutation to document with same key"),new Hh(this.key,Ol.forDeletedDoc())):t},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.precondition.isEqual(t.precondition)},e}(Bl),Ql=function(){function t(){}return t.prototype.applyToLocalView=function(t,e){return new ul(e,t)},t.prototype.applyToRemoteDocument=function(t,e){return e},t.prototype.isEqual=function(e){return e instanceof t},t.instance=new t,t}(),Hl=function(){function t(t){this.elements=t}return t.prototype.applyToLocalView=function(t,e){return this.apply(t)},t.prototype.applyToRemoteDocument=function(t,e){return this.apply(t)},t.prototype.apply=function(t){for(var e=zl(t),n=function(t){e.find(function(e){return e.isEqual(t)})||e.push(t)},r=0,i=this.elements;r<i.length;r++){n(i[r])}return new pl(e)},t.prototype.isEqual=function(e){return e instanceof t&&Nh(e.elements,this.elements)},t}(),Gl=function(){function t(t){this.elements=t}return t.prototype.applyToLocalView=function(t,e){return this.apply(t)},t.prototype.applyToRemoteDocument=function(t,e){return this.apply(t)},t.prototype.apply=function(t){for(var e=zl(t),n=function(t){e=e.filter(function(e){return!e.isEqual(t)})},r=0,i=this.elements;r<i.length;r++){n(i[r])}return new pl(e)},t.prototype.isEqual=function(e){return e instanceof t&&Nh(e.elements,this.elements)},t}();function zl(t){return t instanceof pl?t.internalValue.slice():[]}var Yl,Xl=function(){function t(t){this.count=t}return t.prototype.isEqual=function(t){return t&&t.count===this.count},t}();function Jl(t){switch(t){case th.OK:return Xc("Treated status OK as error");case th.CANCELLED:case th.UNKNOWN:case th.DEADLINE_EXCEEDED:case th.RESOURCE_EXHAUSTED:case th.INTERNAL:case th.UNAVAILABLE:case th.UNAUTHENTICATED:return!1;case th.INVALID_ARGUMENT:case th.NOT_FOUND:case th.ALREADY_EXISTS:case th.PERMISSION_DENIED:case th.FAILED_PRECONDITION:case th.ABORTED:case th.OUT_OF_RANGE:case th.UNIMPLEMENTED:case th.DATA_LOSS:return!0;default:return Xc("Unknown status code: "+t)}}function $l(t){if(void 0===t)return zc("GRPC error has no .code"),th.UNKNOWN;switch(t){case Yl.OK:return th.OK;case Yl.CANCELLED:return th.CANCELLED;case Yl.UNKNOWN:return th.UNKNOWN;case Yl.DEADLINE_EXCEEDED:return th.DEADLINE_EXCEEDED;case Yl.RESOURCE_EXHAUSTED:return th.RESOURCE_EXHAUSTED;case Yl.INTERNAL:return th.INTERNAL;case Yl.UNAVAILABLE:return th.UNAVAILABLE;case Yl.UNAUTHENTICATED:return th.UNAUTHENTICATED;case Yl.INVALID_ARGUMENT:return th.INVALID_ARGUMENT;case Yl.NOT_FOUND:return th.NOT_FOUND;case Yl.ALREADY_EXISTS:return th.ALREADY_EXISTS;case Yl.PERMISSION_DENIED:return th.PERMISSION_DENIED;case Yl.FAILED_PRECONDITION:return th.FAILED_PRECONDITION;case Yl.ABORTED:return th.ABORTED;case Yl.OUT_OF_RANGE:return th.OUT_OF_RANGE;case Yl.UNIMPLEMENTED:return th.UNIMPLEMENTED;case Yl.DATA_LOSS:return th.DATA_LOSS;default:return Xc("Unknown status code: "+t)}}!function(t){t[t.OK=0]="OK",t[t.CANCELLED=1]="CANCELLED",t[t.UNKNOWN=2]="UNKNOWN",t[t.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",t[t.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",t[t.NOT_FOUND=5]="NOT_FOUND",t[t.ALREADY_EXISTS=6]="ALREADY_EXISTS",t[t.PERMISSION_DENIED=7]="PERMISSION_DENIED",t[t.UNAUTHENTICATED=16]="UNAUTHENTICATED",t[t.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",t[t.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",t[t.ABORTED=10]="ABORTED",t[t.OUT_OF_RANGE=11]="OUT_OF_RANGE",t[t.UNIMPLEMENTED=12]="UNIMPLEMENTED",t[t.INTERNAL=13]="INTERNAL",t[t.UNAVAILABLE=14]="UNAVAILABLE",t[t.DATA_LOSS=15]="DATA_LOSS"}(Yl||(Yl={}));var Zl=new zh(jh.comparator);function tf(){return Zl}var ef=new zh(jh.comparator);function nf(){return ef}var rf=new zh(jh.comparator);function of(){return rf}var sf=new Ml(jh.comparator);function af(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];for(var n=sf,r=0,i=t;r<i.length;r++){var o=i[r];n=n.add(o)}return n}var uf=new Ml(Ch);function cf(){return uf}var hf,lf,ff=function(){function t(t){this.comparator=t?function(e,n){return t(e,n)||jh.comparator(e.key,n.key)}:function(t,e){return jh.comparator(t.key,e.key)},this.keyedMap=nf(),this.sortedSet=new zh(this.comparator)}return t.emptySet=function(e){return new t(e.comparator)},t.prototype.has=function(t){return null!=this.keyedMap.get(t)},t.prototype.get=function(t){return this.keyedMap.get(t)},t.prototype.first=function(){return this.sortedSet.minKey()},t.prototype.last=function(){return this.sortedSet.maxKey()},t.prototype.isEmpty=function(){return this.sortedSet.isEmpty()},t.prototype.indexOf=function(t){var e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1},Object.defineProperty(t.prototype,"size",{get:function(){return this.sortedSet.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t){this.sortedSet.inorderTraversal(function(e,n){return t(e),!1})},t.prototype.add=function(t){var e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))},t.prototype.delete=function(t){var e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();n.hasNext();){var i=n.getNext().key,o=r.getNext().key;if(!i.isEqual(o))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"},t.prototype.copy=function(e,n){var r=new t;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=n,r},t}();!function(t){t[t.Added=0]="Added",t[t.Removed=1]="Removed",t[t.Modified=2]="Modified",t[t.Metadata=3]="Metadata"}(hf||(hf={})),function(t){t[t.Local=0]="Local",t[t.Synced=1]="Synced"}(lf||(lf={}));var pf,df=function(){function t(){this.changeMap=new zh(jh.comparator)}return t.prototype.track=function(t){var e=t.doc.key,n=this.changeMap.get(e);n?t.type!==hf.Added&&n.type===hf.Metadata?this.changeMap=this.changeMap.insert(e,t):t.type===hf.Metadata&&n.type!==hf.Removed?this.changeMap=this.changeMap.insert(e,{type:n.type,doc:t.doc}):t.type===hf.Modified&&n.type===hf.Modified?this.changeMap=this.changeMap.insert(e,{type:hf.Modified,doc:t.doc}):t.type===hf.Modified&&n.type===hf.Added?this.changeMap=this.changeMap.insert(e,{type:hf.Added,doc:t.doc}):t.type===hf.Removed&&n.type===hf.Added?this.changeMap=this.changeMap.remove(e):t.type===hf.Removed&&n.type===hf.Modified?this.changeMap=this.changeMap.insert(e,{type:hf.Removed,doc:n.doc}):t.type===hf.Added&&n.type===hf.Removed?this.changeMap=this.changeMap.insert(e,{type:hf.Modified,doc:t.doc}):Xc("unsupported combination of changes: "+JSON.stringify(t)+" after "+JSON.stringify(n)):this.changeMap=this.changeMap.insert(e,t)},t.prototype.getChanges=function(){var t=[];return this.changeMap.inorderTraversal(function(e,n){t.push(n)}),t},t}(),yf=function(){function t(t,e,n,r,i,o,s,a){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=o,this.syncStateChanged=s,this.excludesMetadataChanges=a}return t.fromInitialDocuments=function(e,n,r,i){var o=[];return n.forEach(function(t){o.push({type:hf.Added,doc:t})}),new t(e,n,ff.emptySet(n),o,r,i,!0,!1)},Object.defineProperty(t.prototype,"hasPendingWrites",{get:function(){return!this.mutatedKeys.isEmpty()},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){if(!(this.fromCache===t.fromCache&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&this.query.isEqual(t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;var e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(var r=0;r<e.length;r++)if(e[r].type!==n[r].type||!e[r].doc.isEqual(n[r].doc))return!1;return!0},t}(),mf=function(){function t(t,e,n,r,i){this.snapshotVersion=t,this.targetChanges=e,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}return t.createSynthesizedRemoteEventForCurrentChange=function(e,n){var r,i=((r={})[e]=gf.createSynthesizedTargetChangeForCurrentChange(e,n),r);return new t(Ol.MIN,i,cf(),tf(),af())},t}(),gf=function(){function t(t,e,n,r,i){this.resumeToken=t,this.current=e,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}return t.createSynthesizedTargetChangeForCurrentChange=function(e,n){return new t(Zc(),n,af(),af(),af())},t}(),vf=function(){return function(t,e,n,r){this.updatedTargetIds=t,this.removedTargetIds=e,this.key=n,this.newDoc=r}}(),bf=function(){return function(t,e){this.targetId=t,this.existenceFilter=e}}();!function(t){t[t.NoChange=0]="NoChange",t[t.Added=1]="Added",t[t.Removed=2]="Removed",t[t.Current=3]="Current",t[t.Reset=4]="Reset"}(pf||(pf={}));var _f=function(){return function(t,e,n,r){void 0===n&&(n=Zc()),void 0===r&&(r=null),this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r}}(),wf=function(){function t(){this.pendingResponses=0,this.documentChanges=Sf(),this._resumeToken=Zc(),this._current=!1,this._hasPendingChanges=!0}return Object.defineProperty(t.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"resumeToken",{get:function(){return this._resumeToken},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isPending",{get:function(){return 0!==this.pendingResponses},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPendingChanges",{get:function(){return this._hasPendingChanges},enumerable:!0,configurable:!0}),t.prototype.updateResumeToken=function(t){t.length>0&&(this._hasPendingChanges=!0,this._resumeToken=t)},t.prototype.toTargetChange=function(){var t=af(),e=af(),n=af();return this.documentChanges.forEach(function(r,i){switch(i){case hf.Added:t=t.add(r);break;case hf.Modified:e=e.add(r);break;case hf.Removed:n=n.add(r);break;default:Xc("Encountered invalid change type: "+i)}}),new gf(this._resumeToken,this._current,t,e,n)},t.prototype.clearPendingChanges=function(){this._hasPendingChanges=!1,this.documentChanges=Sf()},t.prototype.addDocumentChange=function(t,e){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.insert(t,e)},t.prototype.removeDocumentChange=function(t){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.remove(t)},t.prototype.recordPendingTargetRequest=function(){this.pendingResponses+=1},t.prototype.recordTargetResponse=function(){this.pendingResponses-=1},t.prototype.markCurrent=function(){this._hasPendingChanges=!0,this._current=!0},t}(),Ef=function(){function t(t){this.metadataProvider=t,this.targetStates={},this.pendingDocumentUpdates=tf(),this.pendingDocumentTargetMapping=Tf(),this.pendingTargetResets=new Ml(Ch)}return t.prototype.handleDocumentChange=function(t){for(var e=0,n=t.updatedTargetIds;e<n.length;e++){var r=n[e];t.newDoc instanceof Qh?this.addDocumentToTarget(r,t.newDoc):t.newDoc instanceof Hh&&this.removeDocumentFromTarget(r,t.key,t.newDoc)}for(var i=0,o=t.removedTargetIds;i<o.length;i++){r=o[i];this.removeDocumentFromTarget(r,t.key,t.newDoc)}},t.prototype.handleTargetChange=function(t){var e=this;this.forEachTarget(t,function(n){var r=e.ensureTargetState(n);switch(t.state){case pf.NoChange:e.isActiveTarget(n)&&r.updateResumeToken(t.resumeToken);break;case pf.Added:r.recordTargetResponse(),r.isPending||r.clearPendingChanges(),r.updateResumeToken(t.resumeToken);break;case pf.Removed:r.recordTargetResponse(),r.isPending||e.removeTarget(n),Jc(!t.cause,"WatchChangeAggregator does not handle errored targets");break;case pf.Current:e.isActiveTarget(n)&&(r.markCurrent(),r.updateResumeToken(t.resumeToken));break;case pf.Reset:e.isActiveTarget(n)&&(e.resetTarget(n),r.updateResumeToken(t.resumeToken));break;default:Xc("Unknown target watch change state: "+t.state)}})},t.prototype.forEachTarget=function(t,e){t.targetIds.length>0?t.targetIds.forEach(e):oh(this.targetStates,e)},t.prototype.handleExistenceFilter=function(t){var e=t.targetId,n=t.existenceFilter.count,r=this.queryDataForActiveTarget(e);if(r){var i=r.query;if(i.isDocumentQuery())if(0===n){var o=new jh(i.path);this.removeDocumentFromTarget(e,o,new Hh(o,Ol.forDeletedDoc()))}else Jc(1===n,"Single document existence filter with count: "+n);else this.getCurrentDocumentCountForTarget(e)!==n&&(this.resetTarget(e),this.pendingTargetResets=this.pendingTargetResets.add(e))}},t.prototype.createRemoteEvent=function(t){var e=this,n={};oh(this.targetStates,function(r,i){var o=e.queryDataForActiveTarget(r);if(o){if(i.current&&o.query.isDocumentQuery()){var s=new jh(o.query.path);null!==e.pendingDocumentUpdates.get(s)||e.targetContainsDocument(r,s)||e.removeDocumentFromTarget(r,s,new Hh(s,t))}i.hasPendingChanges&&(n[r]=i.toTargetChange(),i.clearPendingChanges())}});var r=af();this.pendingDocumentTargetMapping.forEach(function(t,n){var i=!0;n.forEachWhile(function(t){var n=e.queryDataForActiveTarget(t);return!n||n.purpose===_l.LimboResolution||(i=!1,!1)}),i&&(r=r.add(t))});var i=new mf(t,n,this.pendingTargetResets,this.pendingDocumentUpdates,r);return this.pendingDocumentUpdates=tf(),this.pendingDocumentTargetMapping=Tf(),this.pendingTargetResets=new Ml(Ch),i},t.prototype.addDocumentToTarget=function(t,e){if(this.isActiveTarget(t)){var n=this.targetContainsDocument(t,e.key)?hf.Modified:hf.Added;this.ensureTargetState(t).addDocumentChange(e.key,n),this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e.key,e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e.key,this.ensureDocumentTargetMapping(e.key).add(t))}},t.prototype.removeDocumentFromTarget=function(t,e,n){if(this.isActiveTarget(t)){var r=this.ensureTargetState(t);this.targetContainsDocument(t,e)?r.addDocumentChange(e,hf.Removed):r.removeDocumentChange(e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e,this.ensureDocumentTargetMapping(e).delete(t)),n&&(this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e,n))}},t.prototype.removeTarget=function(t){delete this.targetStates[t]},t.prototype.getCurrentDocumentCountForTarget=function(t){var e=this.ensureTargetState(t).toTargetChange();return this.metadataProvider.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size},t.prototype.recordPendingTargetRequest=function(t){this.ensureTargetState(t).recordPendingTargetRequest()},t.prototype.ensureTargetState=function(t){return this.targetStates[t]||(this.targetStates[t]=new wf),this.targetStates[t]},t.prototype.ensureDocumentTargetMapping=function(t){var e=this.pendingDocumentTargetMapping.get(t);return e||(e=new Ml(Ch),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(t,e)),e},t.prototype.isActiveTarget=function(t){return null!==this.queryDataForActiveTarget(t)},t.prototype.queryDataForActiveTarget=function(t){var e=this.targetStates[t];return e&&e.isPending?null:this.metadataProvider.getQueryDataForTarget(t)},t.prototype.resetTarget=function(t){var e=this;Jc(!this.targetStates[t].isPending,"Should only reset active targets"),this.targetStates[t]=new wf,this.metadataProvider.getRemoteKeysForTarget(t).forEach(function(n){e.removeDocumentFromTarget(t,n,null)})},t.prototype.targetContainsDocument=function(t,e){return this.metadataProvider.getRemoteKeysForTarget(t).has(e)},t}();function Tf(){return new zh(jh.comparator)}function Sf(){return new zh(jh.comparator)}var If,Cf,Nf=((If={})[Nl.ASCENDING.name]="ASCENDING",If[Nl.DESCENDING.name]="DESCENDING",If),Df=((Cf={})[Tl.LESS_THAN.name]="LESS_THAN",Cf[Tl.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",Cf[Tl.GREATER_THAN.name]="GREATER_THAN",Cf[Tl.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",Cf[Tl.EQUAL.name]="EQUAL",Cf[Tl.ARRAY_CONTAINS.name]="ARRAY_CONTAINS",Cf),Af=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function kf(t,e){Jc(!vl(t),e+" is missing")}function Rf(t){return"number"==typeof t?t:"string"==typeof t?Number(t):Xc("can't parse "+t)}var Of=function(){function t(t,e){this.databaseId=t,this.options=e}return t.prototype.emptyByteString=function(){return this.options.useProto3Json?"":new Uint8Array(0)},t.prototype.unsafeCastProtoByteString=function(t){return t},t.prototype.fromRpcStatus=function(t){var e=void 0===t.code?th.UNKNOWN:$l(t.code);return new eh(e,t.message||"")},t.prototype.toInt32Value=function(t){return vl(t)?void 0:{value:t}},t.prototype.fromInt32Value=function(t){var e;return vl(e="object"==typeof t?t.value:t)?null:e},t.prototype.toTimestamp=function(t){return{seconds:t.seconds,nanos:t.nanoseconds}},t.prototype.fromTimestamp=function(t){if("string"==typeof t)return this.fromIso8601String(t);Jc(!!t,"Cannot deserialize null or undefined timestamp.");var e=Rf(t.seconds||"0"),n=t.nanos||0;return new Mh(e,n)},t.prototype.fromIso8601String=function(t){var e=0,n=Af.exec(t);if(Jc(!!n,"invalid timestamp: "+t),n[1]){var r=n[1];r=(r+"000000000").substr(0,9),e=Number(r)}var i=new Date(t),o=Math.floor(i.getTime()/1e3);return new Mh(o,e)},t.prototype.toBytes=function(t){return this.options.useProto3Json?t.toBase64():this.unsafeCastProtoByteString(t.toUint8Array())},t.prototype.fromBlob=function(t){return"string"==typeof t?(Jc(this.options.useProto3Json,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Oh.fromBase64String(t)):(Jc(!this.options.useProto3Json,"Expected bytes to be passed in as string, but got something else instead."),Oh.fromUint8Array(t))},t.prototype.toVersion=function(t){return this.toTimestamp(t.toTimestamp())},t.prototype.fromVersion=function(t){return Jc(!!t,"Trying to deserialize version that isn't set"),Ol.fromTimestamp(this.fromTimestamp(t))},t.prototype.toResourceName=function(t,e){return this.fullyQualifiedPrefixPath(t).child("documents").child(e).canonicalString()},t.prototype.fromResourceName=function(t){var e=Bh.fromString(t);return Jc(this.isValidResourceName(e),"Tried to deserialize invalid key "+e.toString()),e},t.prototype.toName=function(t){return this.toResourceName(this.databaseId,t.path)},t.prototype.fromName=function(t){var e=this.fromResourceName(t);return Jc(e.get(1)===this.databaseId.projectId,"Tried to deserialize key from different project: "+e.get(1)+" vs "+this.databaseId.projectId),Jc(!e.get(3)&&!this.databaseId.database||e.get(3)===this.databaseId.database,"Tried to deserialize key from different database: "+e.get(3)+" vs "+this.databaseId.database),new jh(this.extractLocalPathFromResourceName(e))},t.prototype.toQueryPath=function(t){return 0===t.length?this.encodedDatabaseId:this.toResourceName(this.databaseId,t)},t.prototype.fromQueryPath=function(t){var e=this.fromResourceName(t);return 4===e.length?Bh.EMPTY_PATH:this.extractLocalPathFromResourceName(e)},Object.defineProperty(t.prototype,"encodedDatabaseId",{get:function(){return new Bh(["projects",this.databaseId.projectId,"databases",this.databaseId.database]).canonicalString()},enumerable:!0,configurable:!0}),t.prototype.fullyQualifiedPrefixPath=function(t){return new Bh(["projects",t.projectId,"databases",t.database])},t.prototype.extractLocalPathFromResourceName=function(t){return Jc(t.length>4&&"documents"===t.get(4),"tried to deserialize invalid key "+t.toString()),t.popFirst(5)},t.prototype.isValidResourceName=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.toValue=function(t){if(t instanceof tl)return{nullValue:"NULL_VALUE"};if(t instanceof el)return{booleanValue:t.value()};if(t instanceof il)return{integerValue:""+t.value()};if(t instanceof ol){var e=t.value();if(this.options.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:t.value()}}return t instanceof sl?{stringValue:t.value()}:t instanceof fl?{mapValue:this.toMapValue(t)}:t instanceof pl?{arrayValue:this.toArrayValue(t)}:t instanceof al?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof ll?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof cl?{bytesValue:this.toBytes(t.value())}:t instanceof hl?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:Xc("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this,n=t.value_type;if(Pf(t,n,"nullValue"))return tl.INSTANCE;if(Pf(t,n,"booleanValue"))return el.of(t.booleanValue);if(Pf(t,n,"integerValue"))return new il(Rf(t.integerValue));if(Pf(t,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return ol.NAN;if("Infinity"===t.doubleValue)return ol.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return ol.NEGATIVE_INFINITY}return new ol(t.doubleValue)}if(Pf(t,n,"stringValue"))return new sl(t.stringValue);if(Pf(t,n,"mapValue"))return this.fromFields(t.mapValue.fields||{});if(Pf(t,n,"arrayValue")){kf(t.arrayValue,"arrayValue");var r=t.arrayValue.values||[];return new pl(r.map(function(t){return e.fromValue(t)}))}if(Pf(t,n,"timestampValue"))return kf(t.timestampValue,"timestampValue"),new al(this.fromTimestamp(t.timestampValue));if(Pf(t,n,"geoPointValue")){kf(t.geoPointValue,"geoPointValue");var i=t.geoPointValue.latitude||0,o=t.geoPointValue.longitude||0;return new ll(new Lh(i,o))}if(Pf(t,n,"bytesValue")){kf(t.bytesValue,"bytesValue");var s=this.fromBlob(t.bytesValue);return new cl(s)}if(Pf(t,n,"referenceValue")){kf(t.referenceValue,"referenceValue");var a=this.fromResourceName(t.referenceValue),u=new Uh(a.get(1),a.get(3)),c=new jh(this.extractLocalPathFromResourceName(a));return new hl(u,c)}return Xc("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return Jc(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t,e){return new Qh(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasCommittedMutations:!!e})},t.prototype.toFields=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.toValue(r)}),n},t.prototype.fromFields=function(t){var e=this,n=t,r=fl.EMPTY;return sh(n,function(t,n){r=r.set(new Wh([t]),e.fromValue(n))}),r},t.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},t.prototype.fromFound=function(t){Jc(!!t.found,"Tried to deserialize a found document from a missing document."),kf(t.found.name,"doc.found.name"),kf(t.found.updateTime,"doc.found.updateTime");var e=this.fromName(t.found.name),n=this.fromVersion(t.found.updateTime),r=this.fromFields(t.found.fields||{});return new Qh(e,n,r,{})},t.prototype.fromMissing=function(t){Jc(!!t.missing,"Tried to deserialize a missing document from a found document."),Jc(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.fromName(t.missing),n=this.fromVersion(t.readTime);return new Hh(e,n)},t.prototype.fromMaybeDocument=function(t){var e=t.result;return Pf(t,e,"found")?this.fromFound(t):Pf(t,e,"missing")?this.fromMissing(t):Xc("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case pf.Added:return"ADD";case pf.Current:return"CURRENT";case pf.NoChange:return"NO_CHANGE";case pf.Removed:return"REMOVE";case pf.Reset:return"RESET";default:return Xc("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof bf)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof vf){if(t.newDoc instanceof Qh){var e=t.newDoc;return{documentChange:{document:{name:this.toName(e.key),fields:this.toFields(e.data),updateTime:this.toVersion(e.version)},targetIds:t.updatedTargetIds,removedTargetIds:t.removedTargetIds}}}if(t.newDoc instanceof Hh){e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof _f){var n=void 0;return t.cause&&(n={code:function(t){if(void 0===t)return Yl.OK;switch(t){case th.OK:return Yl.OK;case th.CANCELLED:return Yl.CANCELLED;case th.UNKNOWN:return Yl.UNKNOWN;case th.DEADLINE_EXCEEDED:return Yl.DEADLINE_EXCEEDED;case th.RESOURCE_EXHAUSTED:return Yl.RESOURCE_EXHAUSTED;case th.INTERNAL:return Yl.INTERNAL;case th.UNAVAILABLE:return Yl.UNAVAILABLE;case th.UNAUTHENTICATED:return Yl.UNAUTHENTICATED;case th.INVALID_ARGUMENT:return Yl.INVALID_ARGUMENT;case th.NOT_FOUND:return Yl.NOT_FOUND;case th.ALREADY_EXISTS:return Yl.ALREADY_EXISTS;case th.PERMISSION_DENIED:return Yl.PERMISSION_DENIED;case th.FAILED_PRECONDITION:return Yl.FAILED_PRECONDITION;case th.ABORTED:return Yl.ABORTED;case th.OUT_OF_RANGE:return Yl.OUT_OF_RANGE;case th.UNIMPLEMENTED:return Yl.UNIMPLEMENTED;case th.DATA_LOSS:return Yl.DATA_LOSS;default:return Xc("Unknown status code: "+t)}}(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return Xc("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=t.response_type;if(Pf(t,n,"targetChange")){kf(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],o=t.targetChange.resumeToken||this.emptyByteString(),s=t.targetChange.cause,a=s&&this.fromRpcStatus(s);e=new _f(r,i,o,a||null)}else if(Pf(t,n,"documentChange")){kf(t.documentChange,"documentChange"),kf(t.documentChange.document,"documentChange.name"),kf(t.documentChange.document.name,"documentChange.document.name"),kf(t.documentChange.document.updateTime,"documentChange.document.updateTime");var u=t.documentChange,c=this.fromName(u.document.name),h=this.fromVersion(u.document.updateTime),l=this.fromFields(u.document.fields||{}),f=new Qh(c,h,l,{}),p=u.targetIds||[],d=u.removedTargetIds||[];e=new vf(p,d,f.key,f)}else if(Pf(t,n,"documentDelete")){kf(t.documentDelete,"documentDelete"),kf(t.documentDelete.document,"documentDelete.document");var y=t.documentDelete;c=this.fromName(y.document),h=y.readTime?this.fromVersion(y.readTime):Ol.forDeletedDoc(),f=new Hh(c,h),d=y.removedTargetIds||[];e=new vf([],d,f.key,f)}else if(Pf(t,n,"documentRemove")){kf(t.documentRemove,"documentRemove"),kf(t.documentRemove.document,"documentRemove");var m=t.documentRemove;c=this.fromName(m.document),d=m.removedTargetIds||[];e=new vf([],d,c,null)}else{if(!Pf(t,n,"filter"))return Xc("Unknown change type "+JSON.stringify(t));kf(t.filter,"filter"),kf(t.filter.targetId,"filter.targetId");var g=t.filter,v=g.count||0,b=new Xl(v),_=g.targetId;e=new bf(_,b)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?pf.NoChange:"ADD"===t?pf.Added:"REMOVE"===t?pf.Removed:"CURRENT"===t?pf.Current:"RESET"===t?pf.Reset:Xc("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!Pf(t,t.response_type,"targetChange"))return Ol.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?Ol.MIN:e.readTime?this.fromVersion(e.readTime):Ol.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof Vl)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof Kl)e={delete:this.toName(t.key)};else if(t instanceof Wl)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof jl))return Xc("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map(function(t){return n.toFieldTransform(t)})}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):ql.NONE;if(t.update){kf(t.update.name,"name");var r=this.fromName(t.update.name),i=this.fromFields(t.update.fields||{});if(t.updateMask){var o=this.fromDocumentMask(t.updateMask);return new Wl(r,i,o,n)}return new Vl(r,i,n)}if(t.delete){r=this.fromName(t.delete);return new Kl(r,n)}if(t.transform){r=this.fromName(t.transform.document);var s=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return Jc(!0===n.exists,'Transforms only support precondition "exists == true"'),new jl(r,s)}return Xc("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return Jc(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:Xc("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?ql.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?ql.exists(t.exists):ql.NONE},t.prototype.fromWriteResult=function(t,e){var n=this,r=t.updateTime?this.fromVersion(t.updateTime):this.fromVersion(e),i=null;return t.transformResults&&t.transformResults.length>0&&(i=t.transformResults.map(function(t){return n.fromValue(t)})),new Ul(r,i)},t.prototype.fromWriteResults=function(t,e){var n=this;return t&&t.length>0?(Jc(void 0!==e,"Received a write result without a commit time"),t.map(function(t){return n.fromWriteResult(t,e)})):[]},t.prototype.toFieldTransform=function(t){var e=this,n=t.transform;if(n instanceof Ql)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof Hl)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements.map(function(t){return e.toValue(t)})}};if(n instanceof Gl)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements.map(function(t){return e.toValue(t)})}};throw Xc("Unknown transform: "+t.transform)},t.prototype.fromFieldTransform=function(t){var e=this,n=t.transform_type,r=null;if(Pf(t,n,"setToServerValue"))Jc("REQUEST_TIME"===t.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(t)),r=Ql.instance;else if(Pf(t,n,"appendMissingElements")){var i=t.appendMissingElements.values||[];r=new Hl(i.map(function(t){return e.fromValue(t)}))}else if(Pf(t,n,"removeAllFromArray")){i=t.removeAllFromArray.values||[];r=new Gl(i.map(function(t){return e.fromValue(t)}))}else Xc("Unknown transform proto: "+JSON.stringify(t));var o=Wh.fromServerFormat(t.fieldPath);return new Fl(o,r)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;Jc(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return wl.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}};if(t.path.isEmpty())e.parent=this.toQueryPath(Bh.EMPTY_PATH);else{var n=t.path;Jc(n.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(n.popLast()),e.structuredQuery.from=[{collectionId:n.lastSegment()}]}var r=this.toFilter(t.filters);r&&(e.structuredQuery.where=r);var i=this.toOrder(t.orderBy);i&&(e.structuredQuery.orderBy=i);var o=this.toInt32Value(t.limit);return void 0!==o&&(e.structuredQuery.limit=o),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0;if(r>0){Jc(1===r,"StructuredQuery.from with more than one collection is not supported.");var i=n.from[0];e=e.child(i.collectionId)}var o=[];n.where&&(o=this.fromFilter(n.where));var s=[];n.orderBy&&(s=this.fromOrder(n.orderBy));var a=null;n.limit&&(a=this.fromInt32Value(n.limit));var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var c=null;return n.endAt&&(c=this.fromCursor(n.endAt)),new wl(e,s,o,a,u,c)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case _l.Listen:return null;case _l.ExistenceFilterMismatch:return"existence-filter-mismatch";case _l.LimboResolution:return"limbo-document";default:return Xc("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return(e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)}).targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(t){return t instanceof Sl?e.toRelationFilter(t):e.toUnaryFilter(t)});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromRelationFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):Xc("Unknown filter: "+JSON.stringify(t)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},t.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},t.prototype.toCursor=function(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},t.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new Dl(r,n)},t.prototype.toDirection=function(t){return Nf[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return Nl.ASCENDING;case"DESCENDING":return Nl.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return Df[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return Tl.EQUAL;case"GREATER_THAN":return Tl.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return Tl.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return Tl.LESS_THAN;case"LESS_THAN_OR_EQUAL":return Tl.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return Tl.ARRAY_CONTAINS;case"OPERATOR_UNSPECIFIED":return Xc("Unspecified relation");default:return Xc("Unknown relation")}},t.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return Wh.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new Al(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.toRelationFilter=function(t){return t instanceof Sl?{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}:Xc("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromRelationFilter=function(t){return new Sl(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},t.prototype.toUnaryFilter=function(t){return t instanceof Cl?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}}:t instanceof Il?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}:Xc("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return new Cl(e);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return new Il(n);case"OPERATOR_UNSPECIFIED":return Xc("Unspecified filter");default:return Xc("Unknown filter")}},t.prototype.toDocumentMask=function(t){var e=[];return t.fields.forEach(function(t){return e.push(t.canonicalString())}),{fieldPaths:e}},t.prototype.fromDocumentMask=function(t){var e=(t.fieldPaths||[]).map(function(t){return Wh.fromServerFormat(t)});return xl.fromArray(e)},t}();function Pf(t,e,n){return e===n||!e&&n in t}var Lf="FirebaseError",Mf=Error.captureStackTrace,xf=function(){return function(t,e){if(this.code=t,this.message=e,Mf)Mf(this,Ff.prototype.create);else try{throw Error.apply(this,arguments)}catch(t){this.name=Lf,Object.defineProperty(this,"stack",{get:function(){return t.stack}})}}}();xf.prototype=Object.create(Error.prototype),xf.prototype.constructor=xf,xf.prototype.name=Lf;var Ff=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n,this.pattern=/\{\$([^}]+)}/g}return t.prototype.create=function(t,e){void 0===e&&(e={});var n,r=this.errors[t],i=this.service+"/"+t;n=void 0===r?"Error":r.replace(this.pattern,function(t,n){var r=e[n];return void 0!==r?r.toString():"<"+n+"?>"}),n=this.serviceName+": "+n+" ("+i+").";var o=new xf(i,n);for(var s in e)e.hasOwnProperty(s)&&"_"!==s.slice(-1)&&(o[s]=e[s]);return o},t}(),Uf=(function(t){function e(){var e=t.call(this)||this;e.chain_=[],e.buf_=[],e.W_=[],e.pad_=[],e.inbuf_=0,e.total_=0,e.blockSize=64,e.pad_[0]=128;for(var n=1;n<e.blockSize;++n)e.pad_[n]=0;return e.reset(),e}Xe(e,t),e.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},e.prototype.compress_=function(t,e){e||(e=0);var n=this.W_;if("string"==typeof t)for(var r=0;r<16;r++)n[r]=t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|t.charCodeAt(e+3),e+=4;else for(r=0;r<16;r++)n[r]=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3],e+=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,s,a=this.chain_[0],u=this.chain_[1],c=this.chain_[2],h=this.chain_[3],l=this.chain_[4];for(r=0;r<80;r++){r<40?r<20?(o=h^u&(c^h),s=1518500249):(o=u^c^h,s=1859775393):r<60?(o=u&c|h&(u|c),s=2400959708):(o=u^c^h,s=3395469782);i=(a<<5|a>>>27)+o+l+s+n[r]&4294967295;l=h,h=c,c=4294967295&(u<<30|u>>>2),u=a,a=i}this.chain_[0]=this.chain_[0]+a&4294967295,this.chain_[1]=this.chain_[1]+u&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+h&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295},e.prototype.update=function(t,e){if(null!=t){void 0===e&&(e=t.length);for(var n=e-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r<e;){if(0==o)for(;r<=n;)this.compress_(t,r),r+=this.blockSize;if("string"==typeof t){for(;r<e;)if(i[o]=t.charCodeAt(r),++r,++o==this.blockSize){this.compress_(i),o=0;break}}else for(;r<e;)if(i[o]=t[r],++r,++o==this.blockSize){this.compress_(i),o=0;break}}this.inbuf_=o,this.total_+=e}},e.prototype.digest=function(){var t=[],e=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&e,e/=256;this.compress_(this.buf_);var r=0;for(n=0;n<5;n++)for(var i=24;i>=0;i-=8)t[r]=this.chain_[n]>>i&255,++r;return t}}(function(){return function(){this.blockSize=-1}}()),function(){function t(t){this.sendFn=t.sendFn,this.closeFn=t.closeFn}return t.prototype.onOpen=function(t){Jc(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},t.prototype.onClose=function(t){Jc(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},t.prototype.onMessage=function(t){Jc(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},t.prototype.close=function(){this.closeFn()},t.prototype.send=function(t){this.sendFn(t)},t.prototype.callOnOpen=function(){Jc(void 0!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},t.prototype.callOnClose=function(t){Jc(void 0!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},t.prototype.callOnMessage=function(t){Jc(void 0!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},t}()),qf="Connection",Bf={BatchGetDocuments:"batchGet",Commit:"commit"},Vf="gl-js/ fire/"+jc,Wf=function(){function t(t){this.databaseId=t.databaseId,this.pool=new Wc;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host}return t.prototype.modifyHeadersForRequest=function(t,e){if(e)for(var n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n]);t["X-Goog-Api-Client"]=Vf},t.prototype.invokeRPC=function(t,e,n){var r=this,i=this.makeUrl(t);return new Promise(function(o,s){r.pool.getObject(function(a){a.listenOnce(Bc.COMPLETE,function(){try{switch(a.getLastErrorCode()){case qc.NO_ERROR:var e=a.getResponseJson();Gc(qf,"XHR received:",JSON.stringify(e)),o(e);break;case qc.TIMEOUT:Gc(qf,'RPC "'+t+'" timed out'),s(new eh(th.DEADLINE_EXCEEDED,"Request time out"));break;case qc.HTTP_ERROR:var n=a.getStatus();Gc(qf,'RPC "'+t+'" failed with status:',n,"response text:",a.getResponseText()),n>0?s(new eh(function(t){switch(t){case 200:return th.OK;case 400:return th.INVALID_ARGUMENT;case 401:return th.UNAUTHENTICATED;case 403:return th.PERMISSION_DENIED;case 404:return th.NOT_FOUND;case 409:return th.ABORTED;case 416:return th.OUT_OF_RANGE;case 429:return th.RESOURCE_EXHAUSTED;case 499:return th.CANCELLED;case 500:return th.UNKNOWN;case 501:return th.UNIMPLEMENTED;case 503:return th.UNAVAILABLE;case 504:return th.DEADLINE_EXCEEDED;default:return t>=200&&t<300?th.OK:t>=400&&t<500?th.FAILED_PRECONDITION:t>=500&&t<600?th.INTERNAL:th.UNKNOWN}}(n),"Server responded with status "+a.getStatusText())):(Gc(qf,'RPC "'+t+'" failed'),s(new eh(th.UNAVAILABLE,"Connection failed.")));break;default:Xc('RPC "'+t+'" failed with unanticipated webchannel error '+a.getLastErrorCode()+": "+a.getLastError()+", giving up.")}}finally{Gc(qf,'RPC "'+t+'" completed.'),r.pool.releaseObject(a)}});var u=JSON.stringify(e);Gc(qf,"XHR sending: ",i+" "+u);var c={"Content-Type":"text/plain"};r.modifyHeadersForRequest(c,n),a.send(i,"POST",u,c,15)})})},t.prototype.invokeStreamingRPC=function(t,e,n){return this.invokeRPC(t,e,n)},t.prototype.openStream=function(t,e){var n=[this.baseUrl,"/","google.firestore.v1beta1.Firestore","/",t,"/channel"],r=Uc(),i={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(i.initMessageHeaders,e),"object"==typeof navigator&&"ReactNative"===navigator.product||(i.httpHeadersOverwriteParam="$httpHeaders");var o=n.join("");Gc(qf,"Creating WebChannel: "+o+" "+i);var s=r.createWebChannel(o,i),a=!1,u=!1,c=new Uf({sendFn:function(t){u?Gc(qf,"Not sending because WebChannel is closed:",t):(a||(Gc(qf,"Opening WebChannel transport."),s.open(),a=!0),Gc(qf,"WebChannel sending:",t),s.send(t))},closeFn:function(){return s.close()}}),h=function(t,e){s.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})};return h(Vc.EventType.OPEN,function(){u||Gc(qf,"WebChannel transport opened.")}),h(Vc.EventType.CLOSE,function(){u||(u=!0,Gc(qf,"WebChannel transport closed"),c.callOnClose())}),h(Vc.EventType.ERROR,function(t){u||(u=!0,Gc(qf,"WebChannel transport errored:",t),c.callOnClose(new eh(th.UNAVAILABLE,"The operation could not be completed")))}),h(Vc.EventType.MESSAGE,function(t){if(!u){var e=t.data[0];Jc(!!e,"Got a webchannel message without data.");var n=e.error||e[0]&&e[0].error;if(n){Gc(qf,"WebChannel received error:",n);var r=n.status,i=function(t){var e=Yl[t];if(void 0!==e)return $l(e)}(r),o=n.message;void 0===i&&(i=th.INTERNAL,o="Unknown error status: "+r+" with message "+n.message),u=!0,c.callOnClose(new eh(i,o)),s.close()}else Gc(qf,"WebChannel received:",e),c.callOnMessage(e)}}),setTimeout(function(){c.callOnOpen()},0),c},t.prototype.makeUrl=function(t){var e=Bf[t];Jc(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1beta1"];return n.push("/projects/"),n.push(this.databaseId.projectId),n.push("/databases/"),n.push(this.databaseId.database),n.push("/documents"),n.push(":"),n.push(e),n.join("")},t}(),jf=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return Object.defineProperty(t.prototype,"document",{get:function(){return"undefined"!=typeof document?document:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"window",{get:function(){return"undefined"!=typeof window?window:null},enumerable:!0,configurable:!0}),t.prototype.loadConnection=function(t){return Promise.resolve(new Wf(t))},t.prototype.newSerializer=function(t){return new Of(t,{useProto3Json:!0})},t.prototype.formatJSON=function(t){return JSON.stringify(t)},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();$c.setPlatform(new jf);var Kf,Qf=function(){function t(t,e){var n=this;this.previousValue=t,e&&(e.sequenceNumberHandler=function(t){return n.setPreviousValue(t)},this.writeNewSequenceNumber=function(t){return e.writeSequenceNumber(t)})}return t.prototype.setPreviousValue=function(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue},t.prototype.next=function(){var t=++this.previousValue;return this.writeNewSequenceNumber&&this.writeNewSequenceNumber(t),t},t.INVALID=-1,t}(),Hf=function(){return function(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}}();!function(t){t.All="all",t.ListenStreamIdle="listen_stream_idle",t.ListenStreamConnectionBackoff="listen_stream_connection_backoff",t.WriteStreamIdle="write_stream_idle",t.WriteStreamConnectionBackoff="write_stream_connection_backoff",t.OnlineStateTimeout="online_state_timeout",t.ClientMetadataRefresh="client_metadata_refresh",t.LruGarbageCollection="lru_garbage_collection"}(Kf||(Kf={}));var Gf=function(){function t(t,e,n,r,i){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new Hf,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.catch=this.deferred.promise.catch.bind(this.deferred.promise),this.deferred.promise.catch(function(t){})}return t.createAndSchedule=function(e,n,r,i,o){var s=new t(e,n,Date.now()+r,i,o);return s.start(r),s},t.prototype.start=function(t){var e=this;this.timerHandle=setTimeout(function(){return e.handleDelayElapsed()},t)},t.prototype.skipDelay=function(){return this.handleDelayElapsed()},t.prototype.cancel=function(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new eh(th.CANCELLED,"Operation cancelled"+(t?": "+t:""))))},t.prototype.handleDelayElapsed=function(){var t=this;this.asyncQueue.enqueueAndForget(function(){return null!==t.timerHandle?(t.clearTimeout(),t.op().then(function(e){return t.deferred.resolve(e)})):Promise.resolve()})},t.prototype.clearTimeout=function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)},t}(),zf=function(){function t(){this.tail=Promise.resolve(),this.delayedOperations=[],this.operationInProgress=!1}return t.prototype.enqueueAndForget=function(t){this.enqueue(t)},t.prototype.enqueue=function(t){var e=this;this.verifyNotFailed();var n=this.tail.then(function(){return e.operationInProgress=!0,t().catch(function(t){e.failure=t,e.operationInProgress=!1;var n=t.stack||t.message||"";throw zc("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout(function(){throw t},0),t}).then(function(t){return e.operationInProgress=!1,t})});return this.tail=n,n},t.prototype.enqueueAfterDelay=function(t,e,n){var r=this;this.verifyNotFailed(),Jc(e>=0,"Attempted to schedule an operation with a negative delay of "+e),Jc(!this.containsDelayedOperation(t),"Attempted to schedule multiple operations with timer id "+t+".");var i=Gf.createAndSchedule(this,t,e,n,function(t){return r.removeDelayedOperation(t)});return this.delayedOperations.push(i),i},t.prototype.verifyNotFailed=function(){this.failure&&Xc("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},t.prototype.verifyOperationInProgress=function(){Jc(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(){return this.enqueue(function(){return Promise.resolve()})},t.prototype.containsDelayedOperation=function(t){for(var e=0,n=this.delayedOperations;e<n.length;e++){if(n[e].timerId===t)return!0}return!1},t.prototype.runDelayedOperationsEarly=function(t){var e=this;return this.drain().then(function(){Jc(t===Kf.All||e.containsDelayedOperation(t),"Attempted to drain to missing operation "+t),e.delayedOperations.sort(function(t,e){return t.targetTimeMs-e.targetTimeMs});for(var n=0,r=e.delayedOperations;n<r.length;n++){var i=r[n];if(i.skipDelay(),t!==Kf.All&&i.timerId===t)break}return e.drain()})},t.prototype.removeDelayedOperation=function(t){var e=this.delayedOperations.indexOf(t);Jc(e>=0,"Delayed operation not found."),this.delayedOperations.splice(e,1)},t}(),Yf="",Xf="",Jf="",$f="";function Zf(t){for(var e="",n=0;n<t.length;n++)e.length>0&&(e=ep(e)),e=tp(t.get(n),e);return ep(e)}function tp(t,e){for(var n=e,r=t.length,i=0;i<r;i++){var o=t.charAt(i);switch(o){case"\0":n+=Yf+Jf;break;case Yf:n+=Yf+$f;break;default:n+=o}}return n}function ep(t){return t+Yf+Xf}function np(t){var e=t.length;if(Jc(e>=2,"Invalid path "+t),2===e)return Jc(t.charAt(0)===Yf&&t.charAt(1)===Xf,"Non-empty path "+t+" had length 2"),Bh.EMPTY_PATH;for(var n=e-2,r=[],i="",o=0;o<e;){var s=t.indexOf(Yf,o);switch((s<0||s>n)&&Xc('Invalid encoded resource path: "'+t+'"'),t.charAt(s+1)){case Xf:var a=t.substring(o,s),u=void 0;0===i.length?u=a:(u=i+=a,i=""),r.push(u);break;case Jf:i+=t.substring(o,s),i+="\0";break;case $f:i+=t.substring(o,s+1);break;default:Xc('Invalid encoded resource path: "'+t+'"')}o=s+2}return new Bh(r)}var rp,ip=-1,op=function(){function t(t,e,n){this.batchId=t,this.localWriteTime=e,this.mutations=n,Jc(n.length>0,"Cannot create an empty mutation batch")}return t.prototype.applyToRemoteDocument=function(t,e,n){e&&Jc(e.key.isEqual(t),"applyToRemoteDocument: key "+t+" should match maybeDoc key\n "+e.key);var r=n.mutationResults;Jc(r.length===this.mutations.length,"Mismatch between mutations length\n ("+this.mutations.length+") and mutation results length\n ("+r.length+").");for(var i=0;i<this.mutations.length;i++){var o=this.mutations[i];if(o.key.isEqual(t)){var s=r[i];e=o.applyToRemoteDocument(e,s)}}return e},t.prototype.applyToLocalView=function(t,e){e&&Jc(e.key.isEqual(t),"applyToLocalDocument: key "+t+" should match maybeDoc key\n "+e.key);for(var n=e,r=0;r<this.mutations.length;r++){var i=this.mutations[r];i.key.isEqual(t)&&(e=i.applyToLocalView(e,n,this.localWriteTime))}return e},t.prototype.keys=function(){for(var t=af(),e=0,n=this.mutations;e<n.length;e++){var r=n[e];t=t.add(r.key)}return t},t.prototype.isEqual=function(t){return this.batchId===t.batchId&&Nh(this.mutations,t.mutations)},t}(),sp=function(){function t(t,e,n,r,i){this.batch=t,this.commitVersion=e,this.mutationResults=n,this.streamToken=r,this.docVersions=i}return t.from=function(e,n,r,i){Jc(e.mutations.length===r.length,"Mutations sent "+e.mutations.length+" must equal results received "+r.length);for(var o=of(),s=e.mutations,a=0;a<s.length;a++)o=o.insert(s[a].key,r[a].version);return new t(e,n,r,i,o)},t}(),ap=1;!function(t){t[t.QueryCache=0]="QueryCache",t[t.SyncEngine=1]="SyncEngine"}(rp||(rp={}));var up=function(){function t(t,e){this.generatorId=t,Jc((t&ap)===t,"Generator ID "+t+" contains more than "+ap+" reserved bits"),this.seek(void 0!==e?e:this.generatorId)}return t.prototype.next=function(){var t=this.nextId;return this.nextId+=1<<ap,t},t.prototype.after=function(t){return this.seek(t+(1<<ap)),this.next()},t.prototype.seek=function(t){Jc((t&ap)===this.generatorId,"Cannot supply target ID from different generator ID"),this.nextId=t},t.forQueryCache=function(){return new t(rp.QueryCache,2)},t.forSyncEngine=function(){return new t(rp.SyncEngine)},t}(),cp=function(){function t(t){var e=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,t(function(t){e.isDone=!0,e.result=t,e.nextCallback&&e.nextCallback(t)},function(t){e.isDone=!0,e.error=t,e.catchCallback&&e.catchCallback(t)})}return t.prototype.catch=function(t){return this.next(void 0,t)},t.prototype.next=function(e,n){var r=this;return this.callbackAttached&&Xc("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(e,this.result):new t(function(t,i){r.nextCallback=function(n){r.wrapSuccess(e,n).next(t,i)},r.catchCallback=function(e){r.wrapFailure(n,e).next(t,i)}})},t.prototype.toPromise=function(){var t=this;return new Promise(function(e,n){t.next(e,n)})},t.prototype.wrapUserFunction=function(e){try{var n=e();return n instanceof t?n:t.resolve(n)}catch(e){return t.reject(e)}},t.prototype.wrapSuccess=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.resolve(n)},t.prototype.wrapFailure=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.reject(n)},t.resolve=function(e){return new t(function(t,n){t(e)})},t.reject=function(e){return new t(function(t,n){n(e)})},t.waitFor=function(e){return new t(function(t,n){var r=0,i=0,o=!1;e.forEach(function(e){++r,e.next(function(){++i,o&&i===r&&t()},function(t){return n(t)})}),o=!0,i===r&&t()})},t.or=function(e){for(var n=t.resolve(!1),r=function(e){n=n.next(function(n){return n?t.resolve(n):e()})},i=0,o=e;i<o.length;i++){r(o[i])}return n},t.forEach=function(t,e){var n=this,r=[];return t.forEach(function(t,i){r.push(e.call(n,t,i))}),this.waitFor(r)},t}(),hp=function(){function t(t){this.db=t}return t.openOrCreate=function(e,n,r){return Jc(t.isAvailable(),"IndexedDB not supported in current environment."),Gc("SimpleDb","Opening database:",e),new cp(function(i,o){var s=window.indexedDB.open(e,n);s.onsuccess=function(e){var n=e.target.result;i(new t(n))},s.onblocked=function(){o(new eh(th.FAILED_PRECONDITION,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},s.onerror=function(t){o(t.target.error)},s.onupgradeneeded=function(t){Gc("SimpleDb",'Database "'+e+'" requires upgrade from version:',t.oldVersion);var n=t.target.result,i=new fp(s.transaction);r.createOrUpgrade(n,i,t.oldVersion,kp).next(function(){Gc("SimpleDb","Database upgrade to version "+kp+" complete")})}}).toPromise()},t.delete=function(t){return Gc("SimpleDb","Removing database:",t),dp(window.indexedDB.deleteDatabase(t)).toPromise()},t.isAvailable=function(){if("undefined"==typeof window||null==window.indexedDB)return!1;if(void 0===window.navigator)return"YES"===process.env.USE_MOCK_PERSISTENCE;var t=window.navigator.userAgent;return!(t.indexOf("MSIE ")>0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0)},t.getStore=function(t,e){return t.store(e)},t.prototype.runTransaction=function(t,e,n){var r=fp.open(this.db,t,e),i=n(r).catch(function(t){r.abort(t)}).toPromise();return r.completionPromise.then(function(){return i})},t.prototype.close=function(){this.db.close()},t}(),lp=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return dp(this.dbCursor.delete())},t}(),fp=function(){function t(t){var e=this;this.transaction=t,this.aborted=!1,this.completionDeferred=new Hf,this.transaction.oncomplete=function(){e.completionDeferred.resolve()},this.transaction.onabort=function(){t.error?e.completionDeferred.reject(t.error):e.completionDeferred.resolve()},this.transaction.onerror=function(t){e.completionDeferred.reject(t.target.error)}}return t.open=function(e,n,r){return new t(e.transaction(r,n))},Object.defineProperty(t.prototype,"completionPromise",{get:function(){return this.completionDeferred.promise},enumerable:!0,configurable:!0}),t.prototype.abort=function(t){t&&this.completionDeferred.reject(t),this.aborted||(Gc("SimpleDb","Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return Jc(!!e,"Object store not part of transaction: "+t),new pp(e)},t}(),pp=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(Gc("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(Gc("SimpleDb","PUT",this.store.name,"<auto-key>",t),n=this.store.put(t)),dp(n)},t.prototype.add=function(t){return Gc("SimpleDb","ADD",this.store.name,t,t),dp(this.store.add(t))},t.prototype.get=function(t){var e=this;return dp(this.store.get(t)).next(function(n){return void 0===n&&(n=null),Gc("SimpleDb","GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return Gc("SimpleDb","DELETE",this.store.name,t),dp(this.store.delete(t))},t.prototype.count=function(){return Gc("SimpleDb","COUNT",this.store.name),dp(this.store.count())},t.prototype.loadAll=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.iterateCursor(n,function(t,e){r.push(e)}).next(function(){return r})},t.prototype.deleteAll=function(t,e){Gc("SimpleDb","DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},t.prototype.iterateSerial=function(t){var e=this.cursor({});return new cp(function(n,r){e.onerror=function(t){r(t.target.error)},e.onsuccess=function(e){var r=e.target.result;r?t(r.primaryKey,r.value).next(function(t){t?r.continue():n()}):n()}})},t.prototype.iterateCursor=function(t,e){var n=[];return new cp(function(r,i){t.onerror=function(t){i(t.target.error)},t.onsuccess=function(t){var i=t.target.result;if(i){var o=new lp(i),s=e(i.primaryKey,i.value,o);if(s instanceof cp){var a=s.catch(function(t){return o.done(),cp.reject(t)});n.push(a)}o.isDone?r():null===o.skipToKey?i.continue():i.continue(o.skipToKey)}else r()}}).next(function(){return cp.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(Jc(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}();function dp(t){return new cp(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){n(t.target.error)}})}var yp=function(){function t(t,e){this.referenceDelegate=t,this.serializer=e,this.targetIdGenerator=up.forQueryCache()}return t.prototype.allocateTargetId=function(t){var e=this;return this.retrieveMetadata(t).next(function(n){return n.highestTargetId=e.targetIdGenerator.after(n.highestTargetId),e.saveMetadata(t,n).next(function(){return n.highestTargetId})})},t.prototype.getLastRemoteSnapshotVersion=function(t){return this.retrieveMetadata(t).next(function(t){return Ol.fromTimestamp(new Mh(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds))})},t.prototype.getHighestSequenceNumber=function(t){return vp(t.simpleDbTransaction)},t.prototype.setTargetsMetadata=function(t,e,n){var r=this;return this.retrieveMetadata(t).next(function(i){return i.highestListenSequenceNumber=e,n&&(i.lastRemoteSnapshotVersion=n.toTimestamp()),e>i.highestListenSequenceNumber&&(i.highestListenSequenceNumber=e),r.saveMetadata(t,i)})},t.prototype.addQueryData=function(t,e){var n=this;return this.saveQueryData(t,e).next(function(){return n.retrieveMetadata(t).next(function(r){return r.targetCount+=1,n.updateMetadataFromQueryData(e,r),n.saveMetadata(t,r)})})},t.prototype.updateQueryData=function(t,e){return this.saveQueryData(t,e)},t.prototype.removeQueryData=function(t,e){var n=this;return this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){return mp(t).delete(e.targetId)}).next(function(){return n.retrieveMetadata(t)}).next(function(e){return Jc(e.targetCount>0,"Removing from an empty query cache"),e.targetCount-=1,n.saveMetadata(t,e)})},t.prototype.removeTargets=function(t,e,n){var r=this,i=0,o=[];return mp(t).iterate(function(s,a){var u=r.serializer.fromDbTarget(a);u.sequenceNumber<=e&&void 0===n[u.targetId]&&(i++,o.push(r.removeQueryData(t,u)))}).next(function(){return cp.waitFor(o)}).next(function(){return i})},t.prototype.forEachTarget=function(t,e){var n=this;return mp(t).iterate(function(t,r){var i=n.serializer.fromDbTarget(r);e(i)})},t.prototype.retrieveMetadata=function(t){return gp(t.simpleDbTransaction)},t.prototype.saveMetadata=function(t,e){return(n=t,pd.getStore(n,jp.store)).put(jp.key,e);var n},t.prototype.saveQueryData=function(t,e){return mp(t).put(this.serializer.toDbTarget(e))},t.prototype.updateMetadataFromQueryData=function(t,e){var n=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n},t.prototype.getQueryCount=function(t){return this.retrieveMetadata(t).next(function(t){return t.targetCount})},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),i=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),o=null;return mp(t).iterate({range:i,index:Vp.queryTargetsIndexName},function(t,r,i){var s=n.serializer.fromDbTarget(r);e.isEqual(s.query)&&(o=s,i.done())}).next(function(){return o})},t.prototype.addMatchingKeys=function(t,e,n){var r=this,i=[],o=bp(t);return e.forEach(function(e){var s=Zf(e.path);i.push(o.put(new Wp(n,s))),i.push(r.referenceDelegate.addReference(t,e))}),cp.waitFor(i)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,i=bp(t);return cp.forEach(e,function(e){var o=Zf(e.path);return cp.waitFor([i.delete([n,o]),r.referenceDelegate.removeReference(t,e)])})},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=bp(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=bp(t),i=af();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=np(t[1]),o=new jh(r);i=i.add(o)}).next(function(){return i})},t.prototype.containsKey=function(t,e){var n,r=Zf(e.path),i=IDBKeyRange.bound([r],[(n=r,n+"\0")],!1,!0),o=0;return bp(t).iterate({index:Wp.documentTargetsIndex,keysOnly:!0,range:i},function(t,e,n){var r=t[0];t[1];0!==r&&(o++,n.done())}).next(function(){return o>0})},t.prototype.getQueryDataForTarget=function(t,e){var n=this;return mp(t).get(e).next(function(t){return t?n.serializer.fromDbTarget(t):null})},t}();function mp(t){return pd.getStore(t,Vp.store)}function gp(t){return hp.getStore(t,jp.store).get(jp.key).next(function(t){return Jc(null!==t,"Missing metadata row."),t})}function vp(t){return gp(t).next(function(t){return t.highestListenSequenceNumber})}function bp(t){return pd.getStore(t,Wp.store)}var _p=function(){function t(t){this.mapKeyFn=t,this.inner={}}return t.prototype.get=function(t){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0!==n)for(var r=0,i=n;r<i.length;r++){var o=i[r],s=o[0],a=o[1];if(s.isEqual(t))return a}},t.prototype.has=function(t){return void 0!==this.get(t)},t.prototype.set=function(t,e){var n=this.mapKeyFn(t),r=this.inner[n];if(void 0!==r){for(var i=0;i<r.length;i++)if(r[i][0].isEqual(t))return void(r[i]=[t,e]);r.push([t,e])}else this.inner[n]=[[t,e]]},t.prototype.delete=function(t){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0===n)return!1;for(var r=0;r<n.length;r++)if(n[r][0].isEqual(t))return 1===n.length?delete this.inner[e]:n.splice(r,1),!0;return!1},t.prototype.forEach=function(t){sh(this.inner,function(e,n){for(var r=0,i=n;r<i.length;r++){var o=i[r],s=o[0],a=o[1];t(s,a)}})},t.prototype.isEmpty=function(){return ah(this.inner)},t}(),wp=function(){function t(){this.changes=tf(),this.documentSizes=new _p(function(t){return t.toString()})}return t.prototype.addEntry=function(t){var e=this.assertChanges();this.changes=e.insert(t.key,t)},t.prototype.getEntry=function(t,e){var n=this,r=this.assertChanges().get(e);return r?cp.resolve(r):this.getFromCache(t,e).next(function(t){return null===t?(n.documentSizes.set(e,0),null):(n.documentSizes.set(e,t.size),t.maybeDocument)})},t.prototype.apply=function(t){var e=this.applyChanges(t);return this.changes=null,e},t.prototype.assertChanges=function(){return Jc(null!==this.changes,"Changes have already been applied."),this.changes},t}(),Ep="The remote document changelog no longer contains all changes for all local query views. It may be necessary to rebuild these views.",Tp=function(){function t(t,e){this.serializer=t,this.keepDocumentChangeLog=e,this._lastProcessedDocumentChangeId=0}return Object.defineProperty(t.prototype,"lastProcessedDocumentChangeId",{get:function(){return this._lastProcessedDocumentChangeId},enumerable:!0,configurable:!0}),t.prototype.start=function(t){var e=hp.getStore(t,Qp.store);return this.synchronizeLastDocumentChangeId(e)},t.prototype.addEntries=function(t,e,n){var r=[];if(e.length>0){for(var i=Cp(t),o=af(),s=0,a=e;s<a.length;s++){var u=a[s],c=u.key,h=u.doc;r.push(i.put(Dp(c),h)),o=o.add(c)}this.keepDocumentChangeLog&&r.push(Np(t).put({changes:this.serializer.toDbResourcePaths(o)})),r.push(this.updateSize(t,n))}return cp.waitFor(r)},t.prototype.removeEntry=function(t,e){var n=Cp(t),r=Dp(e);return n.get(r).next(function(t){return t?n.delete(r).next(function(){return Ap(t)}):cp.resolve(0)})},t.prototype.getEntry=function(t,e){var n=this;return Cp(t).get(Dp(e)).next(function(t){return t?n.serializer.fromDbRemoteDocument(t):null})},t.prototype.getSizedEntry=function(t,e){var n=this;return Cp(t).get(Dp(e)).next(function(t){return t?{maybeDocument:n.serializer.fromDbRemoteDocument(t),size:Ap(t)}:null})},t.prototype.getDocumentsMatchingQuery=function(t,e){var n=this,r=nf(),i=e.path.toArray(),o=IDBKeyRange.lowerBound(i);return Cp(t).iterate({range:o},function(t,i,o){var s=n.serializer.fromDbRemoteDocument(i);e.path.isPrefixOf(s.key.path)?s instanceof Qh&&e.matches(s)&&(r=r.insert(s.key,s)):o.done()}).next(function(){return r})},t.prototype.getNewDocumentChanges=function(t){var e=this;Jc(this.keepDocumentChangeLog,"Can only call getNewDocumentChanges() when document change log is enabled");var n=af(),r=tf(),i=IDBKeyRange.lowerBound(this._lastProcessedDocumentChangeId+1),o=!0,s=Np(t);return s.iterate({range:i},function(t,r){if(o&&(o=!1,e._lastProcessedDocumentChangeId+1!==r.id))return e.synchronizeLastDocumentChangeId(s).next(function(){return cp.reject(new eh(th.DATA_LOSS,Ep))});n=n.unionWith(e.serializer.fromDbResourcePaths(r.changes)),e._lastProcessedDocumentChangeId=r.id}).next(function(){var i=[];return n.forEach(function(n){i.push(e.getEntry(t,n).next(function(t){var e=t||new Hh(n,Ol.forDeletedDoc());r=r.insert(n,e)}))}),cp.waitFor(i)}).next(function(){return r})},t.prototype.removeDocumentChangesThroughChangeId=function(t,e){var n=IDBKeyRange.upperBound(e);return Np(t).delete(n)},t.prototype.synchronizeLastDocumentChangeId=function(t){var e=this;return this._lastProcessedDocumentChangeId=0,t.iterate({keysOnly:!0,reverse:!0},function(t,n,r){e._lastProcessedDocumentChangeId=t,r.done()})},t.prototype.newChangeBuffer=function(){return new Ip(this)},t.prototype.getSize=function(t){return this.getMetadata(t).next(function(t){return t.byteSize})},t.prototype.getMetadata=function(t){return Sp(t).get(Bp.key).next(function(t){return Jc(!!t,"Missing document cache metadata"),t})},t.prototype.setMetadata=function(t,e){return Sp(t).put(Bp.key,e)},t.prototype.updateSize=function(t,e){var n=this;return this.getMetadata(t).next(function(r){return r.byteSize+=e,n.setMetadata(t,r)})},t}();function Sp(t){return pd.getStore(t,Bp.store)}var Ip=function(t){function e(e){var n=t.call(this)||this;return n.documentCache=e,n}return Xe(e,t),e.prototype.applyChanges=function(t){var e=this,n=0,r=[];return this.assertChanges().forEach(function(t,i){var o=e.documentCache.serializer.toDbRemoteDocument(i),s=e.documentSizes.get(t);Jc(void 0!==s,"Attempting to change document "+t.toString()+" without having read it first");var a=Ap(o);n+=a-s,r.push({key:t,doc:o})}),this.documentCache.addEntries(t,r,n)},e.prototype.getFromCache=function(t,e){return this.documentCache.getSizedEntry(t,e)},e}(wp);function Cp(t){return pd.getStore(t,qp.store)}function Np(t){return pd.getStore(t,Qp.store)}function Dp(t){return t.path.toArray()}function Ap(t){var e;if(t.document)e=t.document;else if(t.unknownDocument)e=t.unknownDocument;else{if(!t.noDocument)throw Xc("Unknown remote document type");e=t.noDocument}return JSON.stringify(e).length}var kp=7,Rp=function(){function t(t){this.serializer=t}return t.prototype.createOrUpgrade=function(t,e,n,r){var i=this;Jc(n<r&&n>=0&&r<=kp,"Unexpected schema upgrade from v"+n+" to v{toVersion}."),n<1&&r>=1&&(function(t){t.createObjectStore(Pp.store)}(t),function(t){t.createObjectStore(Lp.store,{keyPath:Lp.keyPath}),t.createObjectStore(Mp.store,{keyPath:Mp.keyPath,autoIncrement:!0}).createIndex(Mp.userMutationsIndex,Mp.userMutationsKeyPath,{unique:!0}),t.createObjectStore(xp.store)}(t),Kp(t),function(t){t.createObjectStore(qp.store)}(t));var o=cp.resolve();return n<3&&r>=3&&(0!==n&&(!function(t){t.deleteObjectStore(Wp.store),t.deleteObjectStore(Vp.store),t.deleteObjectStore(jp.store)}(t),Kp(t)),o=o.next(function(){return function(t){var e=t.store(jp.store),n=new jp(0,0,Ol.MIN.toTimestamp(),0);return e.put(jp.key,n)}(e)})),n<4&&r>=4&&(0!==n&&(o=o.next(function(){return function(t,e){return e.store(Mp.store).loadAll().next(function(n){t.deleteObjectStore(Mp.store);var r=t.createObjectStore(Mp.store,{keyPath:Mp.keyPath,autoIncrement:!0});r.createIndex(Mp.userMutationsIndex,Mp.userMutationsKeyPath,{unique:!0});var i=e.store(Mp.store),o=n.map(function(t){return i.put(t)});return cp.waitFor(o)})}(t,e)})),o=o.next(function(){!function(t){t.createObjectStore(Hp.store,{keyPath:Hp.keyPath})}(t),function(t){t.createObjectStore(Qp.store,{keyPath:"id",autoIncrement:!0})}(t)})),n<5&&r>=5&&(o=o.next(function(){return i.removeAcknowledgedMutations(e)})),n<6&&r>=6&&(o=o.next(function(){return function(t){t.createObjectStore(Bp.store)}(t),i.addDocumentGlobal(e)})),n<7&&r>=7&&(o=o.next(function(){return i.ensureSequenceNumbers(e)})),o},t.prototype.addDocumentGlobal=function(t){var e=0;return t.store(qp.store).iterate(function(t,n){e+=Ap(n)}).next(function(){var n=new Bp(e);return t.store(Bp.store).put(Bp.key,n)})},t.prototype.removeAcknowledgedMutations=function(t){var e=this,n=t.store(Lp.store),r=t.store(Mp.store);return n.loadAll().next(function(n){return cp.forEach(n,function(n){var i=IDBKeyRange.bound([n.userId,ip],[n.userId,n.lastAcknowledgedBatchId]);return r.loadAll(Mp.userMutationsIndex,i).next(function(r){return cp.forEach(r,function(r){Jc(r.userId===n.userId,"Cannot process batch "+r.batchId+" from unexpected user");var i=e.serializer.fromDbMutationBatch(r);return Xp(t,n.userId,i).next(function(){})})})})})},t.prototype.ensureSequenceNumbers=function(t){var e=t.store(Wp.store),n=t.store(qp.store);return vp(t).next(function(t){var r=[];return n.iterate(function(n,i){var o=new Bh(n),s=function(t){return[0,Zf(t)]}(o);r.push(e.get(s).next(function(n){return n?cp.resolve():function(n){return e.put(new Wp(0,Zf(n),t))}(o)}))}).next(function(){return cp.waitFor(r)})})},t}();var Op=function(){return function(t,e){this.seconds=t,this.nanoseconds=e}}(),Pp=function(){function t(t,e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n}return t.store="owner",t.key="owner",t}();var Lp=function(){function t(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}return t.store="mutationQueues",t.keyPath="userId",t}(),Mp=function(){function t(t,e,n,r){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.mutations=r}return t.store="mutations",t.keyPath="batchId",t.userMutationsIndex="userMutationsIndex",t.userMutationsKeyPath=["userId","batchId"],t}();var xp=function(){function t(){}return t.prefixForUser=function(t){return[t]},t.prefixForPath=function(t,e){return[t,Zf(e)]},t.key=function(t,e,n){return[t,Zf(e),n]},t.store="documentMutations",t.PLACEHOLDER=new t,t}();var Fp=function(){return function(t,e){this.path=t,this.readTime=e}}(),Up=function(){return function(t,e){this.path=t,this.version=e}}(),qp=function(){function t(t,e,n,r){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r}return t.store="remoteDocuments",t}(),Bp=function(){function t(t){this.byteSize=t}return t.store="remoteDocumentGlobal",t.key="remoteDocumentGlobalKey",t}();var Vp=function(){function t(t,e,n,r,i,o){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.query=o}return t.store="targets",t.keyPath="targetId",t.queryTargetsIndexName="queryTargetsIndex",t.queryTargetsKeyPath=["canonicalId","targetId"],t}(),Wp=function(){function t(t,e,n){this.targetId=t,this.path=e,this.sequenceNumber=n,Jc(0===t==(void 0!==n),"A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number")}return t.store="targetDocuments",t.keyPath=["targetId","path"],t.documentTargetsIndex="documentTargetsIndex",t.documentTargetsKeyPath=["path","targetId"],t}(),jp=function(){function t(t,e,n,r){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n,this.targetCount=r}return t.key="targetGlobalKey",t.store="targetGlobal",t}();function Kp(t){t.createObjectStore(Wp.store,{keyPath:Wp.keyPath}).createIndex(Wp.documentTargetsIndex,Wp.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(Vp.store,{keyPath:Vp.keyPath}).createIndex(Vp.queryTargetsIndexName,Vp.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(jp.store)}var Qp=function(){function t(t){this.changes=t}return t.store="remoteDocumentChanges",t.keyPath="id",t}();var Hp=function(){function t(t,e,n,r,i){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r,this.lastProcessedDocumentChangeId=i}return t.store="clientMetadata",t.keyPath="clientId",t}();var Gp=[Lp.store,Mp.store,xp.store,qp.store,Vp.store,Pp.store,jp.store,Wp.store].concat([Hp.store,Qp.store]).concat([Bp.store]),zp=function(){function t(t,e,n){this.userId=t,this.serializer=e,this.referenceDelegate=n,this.documentKeysByBatchId={}}return t.forUser=function(e,n,r){return Jc(""!==e.uid,"UserID must not be an empty string."),new t(e.isAuthenticated()?e.uid:"",n,r)},t.prototype.checkEmpty=function(t){var e=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return $p(t).iterate({index:Mp.userMutationsIndex,range:n},function(t,n,r){e=!1,r.done()}).next(function(){return e})},t.prototype.acknowledgeBatch=function(t,e,n){return this.getMutationQueueMetadata(t).next(function(r){var i=e.batchId;return Jc(i>r.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),r.lastAcknowledgedBatchId=i,r.lastStreamToken=Jp(n),td(t).put(r)})},t.prototype.getLastStreamToken=function(t){return this.getMutationQueueMetadata(t).next(function(t){return t.lastStreamToken})},t.prototype.setLastStreamToken=function(t,e){return this.getMutationQueueMetadata(t).next(function(n){return n.lastStreamToken=Jp(e),td(t).put(n)})},t.prototype.addMutationBatch=function(t,e,n){var r=this,i=Zp(t),o=$p(t);return o.add({}).next(function(t){Jc("number"==typeof t,"Auto-generated key is not a number");var s=new op(t,e,n),a=r.serializer.toDbMutationBatch(r.userId,s);r.documentKeysByBatchId[t]=s.keys();for(var u=[],c=0,h=n;c<h.length;c++){var l=h[c],f=xp.key(r.userId,l.key.path,t);u.push(o.put(a)),u.push(i.put(f,xp.PLACEHOLDER))}return cp.waitFor(u).next(function(){return s})})},t.prototype.lookupMutationBatch=function(t,e){var n=this;return $p(t).get(e).next(function(t){return t?(Jc(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),n.serializer.fromDbMutationBatch(t)):null})},t.prototype.lookupMutationKeys=function(t,e){var n=this;return this.documentKeysByBatchId[e]?cp.resolve(this.documentKeysByBatchId[e]):this.lookupMutationBatch(t,e).next(function(t){if(t){var r=t.keys();return n.documentKeysByBatchId[e]=r,r}return null})},t.prototype.getNextMutationBatchAfterBatchId=function(t,e){var n=this;return this.getMutationQueueMetadata(t).next(function(r){var i=Math.max(e,r.lastAcknowledgedBatchId)+1,o=IDBKeyRange.lowerBound([n.userId,i]),s=null;return $p(t).iterate({index:Mp.userMutationsIndex,range:o},function(t,e,r){e.userId===n.userId&&(Jc(e.batchId>=i,"Should have found mutation after "+i),s=n.serializer.fromDbMutationBatch(e)),r.done()}).next(function(){return s})})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound([this.userId,ip],[this.userId,Number.POSITIVE_INFINITY]);return $p(t).loadAll(Mp.userMutationsIndex,n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=xp.prefixForPath(this.userId,e.path),i=IDBKeyRange.lowerBound(r),o=[];return Zp(t).iterate({range:i},function(r,i,s){var a=r[0],u=r[1],c=r[2],h=np(u);if(a===n.userId&&e.path.isEqual(h))return $p(t).get(c).next(function(t){if(!t)throw Xc("Dangling document-mutation reference found: "+r+" which points to "+c);Jc(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+c),o.push(n.serializer.fromDbMutationBatch(t))});s.done()}).next(function(){return o})},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new Ml(Ch),i=[];return e.forEach(function(e){var o=xp.prefixForPath(n.userId,e.path),s=IDBKeyRange.lowerBound(o),a=Zp(t).iterate({range:s},function(t,i,o){var s=t[0],a=t[1],u=t[2],c=np(a);s===n.userId&&e.path.isEqual(c)?r=r.add(u):o.done()});i.push(a)}),cp.waitFor(i).next(function(){return n.lookupMutationBatches(t,r)})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;Jc(!e.isDocumentQuery(),"Document queries shouldn't go down this path");var r=e.path,i=r.length+1,o=xp.prefixForPath(this.userId,r),s=IDBKeyRange.lowerBound(o),a=new Ml(Ch);return Zp(t).iterate({range:s},function(t,e,o){var s=t[0],u=t[1],c=t[2],h=np(u);s===n.userId&&r.isPrefixOf(h)?h.length===i&&(a=a.add(c)):o.done()}).next(function(){return n.lookupMutationBatches(t,a)})},t.prototype.lookupMutationBatches=function(t,e){var n=this,r=[],i=[];return e.forEach(function(e){i.push($p(t).get(e).next(function(t){if(null===t)throw Xc("Dangling document-mutation reference found, which points to "+e);Jc(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),r.push(n.serializer.fromDbMutationBatch(t))}))}),cp.waitFor(i).next(function(){return r})},t.prototype.removeMutationBatch=function(t,e){var n=this;return Xp(t.simpleDbTransaction,this.userId,e).next(function(r){return n.removeCachedMutationKeys(e.batchId),cp.forEach(r,function(e){return n.referenceDelegate.removeMutationReference(t,e)})})},t.prototype.removeCachedMutationKeys=function(t){delete this.documentKeysByBatchId[t]},t.prototype.performConsistencyCheck=function(t){var e=this;return this.checkEmpty(t).next(function(n){if(!n)return cp.resolve();var r=IDBKeyRange.lowerBound(xp.prefixForUser(e.userId)),i=[];return Zp(t).iterate({range:r},function(t,n,r){if(t[0]===e.userId){var o=np(t[1]);i.push(o)}else r.done()}).next(function(){Jc(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map(function(t){return t.canonicalString()}))})})},t.prototype.containsKey=function(t,e){return Yp(t,this.userId,e)},t.prototype.getMutationQueueMetadata=function(t){var e=this;return td(t).get(this.userId).next(function(t){return t||new Lp(e.userId,ip,"")})},t}();function Yp(t,e,n){var r=xp.prefixForPath(e,n.path),i=r[1],o=IDBKeyRange.lowerBound(r),s=!1;return Zp(t).iterate({range:o,keysOnly:!0},function(t,n,r){var o=t[0],a=t[1];t[2];o===e&&a===i&&(s=!0),r.done()}).next(function(){return s})}function Xp(t,e,n){var r=t.store(Mp.store),i=t.store(xp.store),o=[],s=IDBKeyRange.only(n.batchId),a=0,u=r.iterate({range:s},function(t,e,n){return a++,n.delete()});o.push(u.next(function(){Jc(1===a,"Dangling document-mutation reference found: Missing batch "+n.batchId)}));for(var c=[],h=0,l=n.mutations;h<l.length;h++){var f=l[h],p=xp.key(e,f.key.path,n.batchId);o.push(i.delete(p)),c.push(f.key)}return cp.waitFor(o).next(function(){return c})}function Jp(t){return t instanceof Uint8Array?(Jc("YES"===process.env.USE_MOCK_PERSISTENCE,"Persisting non-string stream tokens is only supported with mock persistence."),t.toString()):t}function $p(t){return pd.getStore(t,Mp.store)}function Zp(t){return pd.getStore(t,xp.store)}function td(t){return pd.getStore(t,Lp.store)}var ed=function(){function t(t){this.remoteSerializer=t}return t.prototype.fromDbRemoteDocument=function(t){if(t.document)return this.remoteSerializer.fromDocument(t.document,!!t.hasCommittedMutations);if(t.noDocument){var e=jh.fromSegments(t.noDocument.path),n=this.fromDbTimestamp(t.noDocument.readTime);return new Hh(e,n,{hasCommittedMutations:!!t.hasCommittedMutations})}if(t.unknownDocument){e=jh.fromSegments(t.unknownDocument.path),n=this.fromDbTimestamp(t.unknownDocument.version);return new Gh(e,n)}return Xc("Unexpected DbRemoteDocument")},t.prototype.toDbRemoteDocument=function(t){if(t instanceof Qh){var e=this.remoteSerializer.toDocument(t),n=t.hasCommittedMutations;return new qp(null,null,e,n)}if(t instanceof Hh){var r=t.key.path.toArray(),i=this.toDbTimestamp(t.version);n=t.hasCommittedMutations;return new qp(null,new Fp(r,i),null,n)}if(t instanceof Gh){r=t.key.path.toArray(),i=this.toDbTimestamp(t.version);return new qp(new Up(r,i),null,null,!0)}return Xc("Unexpected MaybeDocumment")},t.prototype.toDbTimestamp=function(t){var e=t.toTimestamp();return new Op(e.seconds,e.nanoseconds)},t.prototype.fromDbTimestamp=function(t){var e=new Mh(t.seconds,t.nanoseconds);return Ol.fromTimestamp(e)},t.prototype.toDbMutationBatch=function(t,e){var n=this,r=e.mutations.map(function(t){return n.remoteSerializer.toMutation(t)});return new Mp(t,e.batchId,e.localWriteTime.toMillis(),r)},t.prototype.fromDbMutationBatch=function(t){var e=this,n=t.mutations.map(function(t){return e.remoteSerializer.fromMutation(t)}),r=Mh.fromMillis(t.localWriteTimeMs);return new op(t.batchId,r,n)},t.prototype.toDbResourcePaths=function(t){var e=[];return t.forEach(function(t){e.push(Zf(t.path))}),e},t.prototype.fromDbResourcePaths=function(t){for(var e=af(),n=0,r=t;n<r.length;n++){var i=r[n];e=e.add(new jh(np(i)))}return e},t.prototype.fromDbTarget=function(t){var e,n=this.fromDbTimestamp(t.readTime);return e=void 0!==t.query.documents?this.remoteSerializer.fromDocumentsTarget(t.query):this.remoteSerializer.fromQueryTarget(t.query),new Ll(e,t.targetId,_l.Listen,t.lastListenSequenceNumber,n,t.resumeToken)},t.prototype.toDbTarget=function(t){Jc(_l.Listen===t.purpose,"Only queries with purpose "+_l.Listen+" may be stored, got "+t.purpose);var e,n,r=this.toDbTimestamp(t.snapshotVersion);return e=t.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(t.query):this.remoteSerializer.toQueryTarget(t.query),t.resumeToken instanceof Uint8Array?(Jc("YES"===process.env.USE_MOCK_PERSISTENCE,"Persisting non-string stream tokens is only supported with mock persistence ."),n=t.resumeToken.toString()):n=t.resumeToken,new Vp(t.targetId,t.query.canonicalId(),r,n,t.sequenceNumber,e)},t}();function nd(t,e){var n=t[0],r=t[1],i=e[0],o=e[1],s=Ch(n,i);return 0===s?Ch(r,o):s}var rd=function(){function t(t){this.maxElements=t,this.buffer=new Ml(nd),this.previousIndex=0}return t.prototype.nextIndex=function(){return++this.previousIndex},t.prototype.addElement=function(t){var e=[t,this.nextIndex()];if(this.buffer.size<this.maxElements)this.buffer=this.buffer.add(e);else{var n=this.buffer.last();nd(e,n)<0&&(this.buffer=this.buffer.delete(n).add(e))}},Object.defineProperty(t.prototype,"maxValue",{get:function(){return this.buffer.last()[0]},enumerable:!0,configurable:!0}),t}(),id={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0},od=function(){function t(t,e,n){this.cacheSizeCollectionThreshold=t,this.percentileToCollect=e,this.maximumSequenceNumbersToCollect=n}return t.withCacheSize=function(e){return new t(e,t.DEFAULT_COLLECTION_PERCENTILE,t.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)},t.COLLECTION_DISABLED=-1,t.MINIMUM_CACHE_SIZE_BYTES=1048576,t.DEFAULT_CACHE_SIZE_BYTES=41943040,t.DEFAULT_COLLECTION_PERCENTILE=10,t.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,t.DEFAULT=new t(t.DEFAULT_CACHE_SIZE_BYTES,t.DEFAULT_COLLECTION_PERCENTILE,t.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),t.DISABLED=new t(t.COLLECTION_DISABLED,0,0),t}(),sd=function(){function t(t,e,n){this.garbageCollector=t,this.asyncQueue=e,this.localStore=n,this.gcTask=null}return t.prototype.start=function(){Jc(null===this.gcTask,"Cannot start an already started LruScheduler"),this.garbageCollector.params.cacheSizeCollectionThreshold!==Yy&&this.scheduleGC()},t.prototype.stop=function(){this.gcTask&&(this.gcTask.cancel(),this.gcTask=null)},t.prototype.scheduleGC=function(){var t=this;Jc(null===this.gcTask,"Cannot schedule GC while a task is pending");var e=this.hasRun?3e5:6e4;Gc("LruGarbageCollector","Garbage collection scheduled in "+e+"ms"),this.gcTask=this.asyncQueue.enqueueAfterDelay(Kf.LruGarbageCollection,e,function(){return t.gcTask=null,t.hasRun=!0,t.localStore.collectGarbage(t.garbageCollector).then(function(){return t.scheduleGC()})})},t}(),ad=function(){function t(t,e){this.delegate=t,this.params=e}return t.prototype.calculateTargetCount=function(t,e){return this.delegate.getSequenceNumberCount(t).next(function(t){return Math.floor(e/100*t)})},t.prototype.nthSequenceNumber=function(t,e){var n=this;if(0===e)return cp.resolve(Qf.INVALID);var r=new rd(e);return this.delegate.forEachTarget(t,function(t){return r.addElement(t.sequenceNumber)}).next(function(){return n.delegate.forEachOrphanedDocumentSequenceNumber(t,function(t){return r.addElement(t)})}).next(function(){return r.maxValue})},t.prototype.removeTargets=function(t,e,n){return this.delegate.removeTargets(t,e,n)},t.prototype.removeOrphanedDocuments=function(t,e){return this.delegate.removeOrphanedDocuments(t,e)},t.prototype.collect=function(t,e){var n=this;return this.params.cacheSizeCollectionThreshold===od.COLLECTION_DISABLED?(Gc("LruGarbageCollector","Garbage collection skipped; disabled"),cp.resolve(id)):this.getCacheSize(t).next(function(r){return r<n.params.cacheSizeCollectionThreshold?(Gc("LruGarbageCollector","Garbage collection skipped; Cache size "+r+" is lower than threshold "+n.params.cacheSizeCollectionThreshold),id):n.runGarbageCollection(t,e)})},t.prototype.getCacheSize=function(t){return this.delegate.getCacheSize(t)},t.prototype.runGarbageCollection=function(t,e){var n,r,i,o,s,a,u,c,h=this;return o=Date.now(),this.calculateTargetCount(t,this.params.percentileToCollect).next(function(e){return e>h.params.maximumSequenceNumbersToCollect?(Gc("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+h.params.maximumSequenceNumbersToCollect+" from "+e),r=h.params.maximumSequenceNumbersToCollect):r=e,s=Date.now(),h.nthSequenceNumber(t,r)}).next(function(r){return n=r,a=Date.now(),h.removeTargets(t,n,e)}).next(function(e){return i=e,u=Date.now(),h.removeOrphanedDocuments(t,n)}).next(function(t){(c=Date.now(),Qc()<=Mc.DEBUG)&&Gc("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(s-o)+"ms\n\tDetermined least recently used "+r+" in "+(a-s)+"ms\n\tRemoved "+i+" targets in "+(u-a)+"ms\n\tRemoved "+t+" documents in "+(c-u)+"ms\nTotal Duration: "+(c-o)+"ms");return cp.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:t})})},t}(),ud="IndexedDbPersistence",cd="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",hd="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `experimentalTabSynchronization:true` in all tabs.",ld="This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.",fd=function(t){function e(e,n){var r=t.call(this)||this;return r.simpleDbTransaction=e,r.currentSequenceNumber=n,r}return Xe(e,t),e}(function(){return function(){}}()),pd=function(){function t(e,n,r,i,o,s,a){if(this.persistenceKey=e,this.clientId=n,this.queue=i,this.multiClientParams=a,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.inForeground=!1,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(t){return Promise.resolve()},!t.isAvailable())throw new eh(th.UNIMPLEMENTED,ld);if(this.referenceDelegate=new gd(this,s),this.dbName=e+t.MAIN_DATABASE,this.serializer=new ed(o),this.document=r.document,this.allowTabSynchronization=void 0!==a,this.queryCache=new yp(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new Tp(this.serializer,this.allowTabSynchronization),!r.window||!r.window.localStorage)throw new eh(th.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=r.window,this.webStorage=this.window.localStorage}return t.getStore=function(t,e){if(t instanceof fd)return hp.getStore(t.simpleDbTransaction,e);throw Xc("IndexedDbPersistence must use instances of IndexedDbTransaction")},t.createIndexedDbPersistence=function(e,n,r,i,o,s){return $e(this,void 0,void 0,function(){var a;return Ze(this,function(u){switch(u.label){case 0:return[4,(a=new t(e,n,r,i,o,s)).start()];case 1:return u.sent(),[2,a]}})})},t.createMultiClientIndexedDbPersistence=function(e,n,r,i,o,s,a){return $e(this,void 0,void 0,function(){var u;return Ze(this,function(c){switch(c.label){case 0:return[4,(u=new t(e,n,r,i,o,s,a)).start()];case 1:return c.sent(),[2,u]}})})},t.prototype.start=function(){var t=this;return Jc(!this.started,"IndexedDbPersistence double-started!"),Jc(null!==this.window,"Expected 'window' to be defined"),hp.openOrCreate(this.dbName,kp,new Rp(this.serializer)).then(function(e){t.simpleDb=e}).then(function(){return t.startRemoteDocumentCache()}).then(function(){return t.attachVisibilityHandler(),t.attachWindowUnloadHook(),t.updateClientMetadataAndTryBecomePrimary().then(function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()})}).then(function(){return t.simpleDb.runTransaction("readonly",[jp.store],function(e){return vp(e).next(function(e){var n=t.multiClientParams?t.multiClientParams.sequenceNumberSyncer:void 0;t.listenSequence=new Qf(e,n)})})}).then(function(){t._started=!0}).catch(function(e){return t.simpleDb&&t.simpleDb.close(),Promise.reject(e)})},t.prototype.startRemoteDocumentCache=function(){var t=this;return this.simpleDb.runTransaction("readonly",Gp,function(e){return t.remoteDocumentCache.start(e)})},t.prototype.setPrimaryStateListener=function(t){var e=this;return this.primaryStateListener=function(n){return $e(e,void 0,void 0,function(){return Ze(this,function(e){return this.started?[2,t(n)]:[2]})})},t(this.isPrimary)},t.prototype.setNetworkEnabled=function(t){var e=this;this.networkEnabled!==t&&(this.networkEnabled=t,this.queue.enqueueAndForget(function(){return $e(e,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return this.started?[4,this.updateClientMetadataAndTryBecomePrimary()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})}))},t.prototype.updateClientMetadataAndTryBecomePrimary=function(){var t=this;return this.simpleDb.runTransaction("readwrite",Gp,function(e){return md(e).put(new Hp(t.clientId,Date.now(),t.networkEnabled,t.inForeground,t.remoteDocumentCache.lastProcessedDocumentChangeId)).next(function(){if(t.isPrimary)return t.verifyPrimaryLease(e).next(function(e){e||(t.isPrimary=!1,t.queue.enqueueAndForget(function(){return t.primaryStateListener(!1)}))})}).next(function(){return t.canActAsPrimary(e)}).next(function(n){var r=t.isPrimary;return t.isPrimary=n,r!==t.isPrimary&&t.queue.enqueueAndForget(function(){return t.primaryStateListener(t.isPrimary)}),r&&!t.isPrimary?t.releasePrimaryLeaseIfHeld(e):t.isPrimary?t.acquireOrExtendPrimaryLease(e):void 0})})},t.prototype.verifyPrimaryLease=function(t){var e=this;return yd(t).get(Pp.key).next(function(t){return cp.resolve(e.isLocalClient(t))})},t.prototype.removeClientMetadata=function(t){return md(t).delete(this.clientId)},t.prototype.maybeGarbageCollectMultiClientState=function(){return $e(this,void 0,void 0,function(){var e,n,r=this;return Ze(this,function(i){switch(i.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,18e5)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),n=[],[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(i){var o=t.getStore(i,Hp.store);return o.loadAll().next(function(t){e=r.filterActiveClients(t,18e5),n=t.filter(function(t){return-1===e.indexOf(t)})}).next(function(){return cp.forEach(n,function(t){return o.delete(t.clientId)})}).next(function(){if((e=e.filter(function(t){return t.clientId!==r.clientId})).length>0){var t=e.map(function(t){return t.lastProcessedDocumentChangeId||0}),n=Math.min.apply(Math,t);return r.remoteDocumentCache.removeDocumentChangesThroughChangeId(i,n)}})})]);case 1:i.sent(),n.forEach(function(t){r.window.localStorage.removeItem(r.zombiedClientLocalStorageKey(t.clientId))}),i.label=2;case 2:return[2]}})})},t.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var t=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(Kf.ClientMetadataRefresh,4e3,function(){return t.updateClientMetadataAndTryBecomePrimary().then(function(){return t.maybeGarbageCollectMultiClientState()}).then(function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()})})},t.prototype.isLocalClient=function(t){return!!t&&t.ownerId===this.clientId},t.prototype.canActAsPrimary=function(t){var e=this;return yd(t).get(Pp.key).next(function(n){if(null!==n&&e.isWithinAge(n.leaseTimestampMs,5e3)&&!e.isClientZombied(n.ownerId)){if(e.isLocalClient(n)&&e.networkEnabled)return!0;if(!e.isLocalClient(n)){if(!n.allowTabSynchronization)throw new eh(th.FAILED_PRECONDITION,hd);return!1}}return!(!e.networkEnabled||!e.inForeground)||md(t).loadAll().next(function(t){return void 0===e.filterActiveClients(t,5e3).find(function(t){if(e.clientId!==t.clientId){var n=!e.networkEnabled&&t.networkEnabled,r=!e.inForeground&&t.inForeground,i=e.networkEnabled===t.networkEnabled;if(n||r&&i)return!0}return!1})})}).next(function(t){return e.isPrimary!==t&&Gc(ud,"Client "+(t?"is":"is not")+" eligible for a primary lease."),t})},t.prototype.shutdown=function(t){return $e(this,void 0,void 0,function(){var e=this;return Ze(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",[Pp.store,Hp.store],function(t){return e.releasePrimaryLeaseIfHeld(t).next(function(){return e.removeClientMetadata(t)})})];case 1:return n.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),t?[4,hp.delete(this.dbName)]:[3,3];case 2:n.sent(),n.label=3;case 3:return[2]}})})},t.prototype.filterActiveClients=function(t,e){var n=this;return t.filter(function(t){return n.isWithinAge(t.updateTimeMs,e)&&!n.isClientZombied(t.clientId)})},t.prototype.getActiveClients=function(){var t=this;return this.simpleDb.runTransaction("readonly",[Hp.store],function(e){return md(e).loadAll().next(function(e){return t.filterActiveClients(e,18e5).map(function(t){return t.clientId})})})},Object.defineProperty(t.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),t.prototype.getMutationQueue=function(t){return Jc(this.started,"Cannot initialize MutationQueue before persistence is started."),zp.forUser(t,this.serializer,this.referenceDelegate)},t.prototype.getQueryCache=function(){return Jc(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},t.prototype.getRemoteDocumentCache=function(){return Jc(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},t.prototype.runTransaction=function(t,e,n){var r=this;return Gc(ud,"Starting transaction:",t),this.simpleDb.runTransaction("readonly"===e?"readonly":"readwrite",Gp,function(i){return"readwrite-primary"===e?r.verifyPrimaryLease(i).next(function(e){if(!e)throw zc("Failed to obtain primary lease for action '"+t+"'."),r.isPrimary=!1,r.queue.enqueueAndForget(function(){return r.primaryStateListener(!1)}),new eh(th.FAILED_PRECONDITION,cd);return n(new fd(i,r.listenSequence.next()))}).next(function(t){return r.acquireOrExtendPrimaryLease(i).next(function(){return t})}):r.verifyAllowTabSynchronization(i).next(function(){return n(new fd(i,r.listenSequence.next()))})})},t.prototype.verifyAllowTabSynchronization=function(t){var e=this;return yd(t).get(Pp.key).next(function(t){if(null!==t&&e.isWithinAge(t.leaseTimestampMs,5e3)&&!e.isClientZombied(t.ownerId)&&!e.isLocalClient(t)&&!t.allowTabSynchronization)throw new eh(th.FAILED_PRECONDITION,hd)})},t.prototype.acquireOrExtendPrimaryLease=function(t){var e=new Pp(this.clientId,this.allowTabSynchronization,Date.now());return yd(t).put(Pp.key,e)},t.isAvailable=function(){return hp.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.releasePrimaryLeaseIfHeld=function(t){var e=this,n=yd(t);return n.get(Pp.key).next(function(t){return e.isLocalClient(t)?(Gc(ud,"Releasing primary lease."),n.delete(Pp.key)):cp.resolve()})},t.prototype.isWithinAge=function(t,e){var n=Date.now();return!(t<n-e)&&(!(t>n)||(zc("Detected an update time that is in the future: "+t+" > "+n),!1))},t.prototype.attachVisibilityHandler=function(){var t=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.documentVisibilityHandler=function(){t.queue.enqueueAndForget(function(){return t.inForeground="visible"===t.document.visibilityState,t.updateClientMetadataAndTryBecomePrimary()})},this.document.addEventListener("visibilitychange",this.documentVisibilityHandler),this.inForeground="visible"===this.document.visibilityState)},t.prototype.detachVisibilityHandler=function(){this.documentVisibilityHandler&&(Jc(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.documentVisibilityHandler),this.documentVisibilityHandler=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;"function"==typeof this.window.addEventListener&&(this.windowUnloadHandler=function(){t.markClientZombied(),t.queue.enqueueAndForget(function(){return t.shutdown()})},this.window.addEventListener("unload",this.windowUnloadHandler))},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(Jc("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.isClientZombied=function(t){try{var e=null!==this.webStorage.getItem(this.zombiedClientLocalStorageKey(t));return Gc(ud,"Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return zc(ud,"Failed to get zombied client id.",t),!1}},t.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(t){zc("Failed to set zombie client id.",t)}},t.prototype.removeClientZombiedEntry=function(){try{this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId))}catch(t){}},t.prototype.zombiedClientLocalStorageKey=function(t){return"firestore_zombie_"+this.persistenceKey+"_"+t},t.MAIN_DATABASE="main",t}();function dd(t){return t.code===th.FAILED_PRECONDITION&&t.message===cd}function yd(t){return t.store(Pp.store)}function md(t){return t.store(Hp.store)}var gd=function(){function t(t,e){this.db=t,this.garbageCollector=new ad(this,e)}return t.prototype.getSequenceNumberCount=function(t){var e=this.orphanedDocmentCount(t);return this.db.getQueryCache().getQueryCount(t).next(function(t){return e.next(function(e){return t+e})})},t.prototype.orphanedDocmentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,function(t){e++}).next(function(){return e})},t.prototype.forEachTarget=function(t,e){return this.db.getQueryCache().forEachTarget(t,e)},t.prototype.forEachOrphanedDocumentSequenceNumber=function(t,e){return this.forEachOrphanedDocument(t,function(t,n){return e(n)})},t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.addReference=function(t,e){return vd(t,e)},t.prototype.removeReference=function(t,e){return vd(t,e)},t.prototype.removeTargets=function(t,e,n){return this.db.getQueryCache().removeTargets(t,e,n)},t.prototype.removeMutationReference=function(t,e){return vd(t,e)},t.prototype.isPinned=function(t,e){return this.inMemoryPins.containsKey(e)?cp.resolve(!0):function(t,e){var n=!1;return td(t).iterateSerial(function(r){return Yp(t,r,e).next(function(t){return t&&(n=!0),cp.resolve(!t)})}).next(function(){return n})}(t,e)},t.prototype.removeOrphanedDocuments=function(t,e){var n=this,r=0,i=0,o=[];return this.forEachOrphanedDocument(t,function(s,a){if(a<=e){var u=n.isPinned(t,s).next(function(e){if(!e)return r++,n.removeOrphanedDocument(t,s).next(function(t){i+=t})});o.push(u)}}).next(function(){return cp.waitFor(o)}).next(function(){return n.db.getRemoteDocumentCache().updateSize(t,-i)}).next(function(){return r})},t.prototype.removeOrphanedDocument=function(t,e){var n,r=0,i=this.db.getRemoteDocumentCache();return cp.waitFor([bp(t).delete((n=e,[0,Zf(n.path)])),i.removeEntry(t,e).next(function(t){r+=t})]).next(function(){return r})},t.prototype.removeTarget=function(t,e){var n=e.copy({sequenceNumber:t.currentSequenceNumber});return this.db.getQueryCache().updateQueryData(t,n)},t.prototype.updateLimboDocument=function(t,e){return vd(t,e)},t.prototype.forEachOrphanedDocument=function(t,e){var n,r=bp(t),i=Qf.INVALID;return r.iterate({index:Wp.documentTargetsIndex},function(t,r){var o=t[0],s=(t[1],r.path),a=r.sequenceNumber;0===o?(i!==Qf.INVALID&&e(new jh(np(n)),i),i=a,n=s):i=Qf.INVALID}).next(function(){i!==Qf.INVALID&&e(new jh(np(n)),i)})},t.prototype.getCacheSize=function(t){return this.db.getRemoteDocumentCache().getSize(t)},t}();function vd(t,e){return bp(t).put(function(t,e){return new Wp(0,Zf(t.path),e)}(e,t.currentSequenceNumber))}var bd=function(){function t(t,e){this.remoteDocumentCache=t,this.mutationQueue=e}return t.prototype.getDocument=function(t,e){var n=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(t,e).next(function(r){return n.getDocumentInternal(t,e,r)})},t.prototype.getDocumentInternal=function(t,e,n){return this.remoteDocumentCache.getEntry(t,e).next(function(t){for(var r=0,i=n;r<i.length;r++){t=i[r].applyToLocalView(e,t)}return t})},t.prototype.getDocuments=function(t,e){var n=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t,e).next(function(r){var i=[],o=tf();return e.forEach(function(e){i.push(n.getDocumentInternal(t,e,r).next(function(t){t||(t=new Hh(e,Ol.forDeletedDoc())),o=o.insert(e,t)}))}),cp.waitFor(i).next(function(){return o})})},t.prototype.getDocumentsMatchingQuery=function(t,e){return jh.isDocumentKey(e.path)?this.getDocumentsMatchingDocumentQuery(t,e.path):this.getDocumentsMatchingCollectionQuery(t,e)},t.prototype.getDocumentsMatchingDocumentQuery=function(t,e){return this.getDocument(t,new jh(e)).next(function(t){var e=nf();return t instanceof Qh&&(e=e.insert(t.key,t)),e})},t.prototype.getDocumentsMatchingCollectionQuery=function(t,e){var n,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(t,e).next(function(i){return n=i,r.mutationQueue.getAllMutationBatchesAffectingQuery(t,e)}).next(function(t){for(var r=0,i=t;r<i.length;r++)for(var o=i[r],s=0,a=o.mutations;s<a.length;s++){var u=a[s],c=u.key;if(e.path.isImmediateParentOf(c.path)){var h=n.get(c),l=u.applyToLocalView(h,h,o.localWriteTime);n=l instanceof Qh?n.insert(c,l):n.remove(c)}}}).next(function(){return n.forEach(function(t,r){e.matches(r)||(n=n.remove(t))}),n})},t}(),_d=function(){function t(){this.refsByKey=new Ml(wd.compareByKey),this.refsByTarget=new Ml(wd.compareByTargetId)}return t.prototype.isEmpty=function(){return this.refsByKey.isEmpty()},t.prototype.addReference=function(t,e){var n=new wd(t,e);this.refsByKey=this.refsByKey.add(n),this.refsByTarget=this.refsByTarget.add(n)},t.prototype.addReferences=function(t,e){var n=this;t.forEach(function(t){return n.addReference(t,e)})},t.prototype.removeReference=function(t,e){this.removeRef(new wd(t,e))},t.prototype.removeReferences=function(t,e){var n=this;t.forEach(function(t){return n.removeReference(t,e)})},t.prototype.removeReferencesForId=function(t){var e=this,n=jh.EMPTY,r=new wd(n,t),i=new wd(n,t+1),o=[];return this.refsByTarget.forEachInRange([r,i],function(t){e.removeRef(t),o.push(t.key)}),o},t.prototype.removeAllReferences=function(){var t=this;this.refsByKey.forEach(function(e){return t.removeRef(e)})},t.prototype.removeRef=function(t){this.refsByKey=this.refsByKey.delete(t),this.refsByTarget=this.refsByTarget.delete(t)},t.prototype.referencesForId=function(t){var e=jh.EMPTY,n=new wd(e,t),r=new wd(e,t+1),i=af();return this.refsByTarget.forEachInRange([n,r],function(t){i=i.add(t.key)}),i},t.prototype.containsKey=function(t){var e=new wd(t,0),n=this.refsByKey.firstAfterOrEqual(e);return null!==n&&t.isEqual(n.key)},t}(),wd=function(){function t(t,e){this.key=t,this.targetOrBatchId=e}return t.compareByKey=function(t,e){return jh.comparator(t.key,e.key)||Ch(t.targetOrBatchId,e.targetOrBatchId)},t.compareByTargetId=function(t,e){return Ch(t.targetOrBatchId,e.targetOrBatchId)||jh.comparator(t.key,e.key)},t}(),Ed=function(){function t(t,e){this.persistence=t,this.localViewReferences=new _d,this.queryDataByTarget={},Jc(t.started,"LocalStore was passed an unstarted persistence implementation"),this.persistence.referenceDelegate.setInMemoryPins(this.localViewReferences),this.mutationQueue=t.getMutationQueue(e),this.remoteDocuments=t.getRemoteDocumentCache(),this.queryCache=t.getQueryCache(),this.localDocuments=new bd(this.remoteDocuments,this.mutationQueue)}return t.prototype.handleUserChange=function(t){var e=this;return this.persistence.runTransaction("Handle user change","readonly",function(n){var r;return e.mutationQueue.getAllMutationBatches(n).next(function(i){return r=i,e.mutationQueue=e.persistence.getMutationQueue(t),e.localDocuments=new bd(e.remoteDocuments,e.mutationQueue),e.mutationQueue.getAllMutationBatches(n)}).next(function(t){for(var i=[],o=[],s=af(),a=0,u=r;a<u.length;a++){var c=u[a];i.push(c.batchId);for(var h=0,l=c.mutations;h<l.length;h++){var f=l[h];s=s.add(f.key)}}for(var p=0,d=t;p<d.length;p++){c=d[p];o.push(c.batchId);for(var y=0,m=c.mutations;y<m.length;y++){f=m[y];s=s.add(f.key)}}return e.localDocuments.getDocuments(n,s).next(function(t){return{affectedDocuments:t,removedBatchIds:i,addedBatchIds:o}})})})},t.prototype.localWrite=function(t){var e=this;return this.persistence.runTransaction("Locally write mutations","readwrite",function(n){var r,i=Mh.now();return e.mutationQueue.addMutationBatch(n,i,t).next(function(t){var i=(r=t).keys();return e.localDocuments.getDocuments(n,i)}).next(function(t){return{batchId:r.batchId,changes:t}})})},t.prototype.lookupMutationDocuments=function(t){var e=this;return this.persistence.runTransaction("Lookup mutation documents","readonly",function(n){return e.mutationQueue.lookupMutationKeys(n,t).next(function(t){return t?e.localDocuments.getDocuments(n,t):cp.resolve(null)})})},t.prototype.acknowledgeBatch=function(t){var e=this;return this.persistence.runTransaction("Acknowledge batch","readwrite-primary",function(n){var r=t.batch.keys(),i=e.remoteDocuments.newChangeBuffer();return e.mutationQueue.acknowledgeBatch(n,t.batch,t.streamToken).next(function(){return e.applyWriteToRemoteDocuments(n,t,i)}).next(function(){return i.apply(n)}).next(function(){return e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,r)})})},t.prototype.rejectBatch=function(t){var e=this;return this.persistence.runTransaction("Reject batch","readwrite-primary",function(n){var r;return e.mutationQueue.lookupMutationBatch(n,t).next(function(t){return Jc(null!==t,"Attempt to reject nonexistent batch!"),r=t.keys(),e.mutationQueue.removeMutationBatch(n,t)}).next(function(){return e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,r)})})},t.prototype.getLastStreamToken=function(){var t=this;return this.persistence.runTransaction("Get last stream token","readonly",function(e){return t.mutationQueue.getLastStreamToken(e)})},t.prototype.setLastStreamToken=function(t){var e=this;return this.persistence.runTransaction("Set last stream token","readwrite-primary",function(n){return e.mutationQueue.setLastStreamToken(n,t)})},t.prototype.getLastRemoteSnapshotVersion=function(){var t=this;return this.persistence.runTransaction("Get last remote snapshot version","readonly",function(e){return t.queryCache.getLastRemoteSnapshotVersion(e)})},t.prototype.applyRemoteEvent=function(e){var n=this,r=this.remoteDocuments.newChangeBuffer();return this.persistence.runTransaction("Apply remote event","readwrite-primary",function(i){var o=[],s=af();oh(e.targetChanges,function(r,a){var u=n.queryDataByTarget[r];if(u){a.addedDocuments.forEach(function(t){s=s.add(t)}),a.modifiedDocuments.forEach(function(t){s=s.add(t)}),o.push(n.queryCache.removeMatchingKeys(i,a.removedDocuments,r).next(function(){return n.queryCache.addMatchingKeys(i,a.addedDocuments,r)}));var c=a.resumeToken;if(c.length>0){var h=u;u=u.copy({resumeToken:c,snapshotVersion:e.snapshotVersion}),n.queryDataByTarget[r]=u,t.shouldPersistQueryData(h,u,a)&&o.push(n.queryCache.updateQueryData(i,u))}}});var a=af();e.documentUpdates.forEach(function(t,u){a=a.add(t),o.push(r.getEntry(i,t).next(function(e){null==e||u.version.isEqual(Ol.MIN)||s.has(u.key)&&!e.hasPendingWrites||u.version.compareTo(e.version)>=0?r.addEntry(u):Gc("LocalStore","Ignoring outdated watch update for ",t,". Current version:",e.version," Watch version:",u.version)})),e.resolvedLimboDocuments.has(t)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(i,t))});var u=e.snapshotVersion;if(!u.isEqual(Ol.MIN)){var c=n.queryCache.getLastRemoteSnapshotVersion(i).next(function(t){return Jc(u.compareTo(t)>=0,"Watch stream reverted to previous snapshot?? "+u+" < "+t),n.queryCache.setTargetsMetadata(i,i.currentSequenceNumber,u)});o.push(c)}return cp.waitFor(o).next(function(){return r.apply(i)}).next(function(){return n.localDocuments.getDocuments(i,a)})})},t.shouldPersistQueryData=function(t,e,n){return 0!==e.resumeToken.length&&(0===t.resumeToken.length||(e.snapshotVersion.toMicroseconds()-t.snapshotVersion.toMicroseconds()>=this.RESUME_TOKEN_MAX_AGE_MICROS||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0))},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("notifyLocalViewChanges","readwrite",function(n){return cp.forEach(t,function(t){return e.localViewReferences.addReferences(t.addedKeys,t.targetId),e.localViewReferences.removeReferences(t.removedKeys,t.targetId),cp.forEach(t.removedKeys,function(t){return e.persistence.referenceDelegate.removeReference(n,t)})})})},t.prototype.nextMutationBatch=function(t){var e=this;return this.persistence.runTransaction("Get next mutation batch","readonly",function(n){return void 0===t&&(t=ip),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)})},t.prototype.readDocument=function(t){var e=this;return this.persistence.runTransaction("read document","readonly",function(n){return e.localDocuments.getDocument(n,t)})},t.prototype.allocateQuery=function(t){var e=this;return this.persistence.runTransaction("Allocate query","readwrite",function(n){var r;return e.queryCache.getQueryData(n,t).next(function(i){return i?(r=i,cp.resolve()):e.queryCache.allocateTargetId(n).next(function(i){return r=new Ll(t,i,_l.Listen,n.currentSequenceNumber),e.queryCache.addQueryData(n,r)})}).next(function(){return Jc(!e.queryDataByTarget[r.targetId],"Tried to allocate an already allocated query: "+t),e.queryDataByTarget[r.targetId]=r,r})})},t.prototype.releaseQuery=function(t,e){var n=this,r=e?"readwrite":"readwrite-primary";return this.persistence.runTransaction("Release query",r,function(r){return n.queryCache.getQueryData(r,t).next(function(i){Jc(null!=i,"Tried to release nonexistent query: "+t);var o=i.targetId,s=n.queryDataByTarget[o],a=n.localViewReferences.removeReferencesForId(o);return delete n.queryDataByTarget[o],e?cp.resolve():cp.forEach(a,function(t){return n.persistence.referenceDelegate.removeReference(r,t)}).next(function(){return n.persistence.referenceDelegate.removeTarget(r,s)})})})},t.prototype.executeQuery=function(t){var e=this;return this.persistence.runTransaction("Execute query","readonly",function(n){return e.localDocuments.getDocumentsMatchingQuery(n,t)})},t.prototype.remoteDocumentKeys=function(t){var e=this;return this.persistence.runTransaction("Remote document keys","readonly",function(n){return e.queryCache.getMatchingKeysForTargetId(n,t)})},t.prototype.getActiveClients=function(){return this.persistence.getActiveClients()},t.prototype.removeCachedMutationBatchMetadata=function(t){this.mutationQueue.removeCachedMutationKeys(t)},t.prototype.setNetworkEnabled=function(t){this.persistence.setNetworkEnabled(t)},t.prototype.applyWriteToRemoteDocuments=function(t,e,n){var r=this,i=e.batch,o=i.keys(),s=cp.resolve();return o.forEach(function(r){s=s.next(function(){return n.getEntry(t,r)}).next(function(t){var o=t,s=e.docVersions.get(r);Jc(null!==s,"ackVersions should contain every doc in the write."),(!o||o.version.compareTo(s)<0)&&((o=i.applyToRemoteDocument(r,o,e))?n.addEntry(o):Jc(!t,"Mutation batch "+i+" applied to document "+t+" resulted in null"))})}),s.next(function(){return r.mutationQueue.removeMutationBatch(t,i)})},t.prototype.collectGarbage=function(t){var e=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary",function(n){return t.collect(n,e.queryDataByTarget)})},t.prototype.getQueryForTarget=function(t){var e=this;return this.queryDataByTarget[t]?Promise.resolve(this.queryDataByTarget[t].query):this.persistence.runTransaction("Get query data","readonly",function(n){return e.queryCache.getQueryDataForTarget(n,t).next(function(t){return t?t.query:null})})},t.prototype.getNewDocumentChanges=function(){var t=this;return this.persistence.runTransaction("Get new document changes","readonly",function(e){return t.remoteDocuments.getNewDocumentChanges(e)})},t.RESUME_TOKEN_MAX_AGE_MICROS=3e8,t}(),Td=function(){function t(t){this.referenceDelegate=t,this.mutationQueue=[],this.nextBatchId=1,this.highestAcknowledgedBatchId=ip,this.lastStreamToken=Zc(),this.batchesByDocumentKey=new Ml(wd.compareByKey)}return t.prototype.checkEmpty=function(t){return cp.resolve(0===this.mutationQueue.length)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;Jc(r>this.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var i=this.indexOfExistingBatchId(r,"acknowledged");Jc(0===i,"Can only acknowledge the first batch in the mutation queue");var o=this.mutationQueue[i];return Jc(r===o.batchId,"Queue ordering failure: expected batch "+r+", got batch "+o.batchId),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,cp.resolve()},t.prototype.getLastStreamToken=function(t){return cp.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,cp.resolve()},t.prototype.addMutationBatch=function(t,e,n){Jc(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;(this.nextBatchId++,this.mutationQueue.length>0)&&Jc(this.mutationQueue[this.mutationQueue.length-1].batchId<r,"Mutation batchIDs must be monotonically increasing order");var i=new op(r,e,n);this.mutationQueue.push(i);for(var o=0,s=n;o<s.length;o++){var a=s[o];this.batchesByDocumentKey=this.batchesByDocumentKey.add(new wd(a.key,r))}return cp.resolve(i)},t.prototype.lookupMutationBatch=function(t,e){return cp.resolve(this.findMutationBatch(e))},t.prototype.lookupMutationKeys=function(t,e){var n=this.findMutationBatch(e);return Jc(null!=n,"Failed to find local mutation batch."),cp.resolve(n.keys())},t.prototype.getNextMutationBatchAfterBatchId=function(t,e){var n=Math.max(e,this.highestAcknowledgedBatchId)+1,r=this.indexOfBatchId(n),i=r<0?0:r;return cp.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)},t.prototype.getAllMutationBatches=function(t){return cp.resolve(this.mutationQueue.slice())},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new wd(e,0),i=new wd(e,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([r,i],function(t){Jc(e.isEqual(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);Jc(null!==r,"Batches in the index must exist in the main table"),o.push(r)}),cp.resolve(o)},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new Ml(Ch);return e.forEach(function(t){var e=new wd(t,0),i=new wd(t,Number.POSITIVE_INFINITY);n.batchesByDocumentKey.forEachInRange([e,i],function(e){Jc(t.isEqual(e.key),"For each key, should only iterate over a single key's batches"),r=r.add(e.targetOrBatchId)})}),cp.resolve(this.findMutationBatches(r))},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=e.path,r=n.length+1,i=n;jh.isDocumentKey(i)||(i=i.child(""));var o=new wd(new jh(i),0),s=new Ml(Ch);return this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(s=s.add(t.targetOrBatchId)),!0)},o),cp.resolve(this.findMutationBatches(s))},t.prototype.findMutationBatches=function(t){var e=this,n=[];return t.forEach(function(t){var r=e.findMutationBatch(t);null!==r&&n.push(r)}),n},t.prototype.removeMutationBatch=function(t,e){var n=this;Jc(0===this.indexOfExistingBatchId(e.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.mutationQueue.shift();var r=this.batchesByDocumentKey;return cp.forEach(e.mutations,function(i){var o=new wd(i.key,e.batchId);return r=r.delete(o),n.referenceDelegate.removeMutationReference(t,i.key)}).next(function(){n.batchesByDocumentKey=r})},t.prototype.removeCachedMutationKeys=function(t){},t.prototype.containsKey=function(t,e){var n=new wd(e,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return cp.resolve(e.isEqual(r&&r.key))},t.prototype.performConsistencyCheck=function(t){return 0===this.mutationQueue.length&&Jc(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),cp.resolve()},t.prototype.indexOfExistingBatchId=function(t,e){var n=this.indexOfBatchId(t);return Jc(n>=0&&n<this.mutationQueue.length,"Batches must exist to be "+e),n},t.prototype.indexOfBatchId=function(t){return 0===this.mutationQueue.length?0:t-this.mutationQueue[0].batchId},t.prototype.findMutationBatch=function(t){var e=this.indexOfBatchId(t);if(e<0||e>=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return Jc(n.batchId===t,"If found batch must match"),n},t}(),Sd=function(){function t(t){this.persistence=t,this.queries=new _p(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=Ol.MIN,this.highestTargetId=0,this.highestSequenceNumber=0,this.references=new _d,this.targetCount=0,this.targetIdGenerator=up.forQueryCache()}return t.prototype.getTargetCount=function(t){return cp.resolve(this.targetCount)},t.prototype.forEachTarget=function(t,e){return this.queries.forEach(function(t,n){return e(n)}),cp.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(t){return cp.resolve(this.lastRemoteSnapshotVersion)},t.prototype.getHighestSequenceNumber=function(t){return cp.resolve(this.highestSequenceNumber)},t.prototype.allocateTargetId=function(t){var e=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=e,cp.resolve(e)},t.prototype.setTargetsMetadata=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.highestSequenceNumber&&(this.highestSequenceNumber=e),cp.resolve()},t.prototype.saveQueryData=function(t){this.queries.set(t.query,t);var e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e),t.sequenceNumber>this.highestSequenceNumber&&(this.highestSequenceNumber=t.sequenceNumber)},t.prototype.addQueryData=function(t,e){return Jc(!this.queries.has(e.query),"Adding a query that already exists"),this.saveQueryData(e),this.targetCount+=1,cp.resolve()},t.prototype.updateQueryData=function(t,e){return Jc(this.queries.has(e.query),"Updating a non-existent query"),this.saveQueryData(e),cp.resolve()},t.prototype.removeQueryData=function(t,e){return Jc(this.targetCount>0,"Removing a target from an empty cache"),Jc(this.queries.has(e.query),"Removing a non-existent target from the cache"),this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),this.targetCount-=1,cp.resolve()},t.prototype.removeTargets=function(t,e,n){var r=this,i=0,o=[];return this.queries.forEach(function(s,a){a.sequenceNumber<=e&&!n[a.targetId]&&(r.queries.delete(s),o.push(r.removeMatchingKeysForTargetId(t,a.targetId)),i++)}),cp.waitFor(o).next(function(){return i})},t.prototype.getQueryCount=function(t){return cp.resolve(this.targetCount)},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return cp.resolve(n)},t.prototype.getQueryDataForTarget=function(t,e){return Xc("Not yet implemented.")},t.prototype.addMatchingKeys=function(t,e,n){this.references.addReferences(e,n);var r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(function(e){i.push(r.addReference(t,e))}),cp.waitFor(i)},t.prototype.removeMatchingKeys=function(t,e,n){this.references.removeReferences(e,n);var r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(function(e){i.push(r.removeReference(t,e))}),cp.waitFor(i)},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),cp.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return cp.resolve(n)},t.prototype.containsKey=function(t,e){return cp.resolve(this.references.containsKey(e))},t}();var Id,Cd=function(){function t(t){this.sizer=t,this.docs=new zh(jh.comparator),this.newDocumentChanges=af(),this.size=0}return t.prototype.addEntries=function(t,e,n){for(var r=0,i=e;r<i.length;r++){var o=i[r],s=o.maybeDocument.key;this.docs=this.docs.insert(s,o),this.newDocumentChanges=this.newDocumentChanges.add(s)}return this.size+=n,cp.resolve()},t.prototype.removeEntry=function(t,e){var n=this.docs.get(e);return n?(this.docs=this.docs.remove(e),this.size-=n.size,cp.resolve(n.size)):cp.resolve(0)},t.prototype.getEntry=function(t,e){var n=this.docs.get(e);return cp.resolve(n?n.maybeDocument:null)},t.prototype.getSizedEntry=function(t,e){return cp.resolve(this.docs.get(e))},t.prototype.getDocumentsMatchingQuery=function(t,e){for(var n=nf(),r=new jh(e.path.child("")),i=this.docs.getIteratorFrom(r);i.hasNext();){var o=i.getNext(),s=o.key,a=o.value.maybeDocument;if(!e.path.isPrefixOf(s.path))break;a instanceof Qh&&e.matches(a)&&(n=n.insert(a.key,a))}return cp.resolve(n)},t.prototype.forEachDocumentKey=function(t,e){return cp.forEach(this.docs,function(t){return e(t)})},t.prototype.getNewDocumentChanges=function(t){var e=this,n=tf();return this.newDocumentChanges.forEach(function(t){var r=e.docs.get(t),i=r?r.maybeDocument:new Hh(t,Ol.forDeletedDoc());n=n.insert(t,i)}),this.newDocumentChanges=af(),cp.resolve(n)},t.prototype.newChangeBuffer=function(){return new Nd(this.sizer,this)},t.prototype.getSize=function(t){return cp.resolve(this.size)},t}(),Nd=function(t){function e(e,n){var r=t.call(this)||this;return r.sizer=e,r.documentCache=n,r}return Xe(e,t),e.prototype.applyChanges=function(t){var e=this,n=0,r=[];return this.assertChanges().forEach(function(t,i){var o=e.documentSizes.get(t);Jc(void 0!==o,"Attempting to change document "+t.toString()+" without having read it first");var s=e.sizer(i);n+=s-o,r.push({maybeDocument:i,size:s})}),this.documentCache.addEntries(t,r,n)},e.prototype.getFromCache=function(t,e){return this.documentCache.getSizedEntry(t,e)},e}(wp),Dd=function(){function t(t,e){var n=this;this.clientId=t,this.mutationQueues={},this.listenSequence=new Qf(0),this._started=!1,this._started=!0,this.referenceDelegate=e(this),this.queryCache=new Sd(this);this.remoteDocumentCache=new Cd(function(t){return n.referenceDelegate.documentSize(t)})}return t.createLruPersistence=function(e,n,r){return new t(e,function(t){return new Rd(t,new ed(n),r)})},t.createEagerPersistence=function(e){return new t(e,function(t){return new kd(t)})},t.prototype.shutdown=function(t){return this._started=!1,Promise.resolve()},Object.defineProperty(t.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),t.prototype.getActiveClients=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){return[2,[this.clientId]]})})},t.prototype.setPrimaryStateListener=function(t){return t(!0)},t.prototype.setNetworkEnabled=function(t){},t.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new Td(this.referenceDelegate),this.mutationQueues[t.toKey()]=e),e},t.prototype.getQueryCache=function(){return this.queryCache},t.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},t.prototype.runTransaction=function(t,e,n){var r=this;Gc("MemoryPersistence","Starting transaction:",t);var i=new Ad(this.listenSequence.next());return this.referenceDelegate.onTransactionStarted(),n(i).next(function(t){return r.referenceDelegate.onTransactionCommitted(i).next(function(){return t})}).toPromise()},t.prototype.mutationQueuesContainKey=function(t,e){return cp.or((n=this.mutationQueues,r=[],sh(n,function(t,e){return r.push(e)}),r).map(function(n){return function(){return n.containsKey(t,e)}}));var n,r},t}(),Ad=function(){return function(t){this.currentSequenceNumber=t}}(),kd=function(){function t(t){this.persistence=t}return t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.addReference=function(t,e){return this.orphanedDocuments.delete(e),cp.resolve()},t.prototype.removeReference=function(t,e){return this.orphanedDocuments.add(e),cp.resolve()},t.prototype.removeMutationReference=function(t,e){return this.orphanedDocuments.add(e),cp.resolve()},t.prototype.removeTarget=function(t,e){var n=this,r=this.persistence.getQueryCache();return r.getMatchingKeysForTargetId(t,e.targetId).next(function(t){t.forEach(function(t){return n.orphanedDocuments.add(t)})}).next(function(){return r.removeQueryData(t,e)})},t.prototype.onTransactionStarted=function(){this.orphanedDocuments=new Set},t.prototype.onTransactionCommitted=function(t){var e=this,n=this.persistence.getRemoteDocumentCache();return cp.forEach(this.orphanedDocuments,function(r){return e.isReferenced(t,r).next(function(e){return e?cp.resolve():n.removeEntry(t,r).next(function(){})})})},t.prototype.updateLimboDocument=function(t,e){var n=this;return this.isReferenced(t,e).next(function(t){t?n.orphanedDocuments.delete(e):n.orphanedDocuments.add(e)})},t.prototype.documentSize=function(t){return 0},t.prototype.isReferenced=function(t,e){var n=this;return cp.or([function(){return n.persistence.getQueryCache().containsKey(t,e)},function(){return n.persistence.mutationQueuesContainKey(t,e)},function(){return cp.resolve(n.inMemoryPins.containsKey(e))}])},t}(),Rd=function(){function t(t,e,n){this.persistence=t,this.serializer=e,this.orphanedSequenceNumbers=new _p(function(t){return Zf(t.path)}),this.garbageCollector=new ad(this,n)}return t.prototype.onTransactionStarted=function(){},t.prototype.onTransactionCommitted=function(t){return cp.resolve()},t.prototype.forEachTarget=function(t,e){return this.persistence.getQueryCache().forEachTarget(t,e)},t.prototype.getSequenceNumberCount=function(t){var e=this.orphanedDocumentCount(t);return this.persistence.getQueryCache().getTargetCount(t).next(function(t){return e.next(function(e){return t+e})})},t.prototype.orphanedDocumentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,function(t){e++}).next(function(){return e})},t.prototype.forEachOrphanedDocumentSequenceNumber=function(t,e){var n=this;return cp.forEach(this.orphanedSequenceNumbers,function(r,i){return n.isPinned(t,r,i).next(function(t){return t?cp.resolve():e(i)})})},t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.removeTargets=function(t,e,n){return this.persistence.getQueryCache().removeTargets(t,e,n)},t.prototype.removeOrphanedDocuments=function(t,e){var n=this,r=0,i=this.persistence.getRemoteDocumentCache();return i.forEachDocumentKey(t,function(o){return n.isPinned(t,o,e).next(function(e){return e?cp.resolve():(r++,i.removeEntry(t,o).next())})}).next(function(){return r})},t.prototype.removeMutationReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),cp.resolve()},t.prototype.removeTarget=function(t,e){var n=e.copy({sequenceNumber:t.currentSequenceNumber});return this.persistence.getQueryCache().updateQueryData(t,n)},t.prototype.addReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),cp.resolve()},t.prototype.removeReference=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),cp.resolve()},t.prototype.updateLimboDocument=function(t,e){return this.orphanedSequenceNumbers.set(e,t.currentSequenceNumber),cp.resolve()},t.prototype.documentSize=function(t){var e,n=this.serializer.toDbRemoteDocument(t);if(n.document)e=n.document;else if(n.unknownDocument)e=n.unknownDocument;else{if(!n.noDocument)throw Xc("Unknown remote document type");e=n.noDocument}return JSON.stringify(e).length},t.prototype.isPinned=function(t,e,n){var r=this;return cp.or([function(){return r.persistence.mutationQueuesContainKey(t,e)},function(){return cp.resolve(r.inMemoryPins.containsKey(e))},function(){return r.persistence.getQueryCache().containsKey(t,e)},function(){var t=r.orphanedSequenceNumbers.get(e);return cp.resolve(void 0!==t&&t>n)}])},t.prototype.getCacheSize=function(t){return this.persistence.getRemoteDocumentCache().getSize(t)},t}(),Od=function(){function t(t,e,n,r,i){this.queue=t,this.timerId=e,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=i,this.timerPromise=null,this.lastAttemptTime=Date.now(),this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndRun=function(t){var e=this;this.cancel();var n=Math.floor(this.currentBaseMs+this.jitterDelayMs()),r=Math.max(0,Date.now()-this.lastAttemptTime),i=Math.max(0,n-r);this.currentBaseMs>0&&Gc("ExponentialBackoff","Backing off for "+i+" ms (base delay: "+this.currentBaseMs+" ms, delay with jitter: "+n+" ms, last attempt: "+r+" ms ago)"),this.timerPromise=this.queue.enqueueAfterDelay(this.timerId,i,function(){return e.lastAttemptTime=Date.now(),t()}),this.currentBaseMs*=this.backoffFactor,this.currentBaseMs<this.initialDelayMs&&(this.currentBaseMs=this.initialDelayMs),this.currentBaseMs>this.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},t.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}();!function(t){t[t.Initial=0]="Initial",t[t.Starting=1]="Starting",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff"}(Id||(Id={}));var Pd,Ld,Md=1e3,xd=6e4,Fd=1.5,Ud=function(){function t(t,e,n,r,i,o){this.queue=t,this.idleTimerId=n,this.connection=r,this.credentialsProvider=i,this.listener=o,this.state=Id.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new Od(t,e,Md,Fd,xd)}return t.prototype.isStarted=function(){return this.state===Id.Starting||this.state===Id.Open||this.state===Id.Backoff},t.prototype.isOpen=function(){return this.state===Id.Open},t.prototype.start=function(){this.state!==Id.Error?(Jc(this.state===Id.Initial,"Already started"),this.auth()):this.performBackoff()},t.prototype.stop=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return this.isStarted()?[4,this.close(Id.Initial)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},t.prototype.inhibitBackoff=function(){Jc(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=Id.Initial,this.backoff.reset()},t.prototype.markIdle=function(){var t=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,function(){return t.handleIdleCloseTimer()}))},t.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},t.prototype.handleIdleCloseTimer=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){return this.isOpen()?[2,this.close(Id.Initial)]:[2]})})},t.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},t.prototype.close=function(t,e){return $e(this,void 0,void 0,function(){return Ze(this,function(n){switch(n.label){case 0:return Jc(this.isStarted(),"Only started streams should be closed."),Jc(t===Id.Error||vl(e),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,t!==Id.Error?this.backoff.reset():e&&e.code===th.RESOURCE_EXHAUSTED?(zc(e.toString()),zc("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):e&&e.code===th.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=t,[4,this.listener.onClose(e)];case 1:return n.sent(),[2]}})})},t.prototype.tearDown=function(){},t.prototype.auth=function(){var t=this;Jc(this.state===Id.Initial,"Must be in initial state to auth"),this.state=Id.Starting;var e=this.getCloseGuardedDispatcher(this.closeCount),n=this.closeCount;this.credentialsProvider.getToken().then(function(e){t.closeCount===n&&t.startStream(e)},function(n){e(function(){var e=new eh(th.UNKNOWN,"Fetching auth token failed: "+n.message);return t.handleStreamClose(e)})})},t.prototype.startStream=function(t){var e=this;Jc(this.state===Id.Starting,"Trying to start stream in a non-starting state");var n=this.getCloseGuardedDispatcher(this.closeCount);this.stream=this.startRpc(t),this.stream.onOpen(function(){n(function(){return Jc(e.state===Id.Starting,"Expected stream to be in state Starting, but was "+e.state),e.state=Id.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t)})})},t.prototype.performBackoff=function(){var t=this;Jc(this.state===Id.Error,"Should only perform backoff when in Error state"),this.state=Id.Backoff,this.backoff.backoffAndRun(function(){return $e(t,void 0,void 0,function(){return Ze(this,function(t){return Jc(this.state===Id.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=Id.Initial,this.start(),Jc(this.isStarted(),"PersistentStream should have started"),[2]})})})},t.prototype.handleStreamClose=function(t){return Jc(this.isStarted(),"Can't handle server close on non-started stream"),Gc("PersistentStream","close with error: "+t),this.stream=null,this.close(Id.Error,t)},t.prototype.getCloseGuardedDispatcher=function(t){var e=this;return function(n){e.queue.enqueueAndForget(function(){return e.closeCount===t?n():(Gc("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}},t}(),qd=function(t){function e(e,n,r,i,o){var s=t.call(this,e,Kf.ListenStreamConnectionBackoff,Kf.ListenStreamIdle,n,r,o)||this;return s.serializer=i,s}return Xe(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.sendRequest(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},e}(Ud),Bd=function(t){function e(e,n,r,i,o){var s=t.call(this,e,Kf.WriteStreamConnectionBackoff,Kf.WriteStreamIdle,n,r,o)||this;return s.serializer=i,s.handshakeComplete_=!1,s}return Xe(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.handshakeComplete_},enumerable:!0,configurable:!0}),e.prototype.start=function(){this.handshakeComplete_=!1,t.prototype.start.call(this)},e.prototype.tearDown=function(){this.handshakeComplete_&&this.writeMutations([])},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(Jc(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.handshakeComplete_){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults,t.commitTime),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return Jc(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){Jc(this.isOpen(),"Writing handshake requires an opened stream"),Jc(!this.handshakeComplete_,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},e.prototype.writeMutations=function(t){var e=this;Jc(this.isOpen(),"Writing mutations requires an opened stream"),Jc(this.handshakeComplete_,"Handshake must be complete before writing mutations"),Jc(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map(function(t){return e.serializer.toMutation(t)})};this.sendRequest(n)},e}(Ud),Vd=function(){function t(t,e,n,r){this.queue=t,this.connection=e,this.credentials=n,this.serializer=r}return t.prototype.newPersistentWriteStream=function(t){return new Bd(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.newPersistentWatchStream=function(t){return new qd(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.commit=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,writes:t.map(function(t){return e.serializer.toMutation(t)})};return this.invokeRPC("Commit",n).then(function(t){return e.serializer.fromWriteResults(t.writeResults,t.commitTime)})},t.prototype.lookup=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,documents:t.map(function(t){return e.serializer.toName(t)})};return this.invokeStreamingRPC("BatchGetDocuments",n).then(function(n){var r=tf();n.forEach(function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)});var i=[];return t.forEach(function(t){var e=r.get(t);Jc(!!e,"Missing entity in write response for "+t),i.push(e)}),i})},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken().then(function(r){return n.connection.invokeRPC(t,e,r)}).catch(function(t){throw t.code===th.UNAUTHENTICATED&&n.credentials.invalidateToken(),t})},t.prototype.invokeStreamingRPC=function(t,e){var n=this;return this.credentials.getToken().then(function(r){return n.connection.invokeStreamingRPC(t,e,r)}).catch(function(t){throw t.code===th.UNAUTHENTICATED&&n.credentials.invalidateToken(),t})},t}(),Wd=function(){function t(t){this.datastore=t,this.readVersions=of(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e;if(t instanceof Qh)e=t.version;else{if(!(t instanceof Hh))throw Xc("Document in a transaction was a "+t.constructor.name);e=Ol.forDeletedDoc()}var n=this.readVersions.get(t.key);if(null!==n){if(!e.isEqual(n))throw new eh(th.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.lookup=function(t){var e=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(t).then(function(t){return t.forEach(function(t){t instanceof Hh||t instanceof Qh?e.recordVersion(t):Xc("Document in a transaction was a "+t.constructor.name)}),t})},t.prototype.write=function(t){if(this.committed)throw new eh(th.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(t)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return e?ql.updateTime(e):ql.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.isEqual(Ol.forDeletedDoc()))throw new eh(th.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?ql.updateTime(e):ql.exists(!0)},t.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,e){this.write(e.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new Kl(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,Ol.forDeletedDoc())},t.prototype.commit=function(){var t=this,e=this.readVersions;return this.mutations.forEach(function(t){e=e.remove(t.key)}),e.isEmpty()?this.datastore.commit(this.mutations).then(function(){t.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},t}();!function(t){t[t.Unknown=0]="Unknown",t[t.Online=1]="Online",t[t.Offline=2]="Offline"}(Pd||(Pd={})),function(t){t[t.RemoteStore=0]="RemoteStore",t[t.SharedClientState=1]="SharedClientState"}(Ld||(Ld={}));var jd=function(){function t(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state=Pd.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}return t.prototype.handleWatchStreamStart=function(){var t=this;0===this.watchStreamFailures&&(this.setAndBroadcast(Pd.Unknown),Jc(null===this.onlineStateTimer,"onlineStateTimer shouldn't be started yet"),this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(Kf.OnlineStateTimeout,1e4,function(){return t.onlineStateTimer=null,Jc(t.state===Pd.Unknown,"Timer should be canceled if we transitioned to a different state."),t.logClientOfflineWarningIfNecessary("Backend didn't respond within 10 seconds."),t.setAndBroadcast(Pd.Offline),Promise.resolve()}))},t.prototype.handleWatchStreamFailure=function(t){this.state===Pd.Online?(this.setAndBroadcast(Pd.Unknown),Jc(0===this.watchStreamFailures,"watchStreamFailures must be 0"),Jc(null===this.onlineStateTimer,"onlineStateTimer must be null")):(this.watchStreamFailures++,this.watchStreamFailures>=1&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary("Connection failed 1 times. Most recent error: "+t.toString()),this.setAndBroadcast(Pd.Offline)))},t.prototype.set=function(t){this.clearOnlineStateTimer(),this.watchStreamFailures=0,t===Pd.Online&&(this.shouldWarnClientIsOffline=!1),this.setAndBroadcast(t)},t.prototype.setAndBroadcast=function(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))},t.prototype.logClientOfflineWarningIfNecessary=function(t){var e="Could not reach Cloud Firestore backend. "+t+"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.";this.shouldWarnClientIsOffline?(zc(e),this.shouldWarnClientIsOffline=!1):Gc("OnlineStateTracker",e)},t.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},t}(),Kd=function(){function t(t,e,n,r){this.localStore=t,this.datastore=e,this.writePipeline=[],this.listenTargets={},this.watchChangeAggregator=null,this.networkEnabled=!1,this.isPrimary=!1,this.onlineStateTracker=new jd(n,r),this.watchStream=this.datastore.newPersistentWatchStream({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)}),this.writeStream=this.datastore.newPersistentWriteStream({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.enableNetwork=function(){return $e(this,void 0,void 0,function(){var t;return Ze(this,function(e){switch(e.label){case 0:return this.networkEnabled=!0,this.canUseNetwork()?(t=this.writeStream,[4,this.localStore.getLastStreamToken()]):[3,3];case 1:return t.lastStreamToken=e.sent(),this.shouldStartWatchStream()?this.startWatchStream():this.onlineStateTracker.set(Pd.Unknown),[4,this.fillWritePipeline()];case 2:e.sent(),e.label=3;case 3:return[2]}})})},t.prototype.disableNetwork=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Pd.Offline),[2]}})})},t.prototype.disableNetworkInternal=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return[4,this.writeStream.stop()];case 1:return t.sent(),[4,this.watchStream.stop()];case 2:return t.sent(),this.writePipeline.length>0&&(Gc("RemoteStore","Stopping write stream with "+this.writePipeline.length+" pending writes"),this.writePipeline=[]),this.cleanUpWatchStreamState(),[2]}})})},t.prototype.shutdown=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return Gc("RemoteStore","RemoteStore shutting down."),this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Pd.Unknown),[2]}})})},t.prototype.listen=function(t){Jc(!rh(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){Jc(rh(this.listenTargets,t),"unlisten called without assigned target ID!"),delete this.listenTargets[t],this.watchStream.isOpen()&&this.sendUnwatchRequest(t),ah(this.listenTargets)&&(this.watchStream.isOpen()?this.watchStream.markIdle():this.canUseNetwork()&&this.onlineStateTracker.set(Pd.Unknown))},t.prototype.getQueryDataForTarget=function(t){return this.listenTargets[t]||null},t.prototype.getRemoteKeysForTarget=function(t){return this.syncEngine.getRemoteKeysForTarget(t)},t.prototype.sendWatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.startWatchStream=function(){Jc(this.shouldStartWatchStream(),"startWatchStream() called when shouldStartWatchStream() is false."),this.watchChangeAggregator=new Ef(this),this.watchStream.start(),this.onlineStateTracker.handleWatchStreamStart()},t.prototype.shouldStartWatchStream=function(){return this.canUseNetwork()&&!this.watchStream.isStarted()&&!ah(this.listenTargets)},t.prototype.canUseNetwork=function(){return this.isPrimary&&this.networkEnabled},t.prototype.cleanUpWatchStreamState=function(){this.watchChangeAggregator=null},t.prototype.onWatchStreamOpen=function(){return $e(this,void 0,void 0,function(){var t=this;return Ze(this,function(e){return oh(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),[2]})})},t.prototype.onWatchStreamClose=function(t){return $e(this,void 0,void 0,function(){return Ze(this,function(e){return void 0===t&&Jc(!this.shouldStartWatchStream(),"Watch stream was stopped gracefully while still needed."),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.onlineStateTracker.handleWatchStreamFailure(t),this.startWatchStream()):this.onlineStateTracker.set(Pd.Unknown),[2]})})},t.prototype.onWatchStreamChange=function(t,e){return $e(this,void 0,void 0,function(){var n;return Ze(this,function(r){switch(r.label){case 0:return this.onlineStateTracker.set(Pd.Online),t instanceof _f&&t.state===pf.Removed&&t.cause?[2,this.handleTargetError(t)]:(t instanceof vf?this.watchChangeAggregator.handleDocumentChange(t):t instanceof bf?this.watchChangeAggregator.handleExistenceFilter(t):(Jc(t instanceof _f,"Expected watchChange to be an instance of WatchTargetChange"),this.watchChangeAggregator.handleTargetChange(t)),e.isEqual(Ol.MIN)?[3,3]:[4,this.localStore.getLastRemoteSnapshotVersion()]);case 1:return n=r.sent(),e.compareTo(n)>=0?[4,this.raiseWatchSnapshot(e)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[2]}})})},t.prototype.raiseWatchSnapshot=function(t){var e=this;Jc(!t.isEqual(Ol.MIN),"Can't raise event for unknown SnapshotVersion");var n=this.watchChangeAggregator.createRemoteEvent(t);return oh(n.targetChanges,function(n,r){if(r.resumeToken.length>0){var i=e.listenTargets[n];i&&(e.listenTargets[n]=i.copy({resumeToken:r.resumeToken,snapshotVersion:t}))}}),n.targetMismatches.forEach(function(t){var n=e.listenTargets[t];if(n){e.listenTargets[t]=n.copy({resumeToken:Zc()}),e.sendUnwatchRequest(t);var r=new Ll(n.query,t,_l.ExistenceFilterMismatch,n.sequenceNumber);e.sendWatchRequest(r)}}),this.syncEngine.applyRemoteEvent(n)},t.prototype.handleTargetError=function(t){var e=this;Jc(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach(function(t){r=r.then(function(){return $e(e,void 0,void 0,function(){return Ze(this,function(e){return rh(this.listenTargets,t)?(delete this.listenTargets[t],this.watchChangeAggregator.removeTarget(t),[2,this.syncEngine.rejectListen(t,n)]):[2]})})})}),r},t.prototype.fillWritePipeline=function(){return $e(this,void 0,void 0,function(){var t,e;return Ze(this,function(n){switch(n.label){case 0:return this.canAddToWritePipeline()?(t=this.writePipeline.length>0?this.writePipeline[this.writePipeline.length-1].batchId:ip,[4,this.localStore.nextMutationBatch(t)]):[3,4];case 1:return null!==(e=n.sent())?[3,2]:(0===this.writePipeline.length&&this.writeStream.markIdle(),[3,4]);case 2:return this.addToWritePipeline(e),[4,this.fillWritePipeline()];case 3:n.sent(),n.label=4;case 4:return this.shouldStartWriteStream()&&this.startWriteStream(),[2]}})})},t.prototype.canAddToWritePipeline=function(){return this.canUseNetwork()&&this.writePipeline.length<10},t.prototype.outstandingWrites=function(){return this.writePipeline.length},t.prototype.addToWritePipeline=function(t){Jc(this.canAddToWritePipeline(),"addToWritePipeline called when pipeline is full"),this.writePipeline.push(t),this.writeStream.isOpen()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.canUseNetwork()&&!this.writeStream.isStarted()&&this.writePipeline.length>0},t.prototype.startWriteStream=function(){Jc(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},t.prototype.onWriteStreamOpen=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){return this.writeStream.writeHandshake(),[2]})})},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.writePipeline;e<n.length;e++){var r=n[e];t.writeStream.writeMutations(r.mutations)}}).catch(function(e){return t.ignoreIfPrimaryLeaseLoss(e)})},t.prototype.ignoreIfPrimaryLeaseLoss=function(t){if(!dd(t))throw t;Gc("RemoteStore","Unexpectedly lost primary lease")},t.prototype.onMutationResult=function(t,e){var n=this;Jc(this.writePipeline.length>0,"Got result for empty write pipeline");var r=this.writePipeline.shift(),i=sp.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(i).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){return $e(this,void 0,void 0,function(){var e=this;return Ze(this,function(n){return void 0===t&&Jc(!this.shouldStartWriteStream(),"Write stream was stopped gracefully while still needed."),t&&this.writePipeline.length>0?(void 0,[2,(this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t)).then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})]):[2]})})},t.prototype.handleHandshakeError=function(t){return $e(this,void 0,void 0,function(){var e=this;return Ze(this,function(n){return Jl(t.code)||t.code===th.ABORTED?(Gc("RemoteStore","RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=Zc(),[2,this.localStore.setLastStreamToken(Zc()).catch(function(t){return e.ignoreIfPrimaryLeaseLoss(t)})]):[2]})})},t.prototype.handleWriteError=function(t){return $e(this,void 0,void 0,function(){var e,n=this;return Ze(this,function(r){return Jl(t.code)?(e=this.writePipeline.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(e.batchId,t).then(function(){return n.fillWritePipeline()})]):[2]})})},t.prototype.createTransaction=function(){return new Wd(this.datastore)},t.prototype.handleCredentialChange=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return this.canUseNetwork()?(Gc("RemoteStore","RemoteStore restarting streams for new credential"),this.networkEnabled=!1,[4,this.disableNetworkInternal()]):[3,3];case 1:return t.sent(),this.onlineStateTracker.set(Pd.Unknown),[4,this.enableNetwork()];case 2:t.sent(),t.label=3;case 3:return[2]}})})},t.prototype.applyPrimaryState=function(t){return $e(this,void 0,void 0,function(){return Ze(this,function(e){switch(e.label){case 0:return this.isPrimary=t,t&&this.networkEnabled?[4,this.enableNetwork()]:[3,2];case 1:return e.sent(),[3,4];case 2:return t?[3,4]:[4,this.disableNetworkInternal()];case 3:e.sent(),this.onlineStateTracker.set(Pd.Unknown),e.label=4;case 4:return[2]}})})},t}(),Qd=function(){return function(){this.listeners=[]}}(),Hd=function(){function t(t){this.syncEngine=t,this.queries=new _p(function(t){return t.canonicalId()}),this.onlineState=Pd.Unknown,this.syncEngine.subscribe(this)}return t.prototype.listen=function(t){var e=t.query,n=!1,r=this.queries.get(e);return r||(n=!0,r=new Qd,this.queries.set(e,r)),r.listeners.push(t),t.applyOnlineStateChange(this.onlineState),r.viewSnap&&t.onViewSnapshot(r.viewSnap),n?this.syncEngine.listen(e).then(function(t){return r.targetId=t,t}):Promise.resolve(r.targetId)},t.prototype.unlisten=function(t){return $e(this,void 0,void 0,function(){var e,n,r,i;return Ze(this,function(o){return e=t.query,n=!1,(r=this.queries.get(e))&&(i=r.listeners.indexOf(t))>=0&&(r.listeners.splice(i,1),n=0===r.listeners.length),n?(this.queries.delete(e),[2,this.syncEngine.unlisten(e)]):[2]})})},t.prototype.onWatchChange=function(t){for(var e=0,n=t;e<n.length;e++){var r=n[e],i=r.query,o=this.queries.get(i);if(o){for(var s=0,a=o.listeners;s<a.length;s++){a[s].onViewSnapshot(r)}o.viewSnap=r}}},t.prototype.onWatchError=function(t,e){var n=this.queries.get(t);if(n)for(var r=0,i=n.listeners;r<i.length;r++){i[r].onError(e)}this.queries.delete(t)},t.prototype.onOnlineStateChange=function(t){this.onlineState=t,this.queries.forEach(function(e,n){for(var r=0,i=n.listeners;r<i.length;r++){i[r].applyOnlineStateChange(t)}})},t}(),Gd=function(){function t(t,e,n){this.query=t,this.queryObserver=e,this.raisedInitialEvent=!1,this.onlineState=Pd.Unknown,this.options=n||{}}return t.prototype.onViewSnapshot=function(t){if(Jc(t.docChanges.length>0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeMetadataChanges){for(var e=[],n=0,r=t.docChanges;n<r.length;n++){var i=r[n];i.type!==hf.Metadata&&e.push(i)}t=new yf(t.query,t.docs,t.oldDocs,e,t.mutatedKeys,t.fromCache,t.syncStateChanged,!0)}this.raisedInitialEvent?this.shouldRaiseEvent(t)&&this.queryObserver.next(t):this.shouldRaiseInitialEvent(t,this.onlineState)&&this.raiseInitialEvent(t),this.snap=t},t.prototype.onError=function(t){this.queryObserver.error(t)},t.prototype.applyOnlineStateChange=function(t){this.onlineState=t,this.snap&&!this.raisedInitialEvent&&this.shouldRaiseInitialEvent(this.snap,t)&&this.raiseInitialEvent(this.snap)},t.prototype.shouldRaiseInitialEvent=function(t,e){if(Jc(!this.raisedInitialEvent,"Determining whether to raise first event but already had first event"),!t.fromCache)return!0;var n=e!==Pd.Offline;return this.options.waitForSyncWhenOnline&&n?(Jc(t.fromCache,"Waiting for sync, but snapshot is not from cache"),!1):!t.docs.isEmpty()||e===Pd.Offline},t.prototype.shouldRaiseEvent=function(t){if(t.docChanges.length>0)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeMetadataChanges},t.prototype.raiseInitialEvent=function(t){Jc(!this.raisedInitialEvent,"Trying to raise initial events for second time"),t=yf.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache),this.raisedInitialEvent=!0,this.queryObserver.next(t)},t}(),zd=function(){function t(t,e,n){this.targetId=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e,n){for(var r=af(),i=af(),o=0,s=n.docChanges;o<s.length;o++){var a=s[o];switch(a.type){case hf.Added:r=r.add(a.doc.key);break;case hf.Removed:i=i.add(a.doc.key)}}return new t(e,r,i)},t}(),Yd=function(){return function(t){this.key=t}}(),Xd=function(){return function(t){this.key=t}}(),Jd=function(){function t(t,e){this.query=t,this._syncedDocuments=e,this.syncState=null,this.current=!1,this.limboDocuments=af(),this.mutatedKeys=af(),this.documentSet=new ff(t.docComparator.bind(t))}return Object.defineProperty(t.prototype,"syncedDocuments",{get:function(){return this._syncedDocuments},enumerable:!0,configurable:!0}),t.prototype.computeDocChanges=function(t,e){var n=this,r=e?e.changeSet:new df,i=e?e.documentSet:this.documentSet,o=e?e.mutatedKeys:this.mutatedKeys,s=i,a=!1,u=this.query.hasLimit()&&i.size===this.query.limit?i.last():null;if(t.inorderTraversal(function(t,e){var c=i.get(t),h=e instanceof Qh?e:null;h&&(Jc(t.isEqual(h.key),"Mismatching keys found in document changes: "+t+" != "+h.key),h=n.query.matches(h)?h:null);var l=!!c&&n.mutatedKeys.has(c.key),f=!!h&&(h.hasLocalMutations||n.mutatedKeys.has(h.key)&&h.hasCommittedMutations),p=!1;c&&h?c.data.isEqual(h.data)?l!==f&&(r.track({type:hf.Metadata,doc:h}),p=!0):n.shouldWaitForSyncedDocument(c,h)||(r.track({type:hf.Modified,doc:h}),p=!0,u&&n.query.docComparator(h,u)>0&&(a=!0)):!c&&h?(r.track({type:hf.Added,doc:h}),p=!0):c&&!h&&(r.track({type:hf.Removed,doc:c}),p=!0,u&&(a=!0));p&&(h?(s=s.add(h),o=f?o.add(t):o.delete(t)):(s=s.delete(t),o=o.delete(t)))}),this.query.hasLimit())for(;s.size>this.query.limit;){var c=s.last();s=s.delete(c.key),o=o.delete(c.key),r.track({type:hf.Removed,doc:c})}return Jc(!a||!e,"View was refilled using docs that themselves needed refilling."),{documentSet:s,changeSet:r,needsRefill:a,mutatedKeys:o}},t.prototype.shouldWaitForSyncedDocument=function(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations},t.prototype.applyChanges=function(t,e,n){var r=this;Jc(!t.needsRefill,"Cannot apply changes that need a refill");var i=this.documentSet;this.documentSet=t.documentSet,this.mutatedKeys=t.mutatedKeys;var o=t.changeSet.getChanges();o.sort(function(t,e){return function(t,e){var n=function(t){switch(t){case hf.Added:return 1;case hf.Modified:case hf.Metadata:return 2;case hf.Removed:return 0;default:return Xc("Unknown ChangeType: "+t)}};return n(t)-n(e)}(t.type,e.type)||r.query.docComparator(t.doc,e.doc)}),this.applyTargetChange(n);var s=e?this.updateLimboDocuments():[],a=0===this.limboDocuments.size&&this.current?lf.Synced:lf.Local,u=a!==this.syncState;return this.syncState=a,0!==o.length||u?{snapshot:new yf(this.query,t.documentSet,i,o,t.mutatedKeys,a===lf.Local,u,!1),limboChanges:s}:{limboChanges:s}},t.prototype.applyOnlineStateChange=function(t){return this.current&&t===Pd.Offline?(this.current=!1,this.applyChanges({documentSet:this.documentSet,changeSet:new df,mutatedKeys:this.mutatedKeys,needsRefill:!1},!1)):{limboChanges:[]}},t.prototype.shouldBeInLimbo=function(t){return!this._syncedDocuments.has(t)&&(!!this.documentSet.has(t)&&!this.documentSet.get(t).hasLocalMutations)},t.prototype.applyTargetChange=function(t){var e=this;t&&(t.addedDocuments.forEach(function(t){return e._syncedDocuments=e._syncedDocuments.add(t)}),t.modifiedDocuments.forEach(function(t){return Jc(e._syncedDocuments.has(t),"Modified document "+t+" not found in view.")}),t.removedDocuments.forEach(function(t){return e._syncedDocuments=e._syncedDocuments.delete(t)}),this.current=t.current)},t.prototype.updateLimboDocuments=function(){var t=this;if(!this.current)return[];var e=this.limboDocuments;this.limboDocuments=af(),this.documentSet.forEach(function(e){t.shouldBeInLimbo(e.key)&&(t.limboDocuments=t.limboDocuments.add(e.key))});var n=[];return e.forEach(function(e){t.limboDocuments.has(e)||n.push(new Xd(e))}),this.limboDocuments.forEach(function(t){e.has(t)||n.push(new Yd(t))}),n},t.prototype.synchronizeWithPersistedState=function(t,e){this._syncedDocuments=e,this.limboDocuments=af();var n=this.computeDocChanges(t);return this.applyChanges(n,!0)},t.prototype.computeInitialSnapshot=function(){return yf.fromInitialDocuments(this.query,this.documentSet,this.mutatedKeys,this.syncState===lf.Local)},t}();var $d=function(){return function(t,e,n){this.query=t,this.targetId=e,this.view=n}}(),Zd=function(){return function(t){this.key=t}}(),ty=function(){function t(t,e,n,r){this.localStore=t,this.remoteStore=e,this.sharedClientState=n,this.currentUser=r,this.syncEngineListener=null,this.queryViewsByQuery=new _p(function(t){return t.canonicalId()}),this.queryViewsByTarget={},this.limboTargetsByKey=new zh(jh.comparator),this.limboResolutionsByTarget={},this.limboDocumentRefs=new _d,this.mutationUserCallbacks={},this.limboTargetIdGenerator=up.forSyncEngine(),this.isPrimary=void 0,this.onlineState=Pd.Unknown}return Object.defineProperty(t.prototype,"isPrimaryClient",{get:function(){return!0===this.isPrimary},enumerable:!0,configurable:!0}),t.prototype.subscribe=function(t){Jc(null!==t,"SyncEngine listener cannot be null"),Jc(null===this.syncEngineListener,"SyncEngine already has a subscriber."),this.syncEngineListener=t},t.prototype.listen=function(t){return $e(this,void 0,void 0,function(){var e,n,r,i,o;return Ze(this,function(s){switch(s.label){case 0:return this.assertSubscribed("listen()"),(r=this.queryViewsByQuery.get(t))?(e=r.targetId,this.sharedClientState.addLocalQueryTarget(e),n=r.view.computeInitialSnapshot(),[3,4]):[3,1];case 1:return[4,this.localStore.allocateQuery(t)];case 2:return i=s.sent(),o=this.sharedClientState.addLocalQueryTarget(i.targetId),e=i.targetId,[4,this.initializeViewAndComputeSnapshot(i,"current"===o)];case 3:n=s.sent(),this.isPrimary&&this.remoteStore.listen(i),s.label=4;case 4:return this.syncEngineListener.onWatchChange([n]),[2,e]}})})},t.prototype.initializeViewAndComputeSnapshot=function(t,e){var n=this,r=t.query;return this.localStore.executeQuery(r).then(function(i){return n.localStore.remoteDocumentKeys(t.targetId).then(function(o){var s=new Jd(r,o),a=s.computeDocChanges(i),u=gf.createSynthesizedTargetChangeForCurrentChange(t.targetId,e&&n.onlineState!==Pd.Offline),c=s.applyChanges(a,!0===n.isPrimary,u);Jc(0===c.limboChanges.length,"View returned limbo docs before target ack from the server."),Jc(!!c.snapshot,"applyChanges for new view should always return a snapshot");var h=new $d(r,t.targetId,s);return n.queryViewsByQuery.set(r,h),n.queryViewsByTarget[t.targetId]=h,c.snapshot})})},t.prototype.synchronizeViewAndComputeSnapshot=function(t){var e=this;return this.localStore.executeQuery(t.query).then(function(n){return e.localStore.remoteDocumentKeys(t.targetId).then(function(r){return $e(e,void 0,void 0,function(){var e;return Ze(this,function(i){return e=t.view.synchronizeWithPersistedState(n,r),this.isPrimary&&this.updateTrackedLimbos(t.targetId,e.limboChanges),[2,e]})})})})},t.prototype.unlisten=function(t){return $e(this,void 0,void 0,function(){var e,n=this;return Ze(this,function(r){switch(r.label){case 0:return this.assertSubscribed("unlisten()"),Jc(!!(e=this.queryViewsByQuery.get(t)),"Trying to unlisten on query not found:"+t),this.isPrimary?(this.sharedClientState.removeLocalQueryTarget(e.targetId),this.sharedClientState.isActiveQueryTarget(e.targetId)?[3,2]:[4,this.localStore.releaseQuery(t,!1).then(function(){n.sharedClientState.clearQueryState(e.targetId),n.remoteStore.unlisten(e.targetId),n.removeAndCleanupQuery(e)}).catch(function(t){return n.ignoreIfPrimaryLeaseLoss(t)})]):[3,3];case 1:r.sent(),r.label=2;case 2:return[3,5];case 3:return this.removeAndCleanupQuery(e),[4,this.localStore.releaseQuery(t,!0)];case 4:r.sent(),r.label=5;case 5:return[2]}})})},t.prototype.write=function(t,e){var n=this;return this.assertSubscribed("write()"),this.localStore.localWrite(t).then(function(t){return n.sharedClientState.addPendingMutation(t.batchId),n.addMutationCallback(t.batchId,e),n.emitNewSnapsAndNotifyLocalStore(t.changes)}).then(function(){return n.remoteStore.fillWritePipeline()})},t.prototype.wrapUpdateFunctionError=function(t){return t},t.prototype.runTransaction=function(t,e){var n=this;void 0===e&&(e=5),Jc(e>=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!vl(e)&&e.catch&&e.then?e.catch(function(t){return Promise.reject(n.wrapUpdateFunctionError(t))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(t){return Promise.reject(n.wrapUpdateFunctionError(t))}}().then(function(i){return r.commit().then(function(){return i}).catch(function(r){return 0===e?Promise.reject(r):n.runTransaction(t,e-1)})})},t.prototype.applyRemoteEvent=function(t){var e=this;return this.assertSubscribed("applyRemoteEvent()"),this.localStore.applyRemoteEvent(t).then(function(n){return sh(t.targetChanges,function(t,n){var r=e.limboResolutionsByTarget[t];r&&(Jc(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?Jc(r.receivedDocument,"Received change for limbo target document without add."):n.removedDocuments.size>0&&(Jc(r.receivedDocument,"Received remove for limbo target document without add."),r.receivedDocument=!1))}),e.emitNewSnapsAndNotifyLocalStore(n,t)}).catch(function(t){return e.ignoreIfPrimaryLeaseLoss(t)})},t.prototype.applyOnlineStateChange=function(t,e){if(this.isPrimary&&e===Ld.RemoteStore||!this.isPrimary&&e===Ld.SharedClientState){var n=[];this.queryViewsByQuery.forEach(function(e,r){var i=r.view.applyOnlineStateChange(t);Jc(0===i.limboChanges.length,"OnlineState should not affect limbo documents."),i.snapshot&&n.push(i.snapshot)}),this.syncEngineListener.onOnlineStateChange(t),this.syncEngineListener.onWatchChange(n),this.onlineState=t,this.isPrimary&&this.sharedClientState.setOnlineState(t)}},t.prototype.rejectListen=function(t,e){return $e(this,void 0,void 0,function(){var n,r,i,o,s,a,u=this;return Ze(this,function(c){switch(c.label){case 0:return this.assertSubscribed("rejectListens()"),this.sharedClientState.updateQueryState(t,"rejected",e),n=this.limboResolutionsByTarget[t],(r=n&&n.key)?(this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboResolutionsByTarget[t],i=(i=new zh(jh.comparator)).insert(r,new Hh(r,Ol.forDeletedDoc())),o=af().add(r),s=new mf(Ol.MIN,{},new Ml(Ch),i,o),[2,this.applyRemoteEvent(s)]):[3,1];case 1:return Jc(!!(a=this.queryViewsByTarget[t]),"Unknown targetId: "+t),[4,this.localStore.releaseQuery(a.query,!1).then(function(){return u.removeAndCleanupQuery(a)}).catch(function(t){return u.ignoreIfPrimaryLeaseLoss(t)})];case 2:c.sent(),this.syncEngineListener.onWatchError(a.query,e),c.label=3;case 3:return[2]}})})},t.prototype.applyBatchState=function(t,e,n){return $e(this,void 0,void 0,function(){var r;return Ze(this,function(i){switch(i.label){case 0:return this.assertSubscribed("applyBatchState()"),[4,this.localStore.lookupMutationDocuments(t)];case 1:return null===(r=i.sent())?(Gc("SyncEngine","Cannot apply mutation batch with id: "+t),[2]):"pending"!==e?[3,3]:[4,this.remoteStore.fillWritePipeline()];case 2:return i.sent(),[3,4];case 3:"acknowledged"===e||"rejected"===e?(this.processUserCallback(t,n||null),this.localStore.removeCachedMutationBatchMetadata(t)):Xc("Unknown batchState: "+e),i.label=4;case 4:return[4,this.emitNewSnapsAndNotifyLocalStore(r)];case 5:return i.sent(),[2]}})})},t.prototype.applySuccessfulWrite=function(t){var e=this;this.assertSubscribed("applySuccessfulWrite()");var n=t.batch.batchId;return this.processUserCallback(n,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.sharedClientState.updateMutationState(n,"acknowledged"),e.emitNewSnapsAndNotifyLocalStore(t)}).catch(function(t){return e.ignoreIfPrimaryLeaseLoss(t)})},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(r){return n.sharedClientState.updateMutationState(t,"rejected",e),n.emitNewSnapsAndNotifyLocalStore(r)}).catch(function(t){return n.ignoreIfPrimaryLeaseLoss(t)})},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new zh(Ch)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(Jc(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){var e=this;if(this.sharedClientState.removeLocalQueryTarget(t.targetId),this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.isPrimary){var n=this.limboDocumentRefs.referencesForId(t.targetId);this.limboDocumentRefs.removeReferencesForId(t.targetId),n.forEach(function(t){e.limboDocumentRefs.containsKey(t)||e.removeLimboTarget(t)})}},t.prototype.removeLimboTarget=function(t){var e=this.limboTargetsByKey.get(t);null!==e&&(this.remoteStore.unlisten(e),this.limboTargetsByKey=this.limboTargetsByKey.remove(t),delete this.limboResolutionsByTarget[e])},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n<r.length;n++){var i=r[n];if(i instanceof Yd)this.limboDocumentRefs.addReference(i.key,t),this.trackLimboChange(i);else if(i instanceof Xd){Gc("SyncEngine","Document no longer in limbo: "+i.key),this.limboDocumentRefs.removeReference(i.key,t),this.limboDocumentRefs.containsKey(i.key)||this.removeLimboTarget(i.key)}else Xc("Unknown limbo change: "+JSON.stringify(i))}},t.prototype.trackLimboChange=function(t){var e=t.key;if(!this.limboTargetsByKey.get(e)){Gc("SyncEngine","New document in limbo: "+e);var n=this.limboTargetIdGenerator.next(),r=wl.atPath(e.path);this.limboResolutionsByTarget[n]=new Zd(e),this.remoteStore.listen(new Ll(r,n,_l.LimboResolution,Qf.INVALID)),this.limboTargetsByKey=this.limboTargetsByKey.insert(e,n)}},t.prototype.currentLimboDocs=function(){return this.limboTargetsByKey},t.prototype.emitNewSnapsAndNotifyLocalStore=function(t,e){return $e(this,void 0,void 0,function(){var n,r,i,o=this;return Ze(this,function(s){switch(s.label){case 0:return n=[],r=[],i=[],this.queryViewsByQuery.forEach(function(s,a){i.push(Promise.resolve().then(function(){var e=a.view.computeDocChanges(t);return e.needsRefill?o.localStore.executeQuery(a.query).then(function(t){return a.view.computeDocChanges(t,e)}):e}).then(function(t){var i=e&&e.targetChanges[a.targetId],s=a.view.applyChanges(t,!0===o.isPrimary,i);if(o.updateTrackedLimbos(a.targetId,s.limboChanges),s.snapshot){o.isPrimary&&o.sharedClientState.updateQueryState(a.targetId,s.snapshot.fromCache?"not-current":"current"),n.push(s.snapshot);var u=zd.fromSnapshot(a.targetId,s.snapshot);r.push(u)}}))}),[4,Promise.all(i)];case 1:return s.sent(),this.syncEngineListener.onWatchChange(n),[4,this.localStore.notifyLocalViewChanges(r)];case 2:return s.sent(),[2]}})})},t.prototype.ignoreIfPrimaryLeaseLoss=function(t){return $e(this,void 0,void 0,function(){return Ze(this,function(e){if(!dd(t))throw t;return Gc("SyncEngine","Unexpectedly lost primary lease"),[2]})})},t.prototype.assertSubscribed=function(t){Jc(null!==this.syncEngineListener,"Trying to call "+t+" before calling subscribe().")},t.prototype.handleCredentialChange=function(t){return $e(this,void 0,void 0,function(){var e,n;return Ze(this,function(r){switch(r.label){case 0:return e=!this.currentUser.isEqual(t),this.currentUser=t,e?[4,this.localStore.handleUserChange(t)]:[3,3];case 1:return n=r.sent(),this.sharedClientState.handleUserChange(t,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]}})})},t.prototype.applyPrimaryState=function(t){return $e(this,void 0,void 0,function(){var e,n,r,i,o,s,a,u=this;return Ze(this,function(c){switch(c.label){case 0:return!0!==t||!0===this.isPrimary?[3,3]:(this.isPrimary=!0,[4,this.remoteStore.applyPrimaryState(!0)]);case 1:return c.sent(),e=this.sharedClientState.getAllActiveQueryTargets(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(e.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!==t||!1===this.isPrimary?[3,7]:(this.isPrimary=!1,s=[],a=Promise.resolve(),oh(this.queryViewsByTarget,function(t,e){u.sharedClientState.isLocalQueryTarget(t)?s.push(t):a=a.then(function(){return u.unlisten(e.query)}),u.remoteStore.unlisten(e.targetId)}),[4,a]);case 4:return c.sent(),[4,this.synchronizeQueryViewsAndRaiseSnapshots(s)];case 5:return c.sent(),this.resetLimboDocuments(),[4,this.remoteStore.applyPrimaryState(!1)];case 6:c.sent(),c.label=7;case 7:return[2]}})})},t.prototype.resetLimboDocuments=function(){var t=this;oh(this.limboResolutionsByTarget,function(e){t.remoteStore.unlisten(e)}),this.limboDocumentRefs.removeAllReferences(),this.limboResolutionsByTarget=[],this.limboTargetsByKey=new zh(jh.comparator)},t.prototype.synchronizeQueryViewsAndRaiseSnapshots=function(t){for(var e=this,n=Promise.resolve(),r=[],i=[],o=function(t){n=n.then(function(){return $e(e,void 0,void 0,function(){var e,n,o,s;return Ze(this,function(a){switch(a.label){case 0:return(n=this.queryViewsByTarget[t])?[4,this.localStore.releaseQuery(n.query,!0)]:[3,4];case 1:return a.sent(),[4,this.localStore.allocateQuery(n.query)];case 2:return e=a.sent(),[4,this.synchronizeViewAndComputeSnapshot(n)];case 3:return(o=a.sent()).snapshot&&i.push(o.snapshot),[3,8];case 4:return Jc(!0===this.isPrimary,"A secondary tab should never have an active query without an active view."),[4,this.localStore.getQueryForTarget(t)];case 5:return Jc(!!(s=a.sent()),"Query data for target "+t+" not found"),[4,this.localStore.allocateQuery(s)];case 6:return e=a.sent(),[4,this.initializeViewAndComputeSnapshot(e,!1)];case 7:a.sent(),a.label=8;case 8:return r.push(e),[2]}})})})},s=0,a=t;s<a.length;s++){o(a[s])}return n.then(function(){return e.syncEngineListener.onWatchChange(i),r})},t.prototype.getActiveClients=function(){return this.localStore.getActiveClients()},t.prototype.applyTargetState=function(t,e,n){return $e(this,void 0,void 0,function(){var r,i=this;return Ze(this,function(o){switch(o.label){case 0:if(this.isPrimary)return Gc("SyncEngine","Ignoring unexpected query state notification."),[2];if(!this.queryViewsByTarget[t])return[3,5];switch(e){case"current":case"not-current":return[3,1];case"rejected":return[3,2]}return[3,4];case 1:return[2,this.localStore.getNewDocumentChanges().then(function(n){return $e(i,void 0,void 0,function(){var r;return Ze(this,function(i){switch(i.label){case 0:return r=mf.createSynthesizedRemoteEventForCurrentChange(t,"current"===e),[4,this.emitNewSnapsAndNotifyLocalStore(n,r)];case 1:return i.sent(),[2]}})})},function(t){return $e(i,void 0,void 0,function(){var e;return Ze(this,function(n){switch(n.label){case 0:return function(t){return t.code===th.DATA_LOSS&&t.message===Ep}(t)?(e=[],oh(this.queryViewsByTarget,function(t){return e.push(t)}),[4,this.synchronizeQueryViewsAndRaiseSnapshots(e)]):[3,2];case 1:return n.sent(),[3,3];case 2:throw t;case 3:return[2]}})})})];case 2:return r=this.queryViewsByTarget[t],this.removeAndCleanupQuery(r),[4,this.localStore.releaseQuery(r.query,!0)];case 3:return o.sent(),this.syncEngineListener.onWatchError(r.query,n),[3,5];case 4:Xc("Unexpected target state: "+e),o.label=5;case 5:return[2]}})})},t.prototype.applyActiveTargetsChange=function(t,e){return $e(this,void 0,void 0,function(){var n,r,i,o,s,a,u,c,h,l=this;return Ze(this,function(f){switch(f.label){case 0:if(!this.isPrimary)return[2];n=0,r=t,f.label=1;case 1:return n<r.length?(h=r[n],Jc(!this.queryViewsByTarget[h],"Trying to add an already active target"),[4,this.localStore.getQueryForTarget(h)]):[3,6];case 2:return Jc(!!(i=f.sent()),"Query data for active target "+h+" not found"),[4,this.localStore.allocateQuery(i)];case 3:return o=f.sent(),[4,this.initializeViewAndComputeSnapshot(o,!1)];case 4:f.sent(),this.remoteStore.listen(o),f.label=5;case 5:return n++,[3,1];case 6:s=function(t){var e;return Ze(this,function(n){switch(n.label){case 0:return(e=a.queryViewsByTarget[t])?[4,a.localStore.releaseQuery(e.query,!1).then(function(){l.remoteStore.unlisten(t),l.removeAndCleanupQuery(e)}).catch(function(t){return l.ignoreIfPrimaryLeaseLoss(t)})]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})},a=this,u=0,c=e,f.label=7;case 7:return u<c.length?(h=c[u],[5,s(h)]):[3,10];case 8:f.sent(),f.label=9;case 9:return u++,[3,7];case 10:return[2]}})})},t.prototype.enableNetwork=function(){return this.localStore.setNetworkEnabled(!0),this.remoteStore.enableNetwork()},t.prototype.disableNetwork=function(){return this.localStore.setNetworkEnabled(!1),this.remoteStore.disableNetwork()},t.prototype.getRemoteKeysForTarget=function(t){var e=this.limboResolutionsByTarget[t];return e&&e.receivedDocument?af().add(e.key):this.queryViewsByTarget[t]?this.queryViewsByTarget[t].view.syncedDocuments:af()},t}(),ey=function(){function t(t){this.uid=t}return t.prototype.isAuthenticated=function(){return null!=this.uid},t.prototype.toKey=function(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"},t.prototype.isEqual=function(t){return t.uid===this.uid},t.UNAUTHENTICATED=new t(null),t.GOOGLE_CREDENTIALS=new t("google-credentials-uid"),t.FIRST_PARTY=new t("first-party-uid"),t}(),ny="SharedClientState",ry="firestore_clients",iy="firestore_mutations",oy="firestore_targets",sy="firestore_online_state",ay="firestore_sequence_number",uy=function(){function t(t,e,n,r){this.user=t,this.batchId=e,this.state=n,this.error=r,Jc(void 0!==r==("rejected"===n),"MutationMetadata must contain an error iff state is 'rejected'")}return t.fromWebStorageEntry=function(e,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),s=void 0;return o&&i.error&&(o="string"==typeof i.error.message&&"string"==typeof i.error.code)&&(s=new eh(i.error.code,i.error.message)),o?new t(e,n,i.state,s):(zc(ny,"Failed to parse mutation state for ID '"+n+"': "+r),null)},t.prototype.toWebStorageJSON=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)},t}(),cy=function(){function t(t,e,n){this.targetId=t,this.state=e,this.error=n,Jc(void 0!==n==("rejected"===e),"QueryTargetMetadata must contain an error iff state is 'rejected'")}return t.fromWebStorageEntry=function(e,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 eh(r.error.code,r.error.message)),i?new t(e,r.state,o):(zc(ny,"Failed to parse target state for ID '"+e+"': "+n),null)},t.prototype.toWebStorageJSON=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)},t}(),hy=function(){function t(t,e){this.clientId=t,this.activeTargetIds=e}return t.fromWebStorageEntry=function(e,n){for(var r=JSON.parse(n),i="object"==typeof r&&r.activeTargetIds instanceof Array,o=cf(),s=0;i&&s<r.activeTargetIds.length;++s)i=bl(r.activeTargetIds[s]),o=o.add(r.activeTargetIds[s]);return i?new t(e,o):(zc(ny,"Failed to parse client data for instance '"+e+"': "+n),null)},t}(),ly=function(){function t(t,e){this.clientId=t,this.onlineState=e}return t.fromWebStorageEntry=function(e){var n=JSON.parse(e);return"object"==typeof n&&void 0!==Pd[n.onlineState]&&"string"==typeof n.clientId?new t(n.clientId,Pd[n.onlineState]):(zc(ny,"Failed to parse online state: "+e),null)},t}(),fy=function(){function t(){this.activeTargetIds=cf()}return t.prototype.addQueryTarget=function(t){Jc(!this.activeTargetIds.has(t),"Target with ID '"+t+"' already active."),this.activeTargetIds=this.activeTargetIds.add(t)},t.prototype.removeQueryTarget=function(t){this.activeTargetIds=this.activeTargetIds.delete(t)},t.prototype.toWebStorageJSON=function(){var t={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(t)},t}(),py=function(){function t(e,n,r,i,o){if(this.queue=e,this.platform=n,this.persistenceKey=r,this.localClientId=i,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.activeClients={},this.storageListener=this.handleWebStorageEvent.bind(this),this.started=!1,this.earlyEvents=[],!t.isAvailable(this.platform))throw new eh(th.UNIMPLEMENTED,"LocalStorage is not available on this platform.");var s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.platform.window.localStorage,this.currentUser=o,this.localClientStorageKey=this.toWebStorageClientStateKey(this.localClientId),this.sequenceNumberKey=ay+"_"+r,this.activeClients[this.localClientId]=new fy,this.clientStateKeyRe=new RegExp("^"+ry+"_"+s+"_([^_]*)$"),this.mutationBatchKeyRe=new RegExp("^"+iy+"_"+s+"_(\\d+)(?:_(.*))?$"),this.queryTargetKeyRe=new RegExp("^"+oy+"_"+s+"_(\\d+)$"),this.onlineStateKey=sy+"_"+r,this.platform.window.addEventListener("storage",this.storageListener)}return t.isAvailable=function(t){return!(!t.window||null==t.window.localStorage)},t.prototype.start=function(){return $e(this,void 0,void 0,function(){var t,e,n,r,i,o,s,a,u,c,h,l=this;return Ze(this,function(f){switch(f.label){case 0:return Jc(!this.started,"WebStorageSharedClientState already started"),Jc(null!==this.syncEngine,"syncEngine property must be set before calling start()"),Jc(null!==this.onlineStateHandler,"onlineStateHandler property must be set before calling start()"),[4,this.syncEngine.getActiveClients()];case 1:for(t=f.sent(),e=0,n=t;e<n.length;e++)(r=n[e])!==this.localClientId&&(i=this.getItem(this.toWebStorageClientStateKey(r)))&&(o=hy.fromWebStorageEntry(r,i))&&(this.activeClients[o.clientId]=o);for(this.persistClientState(),(s=this.storage.getItem(this.onlineStateKey))&&(a=this.fromWebStorageOnlineState(s))&&this.handleOnlineStateEvent(a),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]}})})},t.prototype.writeSequenceNumber=function(t){this.setItem(this.sequenceNumberKey,JSON.stringify(t))},t.prototype.getAllActiveQueryTargets=function(){var t=cf();return sh(this.activeClients,function(e,n){t=t.unionWith(n.activeTargetIds)}),t},t.prototype.isActiveQueryTarget=function(t){for(var e in this.activeClients)if(this.activeClients.hasOwnProperty(e)&&this.activeClients[e].activeTargetIds.has(t))return!0;return!1},t.prototype.addPendingMutation=function(t){this.persistMutationState(t,"pending")},t.prototype.updateMutationState=function(t,e,n){this.persistMutationState(t,e,n),this.removeMutationState(t)},t.prototype.addLocalQueryTarget=function(t){var e="not-current";if(this.isActiveQueryTarget(t)){var n=this.storage.getItem(this.toWebStorageQueryTargetMetadataKey(t));if(n){var r=cy.fromWebStorageEntry(t,n);r&&(e=r.state)}}return this.localClientState.addQueryTarget(t),this.persistClientState(),e},t.prototype.removeLocalQueryTarget=function(t){this.localClientState.removeQueryTarget(t),this.persistClientState()},t.prototype.isLocalQueryTarget=function(t){return this.localClientState.activeTargetIds.has(t)},t.prototype.clearQueryState=function(t){this.removeItem(this.toWebStorageQueryTargetMetadataKey(t))},t.prototype.updateQueryState=function(t,e,n){this.persistQueryTargetState(t,e,n)},t.prototype.handleUserChange=function(t,e,n){var r=this;e.forEach(function(t){r.removeMutationState(t)}),this.currentUser=t,n.forEach(function(t){r.addPendingMutation(t)})},t.prototype.setOnlineState=function(t){this.persistOnlineState(t)},t.prototype.shutdown=function(){this.started&&(this.platform.window.removeEventListener("storage",this.storageListener),this.removeItem(this.localClientStorageKey),this.started=!1)},t.prototype.getItem=function(t){var e=this.storage.getItem(t);return Gc(ny,"READ",t,e),e},t.prototype.setItem=function(t,e){Gc(ny,"SET",t,e),this.storage.setItem(t,e)},t.prototype.removeItem=function(t){Gc(ny,"REMOVE",t),this.storage.removeItem(t)},t.prototype.handleWebStorageEvent=function(t){var e=this;if(t.storageArea===this.storage){if(Gc(ny,"EVENT",t.key,t.newValue),t.key===this.localClientStorageKey)return void zc("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.queue.enqueueAndForget(function(){return $e(e,void 0,void 0,function(){var e,n,r,i,o,s;return Ze(this,function(a){if(!this.started)return this.earlyEvents.push(t),[2];if(null===t.key)return[2];if(this.clientStateKeyRe.test(t.key)){if(null==t.newValue)return n=this.fromWebStorageClientStateKey(t.key),[2,this.handleClientStateEvent(n,null)];if(e=this.fromWebStorageClientState(t.key,t.newValue))return[2,this.handleClientStateEvent(e.clientId,e)]}else if(this.mutationBatchKeyRe.test(t.key)){if(null!==t.newValue&&(r=this.fromWebStorageMutationMetadata(t.key,t.newValue)))return[2,this.handleMutationBatchEvent(r)]}else if(this.queryTargetKeyRe.test(t.key)){if(null!==t.newValue&&(i=this.fromWebStorageQueryTargetMetadata(t.key,t.newValue)))return[2,this.handleQueryTargetEvent(i)]}else if(t.key===this.onlineStateKey){if(null!==t.newValue&&(o=this.fromWebStorageOnlineState(t.newValue)))return[2,this.handleOnlineStateEvent(o)]}else t.key===this.sequenceNumberKey&&(Jc(!!this.sequenceNumberHandler,"Missing sequenceNumberHandler"),(s=function(t){var e=Qf.INVALID;if(null!=t)try{var n=JSON.parse(t);Jc("number"==typeof n,"Found non-numeric sequence number"),e=n}catch(t){zc(ny,"Failed to read sequence number from WebStorage",t)}return e}(t.newValue))!==Qf.INVALID&&this.sequenceNumberHandler(s));return[2]})})})}},Object.defineProperty(t.prototype,"localClientState",{get:function(){return this.activeClients[this.localClientId]},enumerable:!0,configurable:!0}),t.prototype.persistClientState=function(){this.setItem(this.localClientStorageKey,this.localClientState.toWebStorageJSON())},t.prototype.persistMutationState=function(t,e,n){var r=new uy(this.currentUser,t,e,n),i=this.toWebStorageMutationBatchKey(t);this.setItem(i,r.toWebStorageJSON())},t.prototype.removeMutationState=function(t){var e=this.toWebStorageMutationBatchKey(t);this.removeItem(e)},t.prototype.persistOnlineState=function(t){var e={clientId:this.localClientId,onlineState:Pd[t]};this.storage.setItem(this.onlineStateKey,JSON.stringify(e))},t.prototype.persistQueryTargetState=function(t,e,n){var r=this.toWebStorageQueryTargetMetadataKey(t),i=new cy(t,e,n);this.setItem(r,i.toWebStorageJSON())},t.prototype.toWebStorageClientStateKey=function(t){return Jc(-1===t.indexOf("_"),"Client key cannot contain '_', but was '"+t+"'"),ry+"_"+this.persistenceKey+"_"+t},t.prototype.toWebStorageQueryTargetMetadataKey=function(t){return oy+"_"+this.persistenceKey+"_"+t},t.prototype.toWebStorageMutationBatchKey=function(t){var e=iy+"_"+this.persistenceKey+"_"+t;return this.currentUser.isAuthenticated()&&(e+="_"+this.currentUser.uid),e},t.prototype.fromWebStorageClientStateKey=function(t){var e=this.clientStateKeyRe.exec(t);return e?e[1]:null},t.prototype.fromWebStorageClientState=function(t,e){var n=this.fromWebStorageClientStateKey(t);return Jc(null!==n,"Cannot parse client state key '"+t+"'"),hy.fromWebStorageEntry(n,e)},t.prototype.fromWebStorageMutationMetadata=function(t,e){var n=this.mutationBatchKeyRe.exec(t);Jc(null!==n,"Cannot parse mutation batch key '"+t+"'");var r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return uy.fromWebStorageEntry(new ey(i),r,e)},t.prototype.fromWebStorageQueryTargetMetadata=function(t,e){var n=this.queryTargetKeyRe.exec(t);Jc(null!==n,"Cannot parse query target key '"+t+"'");var r=Number(n[1]);return cy.fromWebStorageEntry(r,e)},t.prototype.fromWebStorageOnlineState=function(t){return ly.fromWebStorageEntry(t)},t.prototype.handleMutationBatchEvent=function(t){return $e(this,void 0,void 0,function(){return Ze(this,function(e){return t.user.uid!==this.currentUser.uid?(Gc(ny,"Ignoring mutation for non-active user "+t.user.uid),[2]):[2,this.syncEngine.applyBatchState(t.batchId,t.state,t.error)]})})},t.prototype.handleQueryTargetEvent=function(t){return this.syncEngine.applyTargetState(t.targetId,t.state,t.error)},t.prototype.handleClientStateEvent=function(t,e){var n=this,r=this.getAllActiveQueryTargets();e?this.activeClients[t]=e:delete this.activeClients[t];var i=this.getAllActiveQueryTargets(),o=[],s=[];return i.forEach(function(t){return $e(n,void 0,void 0,function(){return Ze(this,function(e){return r.has(t)||o.push(t),[2]})})}),r.forEach(function(t){return $e(n,void 0,void 0,function(){return Ze(this,function(e){return i.has(t)||s.push(t),[2]})})}),this.syncEngine.applyActiveTargetsChange(o,s)},t.prototype.handleOnlineStateEvent=function(t){this.activeClients[t.clientId]&&this.onlineStateHandler(t.onlineState)},t}();var dy=function(){function t(){this.localState=new fy,this.queryState={},this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null}return t.prototype.addPendingMutation=function(t){},t.prototype.updateMutationState=function(t,e,n){},t.prototype.addLocalQueryTarget=function(t){return this.localState.addQueryTarget(t),this.queryState[t]||"not-current"},t.prototype.updateQueryState=function(t,e,n){this.queryState[t]=e},t.prototype.removeLocalQueryTarget=function(t){this.localState.removeQueryTarget(t)},t.prototype.isLocalQueryTarget=function(t){return this.localState.activeTargetIds.has(t)},t.prototype.clearQueryState=function(t){delete this.queryState[t]},t.prototype.getAllActiveQueryTargets=function(){return this.localState.activeTargetIds},t.prototype.isActiveQueryTarget=function(t){return this.localState.activeTargetIds.has(t)},t.prototype.start=function(){return this.localState=new fy,Promise.resolve()},t.prototype.handleUserChange=function(t,e,n){},t.prototype.setOnlineState=function(t){},t.prototype.shutdown=function(){},t.prototype.writeSequenceNumber=function(t){},t}(),yy=function(){function t(t,e){this.cacheSizeBytes=t,this.experimentalTabSynchronization=e}return t.prototype.lruParams=function(){return od.withCacheSize(this.cacheSizeBytes)},t}(),my=function(){return function(){}}(),gy=function(){function t(t,e,n,r){this.platform=t,this.databaseInfo=e,this.credentials=n,this.asyncQueue=r,this.clientId=Ih.newId()}return t.prototype.start=function(t){var e=this,n=new Hf,r=new Hf,i=!1;return this.credentials.setChangeListener(function(o){i?e.asyncQueue.enqueueAndForget(function(){return e.handleCredentialChange(o)}):(i=!0,e.initializePersistence(t,r,o).then(function(t){return e.initializeRest(o,t)}).then(n.resolve,n.reject))}),this.asyncQueue.enqueueAndForget(function(){return n.promise}),r.promise},t.prototype.enableNetwork=function(){var t=this;return this.asyncQueue.enqueue(function(){return t.syncEngine.enableNetwork()})},t.prototype.initializePersistence=function(t,e,n){var r=this;return t instanceof yy?this.startIndexedDbPersistence(n,t).then(function(t){return e.resolve(),t}).catch(function(t){if(e.reject(t),!r.canFallback(t))throw t;return console.warn("Error enabling offline storage. Falling back to storage disabled: "+t),r.startMemoryPersistence()}):(e.resolve(),this.startMemoryPersistence())},t.prototype.canFallback=function(t){return t instanceof eh?t.code===th.FAILED_PRECONDITION||t.code===th.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code)},t.prototype.startIndexedDbPersistence=function(t,e){var n=this,r=pd.buildStoragePrefix(this.databaseInfo),i=new Of(this.databaseInfo.databaseId,{useProto3Json:!0});return Promise.resolve().then(function(){return $e(n,void 0,void 0,function(){var n,o;return Ze(this,function(s){switch(s.label){case 0:if(e.experimentalTabSynchronization&&!py.isAvailable(this.platform))throw new eh(th.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");return o=e.lruParams(),e.experimentalTabSynchronization?(this.sharedClientState=new py(this.asyncQueue,this.platform,r,this.clientId,t),[4,pd.createMultiClientIndexedDbPersistence(r,this.clientId,this.platform,this.asyncQueue,i,o,{sequenceNumberSyncer:this.sharedClientState})]):[3,2];case 1:return n=s.sent(),[3,4];case 2:return this.sharedClientState=new dy,[4,pd.createIndexedDbPersistence(r,this.clientId,this.platform,this.asyncQueue,i,o)];case 3:n=s.sent(),s.label=4;case 4:return this.persistence=n,[2,n.referenceDelegate.garbageCollector]}})})})},t.prototype.startMemoryPersistence=function(){return this.persistence=Dd.createEagerPersistence(this.clientId),this.sharedClientState=new dy,Promise.resolve(null)},t.prototype.initializeRest=function(t,e){var n=this;return Gc("FirestoreClient","Initializing. user=",t.uid),this.platform.loadConnection(this.databaseInfo).then(function(r){return $e(n,void 0,void 0,function(){var n,i,o,s,a=this;return Ze(this,function(u){switch(u.label){case 0:return this.localStore=new Ed(this.persistence,t),e&&(this.lruScheduler=new sd(e,this.asyncQueue,this.localStore),this.lruScheduler.start()),n=this.platform.newSerializer(this.databaseInfo.databaseId),i=new Vd(this.asyncQueue,r,this.credentials,n),o=function(t){return a.syncEngine.applyOnlineStateChange(t,Ld.RemoteStore)},s=function(t){return a.syncEngine.applyOnlineStateChange(t,Ld.SharedClientState)},this.remoteStore=new Kd(this.localStore,i,this.asyncQueue,o),this.syncEngine=new ty(this.localStore,this.remoteStore,this.sharedClientState,t),this.sharedClientState.onlineStateHandler=s,this.remoteStore.syncEngine=this.syncEngine,this.sharedClientState.syncEngine=this.syncEngine,this.eventMgr=new Hd(this.syncEngine),[4,this.sharedClientState.start()];case 1:return u.sent(),[4,this.remoteStore.start()];case 2:return u.sent(),[4,this.persistence.setPrimaryStateListener(function(t){return a.syncEngine.applyPrimaryState(t)})];case 3:return u.sent(),[2]}})})})},t.prototype.handleCredentialChange=function(t){return this.asyncQueue.verifyOperationInProgress(),Gc("FirestoreClient","Credential Changed. Current user: "+t.uid),this.syncEngine.handleCredentialChange(t)},t.prototype.disableNetwork=function(){var t=this;return this.asyncQueue.enqueue(function(){return t.syncEngine.disableNetwork()})},t.prototype.shutdown=function(t){var e=this;return this.asyncQueue.enqueue(function(){return $e(e,void 0,void 0,function(){return Ze(this,function(e){switch(e.label){case 0:return this.lruScheduler&&this.lruScheduler.stop(),[4,this.remoteStore.shutdown()];case 1:return e.sent(),[4,this.sharedClientState.shutdown()];case 2:return e.sent(),[4,this.persistence.shutdown(t&&t.purgePersistenceWithDataLoss)];case 3:return e.sent(),this.credentials.removeChangeListener(),[2]}})})})},t.prototype.listen=function(t,e,n){var r=this,i=new Gd(t,e,n);return this.asyncQueue.enqueueAndForget(function(){return r.eventMgr.listen(i)}),i},t.prototype.unlisten=function(t){var e=this;this.asyncQueue.enqueueAndForget(function(){return e.eventMgr.unlisten(t)})},t.prototype.getDocumentFromLocalCache=function(t){var e=this;return this.asyncQueue.enqueue(function(){return e.localStore.readDocument(t)}).then(function(t){if(t instanceof Qh)return t;if(t instanceof Hh)return null;throw new eh(th.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.)")})},t.prototype.getDocumentsFromLocalCache=function(t){var e=this;return this.asyncQueue.enqueue(function(){return e.localStore.executeQuery(t)}).then(function(e){var n=af(),r=new Jd(t,n),i=r.computeDocChanges(e);return r.applyChanges(i,!1).snapshot})},t.prototype.write=function(t){var e=this,n=new Hf;return this.asyncQueue.enqueueAndForget(function(){return e.syncEngine.write(t,n)}),n.promise},t.prototype.databaseId=function(){return this.databaseInfo.databaseId},t.prototype.transaction=function(t){var e=this;return this.asyncQueue.enqueue(function(){return $e(e,void 0,void 0,function(){return Ze(this,function(t){return[2]})})}).then(function(){return e.syncEngine.runTransaction(t)})},t}(),vy=function(){function t(t){this.observer=t,this.muted=!1}return t.prototype.next=function(t){this.scheduleEvent(this.observer.next,t)},t.prototype.error=function(t){this.scheduleEvent(this.observer.error,t)},t.prototype.mute=function(){this.muted=!0},t.prototype.scheduleEvent=function(t,e){var n=this;this.muted||setTimeout(function(){n.muted||t(e)},0)},t}(),by=function(){function t(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];!function(t,e,n,r){if(!(e instanceof Array)||e.length<r)throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() requires its "+n+" argument to be an array with at least "+Sh(r,"element")+".")}("FieldPath",t,"fieldNames",1);for(var n=0;n<t.length;++n)if(lh("FieldPath","string",n,t[n]),0===t[n].length)throw new eh(th.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Wh(t)}return t.documentId=function(){return t._DOCUMENT_ID},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Eh("isEqual","FieldPath",1,e);return this._internalPath.isEqual(e._internalPath)},t._DOCUMENT_ID=new t(Wh.keyField().canonicalString()),t}(),_y=new RegExp("[~\\*/\\[\\]]");var wy=function(){return function(t,e){this.user=e,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+t}}}(),Ey=function(){function t(){this.changeListener=null}return t.prototype.getToken=function(){return Promise.resolve(null)},t.prototype.invalidateToken=function(){},t.prototype.setChangeListener=function(t){Jc(!this.changeListener,"Can only call setChangeListener() once."),this.changeListener=t,t(ey.UNAUTHENTICATED)},t.prototype.removeChangeListener=function(){Jc(null!==this.changeListener,"removeChangeListener() when no listener registered"),this.changeListener=null},t}(),Ty=function(){function t(t){var e=this;this.app=t,this.tokenListener=null,this.tokenCounter=0,this.changeListener=null,this.forceRefresh=!1,this.tokenListener=function(){e.tokenCounter++,e.currentUser=e.getUser(),e.changeListener&&e.changeListener(e.currentUser)},this.tokenCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return t.prototype.getToken=function(){var t=this;Jc(null!=this.tokenListener,"getToken cannot be called after listener removed.");var e=this.tokenCounter,n=this.forceRefresh;return this.forceRefresh=!1,this.app.INTERNAL.getToken(n).then(function(n){if(t.tokenCounter!==e)throw new eh(th.ABORTED,"getToken aborted due to token change.");return n?(Jc("string"==typeof n.accessToken,"Invalid tokenData returned from getToken():"+n),new wy(n.accessToken,t.currentUser)):null})},t.prototype.invalidateToken=function(){this.forceRefresh=!0},t.prototype.setChangeListener=function(t){Jc(!this.changeListener,"Can only call setChangeListener() once."),this.changeListener=t,this.currentUser&&t(this.currentUser)},t.prototype.removeChangeListener=function(){Jc(null!=this.tokenListener,"removeChangeListener() called twice"),Jc(null!==this.changeListener,"removeChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.changeListener=null},t.prototype.getUser=function(){var t=this.app.INTERNAL.getUid();return Jc(null===t||"string"==typeof t,"Received invalid UID: "+t),new ey(t)},t}(),Sy=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,this.type="FirstParty",this.user=ey.FIRST_PARTY,Jc(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return Object.defineProperty(t.prototype,"authHeaders",{get:function(){return{Authorization:this.gapi.auth.getAuthHeaderValueForFirstParty([]),"X-Goog-AuthUser":this.sessionIndex}},enumerable:!0,configurable:!0}),t}(),Iy=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,Jc(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return t.prototype.getToken=function(){return Promise.resolve(new Sy(this.gapi,this.sessionIndex))},t.prototype.setChangeListener=function(t){t(ey.FIRST_PARTY)},t.prototype.removeChangeListener=function(){},t.prototype.invalidateToken=function(){},t}();function Cy(t){return function(t,e){if("object"!=typeof t||null===t)return!1;for(var n=t,r=0,i=e;r<i.length;r++){var o=i[r];if(o in n&&"function"==typeof n[o])return!0}return!1}(t,["next","error","complete"])}var Ny,Dy=function(){function t(t){this._methodName=t}return t.delete=function(){return Ay.instance},t.serverTimestamp=function(){return ky.instance},t.arrayUnion=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return ch("FieldValue.arrayUnion",arguments,1),new Ry(t)},t.arrayRemove=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return ch("FieldValue.arrayRemove",arguments,1),new Oy(t)},t.prototype.isEqual=function(t){return this===t},t}(),Ay=function(t){function e(){return t.call(this,"FieldValue.delete")||this}return Xe(e,t),e.instance=new e,e}(Dy),ky=function(t){function e(){return t.call(this,"FieldValue.serverTimestamp")||this}return Xe(e,t),e.instance=new e,e}(Dy),Ry=function(t){function e(e){var n=t.call(this,"FieldValue.arrayUnion")||this;return n._elements=e,n}return Xe(e,t),e}(Dy),Oy=function(t){function e(e){var n=t.call(this,"FieldValue.arrayRemove")||this;return n._elements=e,n}return Xe(e,t),e}(Dy),Py=nh(Dy,"Use FieldValue.<field>() instead."),Ly=/^__.*__$/,My=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new Wl(t,this.data,this.fieldMask,e)):n.push(new Vl(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new jl(t,this.fieldTransforms)),n},t}(),xy=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[new Wl(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new jl(t,this.fieldTransforms)),n},t}();function Fy(t){switch(t){case Ny.Set:case Ny.MergeSet:case Ny.Update:return!0;case Ny.Argument:return!1;default:throw Xc("Unexpected case for UserDataSource: "+t)}}!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.Argument=3]="Argument"}(Ny||(Ny={}));var Uy=function(){function t(t,e,n,r,i,o){this.dataSource=t,this.methodName=e,this.path=n,this.arrayElement=r,void 0===i&&this.validatePath(),this.arrayElement=void 0!==r&&r,this.fieldTransforms=i||[],this.fieldMask=o||[]}return t.prototype.childContextForField=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(e),r},t.prototype.childContextForFieldPath=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},t.prototype.childContextForArray=function(e){return new t(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path.toString()+")";return new eh(th.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.contains=function(t){return void 0!==this.fieldMask.find(function(e){return t.isPrefixOf(e)})||void 0!==this.fieldTransforms.find(function(e){return t.isPrefixOf(e.field)})},t.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t<this.path.length;t++)this.validatePathSegment(this.path.get(t))},t.prototype.validatePathSegment=function(t){if(Fy(this.dataSource)&&Ly.test(t))throw this.createError("Document fields cannot begin and end with __")},t}(),qy=function(){return function(t,e){this.databaseId=t,this.key=e}}(),By=function(){function t(t){this.preConverter=t}return t.prototype.parseSetData=function(t,e){var n=new Uy(Ny.Set,t,Wh.EMPTY_PATH);Wy("Data must be an object, but it was:",n,e);var r=this.parseData(e,n);return new My(r,null,n.fieldTransforms)},t.prototype.parseMergeData=function(t,e,n){var r=new Uy(Ny.MergeSet,t,Wh.EMPTY_PATH);Wy("Data must be an object, but it was:",r,e);var i,o,s=this.parseData(e,r);if(n){for(var a=[],u=0,c=n;u<c.length;u++){var h=c[u],l=void 0;if(h instanceof by)l=h._internalPath;else{if("string"!=typeof h)throw Xc("Expected stringOrFieldPath to be a string or a FieldPath");l=Ky(t,h)}if(!r.contains(l))throw new eh(th.INVALID_ARGUMENT,"Field '"+l+"' is specified in your field mask but missing from your input data.");a.push(l)}i=xl.fromArray(a),o=r.fieldTransforms.filter(function(t){return i.covers(t.field)})}else i=xl.fromArray(r.fieldMask),o=r.fieldTransforms;return new My(s,i,o)},t.prototype.parseUpdateData=function(t,e){var n=this,r=new Uy(Ny.Update,t,Wh.EMPTY_PATH);Wy("Data must be an object, but it was:",r,e);var i=[],o=fl.EMPTY;sh(e,function(e,s){var a=Ky(t,e),u=r.childContextForFieldPath(a);if((s=n.runPreConverter(s,u))instanceof Ay)i.push(a);else{var c=n.parseData(s,u);null!=c&&(i.push(a),o=o.set(a,c))}});var s=xl.fromArray(i);return new xy(o,s,r.fieldTransforms)},t.prototype.parseUpdateVarargs=function(t,e,n,r){var i=new Uy(Ny.Update,t,Wh.EMPTY_PATH),o=[jy(t,e)],s=[n];if(r.length%2!=0)throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() needs to be called with an even number of arguments that alternate between field names and values.");for(var a=0;a<r.length;a+=2)o.push(jy(t,r[a])),s.push(r[a+1]);var u=[],c=fl.EMPTY;for(a=0;a<o.length;++a){var h=o[a],l=i.childContextForFieldPath(h),f=this.runPreConverter(s[a],l);if(f instanceof Ay)u.push(h);else{var p=this.parseData(f,l);null!=p&&(u.push(h),c=c.set(h,p))}}var d=xl.fromArray(u);return new xy(c,d,i.fieldTransforms)},t.prototype.parseQueryValue=function(t,e){var n=new Uy(Ny.Argument,t,Wh.EMPTY_PATH),r=this.parseData(e,n);return Jc(null!=r,"Parsed data should not be null."),Jc(0===n.fieldTransforms.length,"Field transforms should have been disallowed."),r},t.prototype.runPreConverter=function(t,e){try{return this.preConverter(t)}catch(t){var n=Qy(t);throw e.createError(n)}},t.prototype.parseData=function(t,e){if(Vy(t=this.runPreConverter(t,e)))return Wy("Unsupported field value:",e,t),this.parseObject(t,e);if(t instanceof Dy)return this.parseSentinelFieldValue(t,e),null;if(e.path&&e.fieldMask.push(e.path),t instanceof Array){if(e.arrayElement)throw e.createError("Nested arrays are not supported");return this.parseArray(t,e)}return this.parseScalarValue(t,e)},t.prototype.parseObject=function(t,e){var n=this,r=new zh(Ch);return ah(t)?e.path&&e.path.length>0&&e.fieldMask.push(e.path):sh(t,function(t,i){var o=n.parseData(i,e.childContextForField(t));null!=o&&(r=r.insert(t,o))}),new fl(r)},t.prototype.parseArray=function(t,e){for(var n=[],r=0,i=0,o=t;i<o.length;i++){var s=o[i],a=this.parseData(s,e.childContextForArray(r));null==a&&(a=tl.INSTANCE),n.push(a),r++}return new pl(n)},t.prototype.parseSentinelFieldValue=function(t,e){if(!Fy(e.dataSource))throw e.createError(t._methodName+"() can only be used with update() and set()");if(null===e.path)throw e.createError(t._methodName+"() is not currently supported inside arrays");if(t instanceof Ay){if(e.dataSource!==Ny.MergeSet)throw e.dataSource===Ny.Update?(Jc(e.path.length>0,"FieldValue.delete() at the top level should have already been handled."),e.createError("FieldValue.delete() can only appear at the top level of your update data")):e.createError("FieldValue.delete() cannot be used with set() unless you pass {merge:true}");e.fieldMask.push(e.path)}else if(t instanceof ky)e.fieldTransforms.push(new Fl(e.path,Ql.instance));else if(t instanceof Ry){var n=this.parseArrayTransformElements(t._methodName,t._elements),r=new Hl(n);e.fieldTransforms.push(new Fl(e.path,r))}else if(t instanceof Oy){n=this.parseArrayTransformElements(t._methodName,t._elements);var i=new Gl(n);e.fieldTransforms.push(new Fl(e.path,i))}else Xc("Unknown FieldValue type: "+t)},t.prototype.parseScalarValue=function(t,e){if(null===t)return tl.INSTANCE;if("number"==typeof t)return bl(t)?new il(t):new ol(t);if("boolean"==typeof t)return el.of(t);if("string"==typeof t)return new sl(t);if(t instanceof Date)return new al(Mh.fromDate(t));if(t instanceof Mh)return new al(new Mh(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)));if(t instanceof Lh)return new ll(t);if(t instanceof Oh)return new cl(t);if(t instanceof qy)return new hl(t.databaseId,t.key);throw e.createError("Unsupported field value: "+bh(t))},t.prototype.parseArrayTransformElements=function(t,e){var n=this;return e.map(function(e,r){var i=new Uy(Ny.Argument,t,Wh.EMPTY_PATH);return n.parseData(e,i.childContextForArray(r))})},t}();function Vy(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof Mh||t instanceof Lh||t instanceof Oh||t instanceof qy||t instanceof Dy)}function Wy(t,e,n){if(!Vy(n)||!vh(n)){var r=bh(n);throw"an object"===r?e.createError(t+" a custom object"):e.createError(t+" "+r)}}function jy(t,e){if(e instanceof by)return e._internalPath;if("string"==typeof e)return Ky(t,e);throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function Ky(t,e){try{return function(t){if(t.search(_y)>=0)throw new eh(th.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(by.bind.apply(by,[void 0].concat(t.split("."))))}catch(e){throw new eh(th.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}(e)._internalPath}catch(e){var n=Qy(e);throw new eh(th.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. "+n)}}function Qy(t){return t instanceof Error?t.message:t.toString()}var Hy="firestore.googleapis.com",Gy=!0,zy=!1,Yy=od.COLLECTION_DISABLED,Xy=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new eh(th.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Hy,this.ssl=Gy}else ph("settings","non-empty string","host",t.host),this.host=t.host,dh("settings","boolean","ssl",t.ssl),this.ssl=ih(t.ssl,Gy);if(wh("settings",t,["host","ssl","credentials","timestampsInSnapshots","cacheSizeBytes"]),dh("settings","object","credentials",t.credentials),this.credentials=t.credentials,dh("settings","boolean","timestampsInSnapshots",t.timestampsInSnapshots),this.timestampsInSnapshots=ih(t.timestampsInSnapshots,zy),dh("settings","number","cacheSizeBytes",t.cacheSizeBytes),void 0===t.cacheSizeBytes)this.cacheSizeBytes=od.DEFAULT_CACHE_SIZE_BYTES;else{if(t.cacheSizeBytes!==Yy&&t.cacheSizeBytes<od.MINIMUM_CACHE_SIZE_BYTES)throw new eh(th.INVALID_ARGUMENT,"cacheSizeBytes must be at least "+od.MINIMUM_CACHE_SIZE_BYTES);this.cacheSizeBytes=t.cacheSizeBytes}}return t.prototype.isEqual=function(t){return this.host===t.host&&this.ssl===t.ssl&&this.timestampsInSnapshots===t.timestampsInSnapshots&&this.credentials===t.credentials&&this.cacheSizeBytes===t.cacheSizeBytes},t}(),Jy=function(){return function(){}}(),$y=function(){function t(e){var n=this;this._queue=new zf,this.INTERNAL={delete:function(t){return $e(n,void 0,void 0,function(){return Ze(this,function(e){return this._firestoreClient?[2,this._firestoreClient.shutdown(t)]:[2]})})}};var r=new Jy;if("object"==typeof e.options){var i=e;r.firebaseApp=i,r.databaseId=t.databaseIdFromApp(i),r.persistenceKey=r.firebaseApp.name,r.credentials=new Ty(i)}else{var o=e;if(!o.projectId)throw new eh(th.INVALID_ARGUMENT,"Must provide projectId");r.databaseId=new Uh(o.projectId,o.database),r.persistenceKey="[DEFAULT]",r.credentials=new Ey}r.settings=new Xy({}),this._config=r,this._databaseId=r.databaseId}return t.prototype.settings=function(t){if(uh("Firestore.settings",arguments,1),lh("Firestore.settings","object",1,t),rh(t,"persistence"))throw new eh(th.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var e=new Xy(t);if(this._firestoreClient&&!this._config.settings.isEqual(e))throw new eh(th.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=e,void 0!==e.credentials&&(this._config.credentials=function(t){if(!t)return new Ey;switch(t.type){case"gapi":return new Iy(t.client,t.sessionIndex||"0");case"provider":return t.client;default:throw new eh(th.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}(e.credentials))},t.prototype.enableNetwork=function(){return this.ensureClientConfigured(),this._firestoreClient.enableNetwork()},t.prototype.disableNetwork=function(){return this.ensureClientConfigured(),this._firestoreClient.disableNetwork()},t.prototype.enablePersistence=function(t){if(this._firestoreClient)throw new eh(th.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 yy(this._config.settings.cacheSizeBytes,void 0!==t&&ih(t.experimentalTabSynchronization,!1)))},t.prototype.ensureClientConfigured=function(){return this._firestoreClient||this.configureClient(new my),this._firestoreClient},t.prototype.configureClient=function(t){var e=this;Jc(!!this._config.settings.host,"FirestoreSettings.host cannot be falsey"),this._config.settings.timestampsInSnapshots||zc("\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."),Jc(!this._firestoreClient,"configureClient() called multiple times");var n=new xh(this._config.databaseId,this._config.persistenceKey,this._config.settings.host,this._config.settings.ssl);return this._dataConverter=new By(function(t){if(t instanceof em){var n=e._config.databaseId,r=t.firestore._config.databaseId;if(!r.isEqual(n))throw new eh(th.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new qy(e._config.databaseId,t._key)}return t}),this._firestoreClient=new gy($c.getPlatform(),n,this._config.credentials,this._queue),this._firestoreClient.start(t)},t.databaseIdFromApp=function(t){var e=t.options;if(!rh(e,"projectId"))throw new eh(th.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');var n=e.projectId;if(!n||"string"!=typeof n)throw new eh(th.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new Uh(n)},Object.defineProperty(t.prototype,"app",{get:function(){if(!this._config.firebaseApp)throw new eh(th.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._config.firebaseApp},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(uh("Firestore.collection",arguments,1),lh("Firestore.collection","non-empty string",1,t),!t)throw new eh(th.INVALID_ARGUMENT,"Must provide a non-empty collection path to collection()");return this.ensureClientConfigured(),new am(Bh.fromString(t),this)},t.prototype.doc=function(t){if(uh("Firestore.doc",arguments,1),lh("Firestore.doc","non-empty string",1,t),!t)throw new eh(th.INVALID_ARGUMENT,"Must provide a non-empty document path to doc()");return this.ensureClientConfigured(),em.forPath(Bh.fromString(t),this)},t.prototype.runTransaction=function(t){var e=this;return uh("Firestore.runTransaction",arguments,1),lh("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction(function(n){return t(new Zy(e,n))})},t.prototype.batch=function(){return this.ensureClientConfigured(),new tm(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(Qc()){case Mc.DEBUG:return"debug";case Mc.ERROR:return"error";case Mc.SILENT:return"silent";default:return Xc("Unknown log level: "+Qc())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(uh("Firestore.setLogLevel",arguments,1),lh("Firestore.setLogLevel","non-empty string",1,t),t){case"debug":Hc(Mc.DEBUG);break;case"error":Hc(Mc.ERROR);break;case"silent":Hc(Mc.SILENT);break;default:throw new eh(th.INVALID_ARGUMENT,"Invalid log level: "+t)}},t.prototype._areTimestampsInSnapshotsEnabled=function(){return this._config.settings.timestampsInSnapshots},t}(),Zy=function(){function t(t,e){this._firestore=t,this._transaction=e}return t.prototype.get=function(t){var e=this;uh("Transaction.get",arguments,1);var n=lm("Transaction.get",t,this._firestore);return this._transaction.lookup([n._key]).then(function(t){if(!t||1!==t.length)return Xc("Mismatch in docs returned from document lookup.");var r=t[0];if(r instanceof Hh)return new rm(e._firestore,n._key,null,!1,!1);if(r instanceof Qh)return new rm(e._firestore,n._key,r,!1,!1);throw Xc("BatchGetDocumentsRequest returned unexpected document type: "+r.constructor.name)})},t.prototype.set=function(t,e,n){hh("Transaction.set",arguments,2,3);var r=lm("Transaction.set",t,this._firestore),i=(n=um("Transaction.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("Transaction.set",e,n.mergeFields):this._firestore._dataConverter.parseSetData("Transaction.set",e);return this._transaction.set(r._key,i),this},t.prototype.update=function(t,e,n){for(var r,i,o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return"string"==typeof e||e instanceof by?(ch("Transaction.update",arguments,3),r=lm("Transaction.update",t,this._firestore),i=this._firestore._dataConverter.parseUpdateVarargs("Transaction.update",e,n,o)):(uh("Transaction.update",arguments,2),r=lm("Transaction.update",t,this._firestore),i=this._firestore._dataConverter.parseUpdateData("Transaction.update",e)),this._transaction.update(r._key,i),this},t.prototype.delete=function(t){uh("Transaction.delete",arguments,1);var e=lm("Transaction.delete",t,this._firestore);return this._transaction.delete(e._key),this},t}(),tm=function(){function t(t){this._firestore=t,this._mutations=[],this._committed=!1}return t.prototype.set=function(t,e,n){hh("WriteBatch.set",arguments,2,3),this.verifyNotCommitted();var r=lm("WriteBatch.set",t,this._firestore),i=(n=um("WriteBatch.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("WriteBatch.set",e,n.mergeFields):this._firestore._dataConverter.parseSetData("WriteBatch.set",e);return this._mutations=this._mutations.concat(i.toMutations(r._key,ql.NONE)),this},t.prototype.update=function(t,e,n){for(var r,i,o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return this.verifyNotCommitted(),"string"==typeof e||e instanceof by?(ch("WriteBatch.update",arguments,3),r=lm("WriteBatch.update",t,this._firestore),i=this._firestore._dataConverter.parseUpdateVarargs("WriteBatch.update",e,n,o)):(uh("WriteBatch.update",arguments,2),r=lm("WriteBatch.update",t,this._firestore),i=this._firestore._dataConverter.parseUpdateData("WriteBatch.update",e)),this._mutations=this._mutations.concat(i.toMutations(r._key,ql.exists(!0))),this},t.prototype.delete=function(t){uh("WriteBatch.delete",arguments,1),this.verifyNotCommitted();var e=lm("WriteBatch.delete",t,this._firestore);return this._mutations=this._mutations.concat(new Kl(e._key,ql.NONE)),this},t.prototype.commit=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){return this.verifyNotCommitted(),this._committed=!0,this._mutations.length>0?[2,this._firestore.ensureClientConfigured().write(this._mutations)]:[2]})})},t.prototype.verifyNotCommitted=function(){if(this._committed)throw new eh(th.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),em=function(){function t(t,e){this._key=t,this.firestore=e,this._firestoreClient=this.firestore.ensureClientConfigured()}return t.forPath=function(e,n){if(e.length%2!=0)throw new eh(th.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new t(new jh(e),n)},Object.defineProperty(t.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new am(this._key.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this._key.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(uh("DocumentReference.collection",arguments,1),lh("DocumentReference.collection","non-empty string",1,t),!t)throw new eh(th.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=Bh.fromString(t);return new am(this._key.path.child(e),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Eh("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this._key.isEqual(e._key)},t.prototype.set=function(t,e){hh("DocumentReference.set",arguments,1,2);var n=(e=um("DocumentReference.set",e)).merge||e.mergeFields?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t,e.mergeFields):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this._firestoreClient.write(n.toMutations(this._key,ql.NONE))},t.prototype.update=function(t,e){for(var n,r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];return"string"==typeof t||t instanceof by?(ch("DocumentReference.update",arguments,2),n=this.firestore._dataConverter.parseUpdateVarargs("DocumentReference.update",t,e,r)):(uh("DocumentReference.update",arguments,1),n=this.firestore._dataConverter.parseUpdateData("DocumentReference.update",t)),this._firestoreClient.write(n.toMutations(this._key,ql.exists(!0)))},t.prototype.delete=function(){return uh("DocumentReference.delete",arguments,0),this._firestoreClient.write([new Kl(this._key,ql.NONE)])},t.prototype.onSnapshot=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];hh("DocumentReference.onSnapshot",arguments,1,4);var n,r={includeMetadataChanges:!1},i=0;"object"!=typeof t[i]||Cy(t[i])||(wh("DocumentReference.onSnapshot",r=t[i],["includeMetadataChanges"]),dh("DocumentReference.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++);var o={includeMetadataChanges:r.includeMetadataChanges};return Cy(t[i])?n=t[i]:(lh("DocumentReference.onSnapshot","function",i,t[i]),fh("DocumentReference.onSnapshot","function",i+1,t[i+1]),fh("DocumentReference.onSnapshot","function",i+2,t[i+2]),n={next:t[i],error:t[i+1],complete:t[i+2]}),this.onSnapshotInternal(o,n)},t.prototype.onSnapshotInternal=function(t,e){var n=this,r=function(t){console.error("Uncaught Error in onSnapshot:",t)};e.error&&(r=e.error.bind(e));var i=new vy({next:function(t){if(e.next){Jc(t.docs.size<=1,"Too many documents returned on a document query");var r=t.docs.get(n._key);e.next(new rm(n.firestore,n._key,r,t.fromCache,t.hasPendingWrites))}},error:r}),o=this._firestoreClient.listen(wl.atPath(this._key.path),i,t);return function(){i.mute(),n._firestoreClient.unlisten(o)}},t.prototype.get=function(t){var e=this;return hh("DocumentReference.get",arguments,0,1),hm("DocumentReference.get",t),new Promise(function(n,r){t&&"cache"===t.source?e.firestore.ensureClientConfigured().getDocumentFromLocalCache(e._key).then(function(t){n(new rm(e.firestore,e._key,t,!0,t instanceof Qh&&t.hasLocalMutations))},r):e.getViaSnapshotListener(n,r,t)})},t.prototype.getViaSnapshotListener=function(t,e,n){var r=this.onSnapshotInternal({includeMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(i){r(),!i.exists&&i.metadata.fromCache?e(new eh(th.UNAVAILABLE,"Failed to get document because the client is offline.")):i.exists&&i.metadata.fromCache&&n&&"server"===n.source?e(new eh(th.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.)')):t(i)},error:e})},t}(),nm=function(){function t(t,e){this.hasPendingWrites=t,this.fromCache=e}return t.prototype.isEqual=function(t){return this.hasPendingWrites===t.hasPendingWrites&&this.fromCache===t.fromCache},t}(),rm=function(){function t(t,e,n,r,i){this._firestore=t,this._key=e,this._document=n,this._fromCache=r,this._hasPendingWrites=i}return t.prototype.data=function(t){return hh("DocumentSnapshot.data",arguments,0,1),t=cm("DocumentSnapshot.data",t),this._document?this.convertObject(this._document.data,$h.fromSnapshotOptions(t,this._firestore._areTimestampsInSnapshotsEnabled())):void 0},t.prototype.get=function(t,e){if(hh("DocumentSnapshot.get",arguments,1,2),e=cm("DocumentSnapshot.get",e),this._document){var n=this._document.data.field(jy("DocumentSnapshot.get",t));if(void 0!==n)return this.convertValue(n,$h.fromSnapshotOptions(e,this._firestore._areTimestampsInSnapshotsEnabled()))}},Object.defineProperty(t.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ref",{get:function(){return new em(this._key,this._firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"exists",{get:function(){return null!==this._document},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"metadata",{get:function(){return new nm(this._hasPendingWrites,this._fromCache)},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){if(!(e instanceof t))throw Eh("isEqual","DocumentSnapshot",1,e);return this._firestore===e._firestore&&this._fromCache===e._fromCache&&this._key.isEqual(e._key)&&(null===this._document?null===e._document:this._document.isEqual(e._document))},t.prototype.convertObject=function(t,e){var n=this,r={};return t.forEach(function(t,i){r[t]=n.convertValue(i,e)}),r},t.prototype.convertValue=function(t,e){if(t instanceof fl)return this.convertObject(t,e);if(t instanceof pl)return this.convertArray(t,e);if(t instanceof hl){var n=t.value(e),r=this._firestore.ensureClientConfigured().databaseId();return t.databaseId.isEqual(r)||zc("Document "+this._key.path+" contains a document reference within a different database ("+t.databaseId.projectId+"/"+t.databaseId.database+") which is not supported. It will be treated as a reference in the current database ("+r.projectId+"/"+r.database+") instead."),new em(n,this._firestore)}return t.value(e)},t.prototype.convertArray=function(t,e){var n=this;return t.internalValue.map(function(t){return n.convertValue(t,e)})},t}(),im=function(t){function e(e,n,r,i,o){return t.call(this,e,n,r,i,o)||this}return Xe(e,t),e.prototype.data=function(e){var n=t.prototype.data.call(this,e);return Jc("object"==typeof n,"Document in a QueryDocumentSnapshot should exist"),n},e}(rm),om=function(){function t(t,e){this._query=t,this.firestore=e}return t.prototype.where=function(e,n,r){var i;uh("Query.where",arguments,3),lh("Query.where","non-empty string",2,n),_h("Query.where",3,r);var o=jy("Query.where",e),s=Tl.fromString(n);if(o.isKeyField()){if(s===Tl.ARRAY_CONTAINS)throw new eh(th.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 eh(th.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 eh(th.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a valid document ID if the first parameter is FieldPath.documentId(), but it was an empty string.");var a=this._query.path.child(new Bh([r]));Jc(a.length%2==0,"Path should be a document key"),i=new hl(this.firestore._databaseId,new jh(a))}else{if(!(r instanceof em))throw new eh(th.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: "+bh(r)+".");var u=r;i=new hl(this.firestore._databaseId,u._key)}}else i=this.firestore._dataConverter.parseQueryValue("Query.where",r);var c=El.create(o,s,i);return this.validateNewFilter(c),new t(this._query.addFilter(c),this.firestore)},t.prototype.orderBy=function(e,n){var r;if(hh("Query.orderBy",arguments,1,2),fh("Query.orderBy","non-empty string",2,n),void 0===n||"asc"===n)r=Nl.ASCENDING;else{if("desc"!==n)throw new eh(th.INVALID_ARGUMENT,"Function Query.orderBy() has unknown direction '"+n+"', expected 'asc' or 'desc'.");r=Nl.DESCENDING}if(null!==this._query.startAt)throw new eh(th.INVALID_ARGUMENT,"Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");if(null!==this._query.endAt)throw new eh(th.INVALID_ARGUMENT,"Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");var i=jy("Query.orderBy",e),o=new Al(i,r);return this.validateNewOrderBy(o),new t(this._query.addOrderBy(o),this.firestore)},t.prototype.limit=function(e){if(uh("Query.limit",arguments,1),lh("Query.limit","number",1,e),e<=0)throw new eh(th.INVALID_ARGUMENT,"Invalid Query. Query limit ("+e+") is invalid. Limit must be positive.");return new t(this._query.withLimit(e),this.firestore)},t.prototype.startAt=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];ch("Query.startAt",arguments,1);var i=this.boundFromDocOrFields("Query.startAt",e,n,!0);return new t(this._query.withStartAt(i),this.firestore)},t.prototype.startAfter=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];ch("Query.startAfter",arguments,1);var i=this.boundFromDocOrFields("Query.startAfter",e,n,!1);return new t(this._query.withStartAt(i),this.firestore)},t.prototype.endBefore=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];ch("Query.endBefore",arguments,1);var i=this.boundFromDocOrFields("Query.endBefore",e,n,!0);return new t(this._query.withEndAt(i),this.firestore)},t.prototype.endAt=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];ch("Query.endAt",arguments,1);var i=this.boundFromDocOrFields("Query.endAt",e,n,!1);return new t(this._query.withEndAt(i),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Eh("isEqual","Query",1,e);return this.firestore===e.firestore&&this._query.isEqual(e._query)},t.prototype.boundFromDocOrFields=function(t,e,n,r){if(_h(t,1,e),e instanceof rm){if(n.length>0)throw new eh(th.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var i=e;if(!i.exists)throw new eh(th.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,i._document,r)}var o=[e].concat(n);return this.boundFromFields(t,o,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],i=0,o=this._query.orderBy;i<o.length;i++){var s=o[i];if(s.field.isKeyField())r.push(new hl(this.firestore._databaseId,e.key));else{var a=e.field(s.field);if(void 0===a){var u=s.field.canonicalString();throw new eh(th.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(a)}}return new Dl(r,n)},t.prototype.boundFromFields=function(t,e,n){var r=this._query.explicitOrderBy;if(e.length>r.length)throw new eh(th.INVALID_ARGUMENT,"Too many arguments provided to "+t+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var i=[],o=0;o<e.length;o++){var s=e[o];if(r[o].field.isKeyField()){if("string"!=typeof s)throw new eh(th.INVALID_ARGUMENT,"Invalid query. Expected a string for document ID in "+t+"(), but got a "+typeof s);if(-1!==s.indexOf("/"))throw new eh(th.INVALID_ARGUMENT,"Invalid query. Document ID '"+s+"' contains a slash in "+t+"()");var a=new jh(this._query.path.child(s));i.push(new hl(this.firestore._databaseId,a))}else{var u=this.firestore._dataConverter.parseQueryValue(t,s);i.push(u)}}return new Dl(i,n)},t.prototype.onSnapshot=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];hh("Query.onSnapshot",arguments,1,4);var n,r={},i=0;return"object"!=typeof t[i]||Cy(t[i])||(wh("Query.onSnapshot",r=t[i],["includeMetadataChanges"]),dh("Query.onSnapshot","boolean","includeMetadataChanges",r.includeMetadataChanges),i++),Cy(t[i])?n=t[i]:(lh("Query.onSnapshot","function",i,t[i]),fh("Query.onSnapshot","function",i+1,t[i+1]),fh("Query.onSnapshot","function",i+2,t[i+2]),n={next:t[i],error:t[i+1],complete:t[i+2]}),this.onSnapshotInternal(r,n)},t.prototype.onSnapshotInternal=function(t,e){var n=this,r=function(t){console.error("Uncaught Error in onSnapshot:",t)};e.error&&(r=e.error.bind(e));var i=new vy({next:function(t){e.next&&e.next(new sm(n.firestore,n._query,t))},error:r}),o=this.firestore.ensureClientConfigured(),s=o.listen(this._query,i,t);return function(){i.mute(),o.unlisten(s)}},t.prototype.get=function(t){var e=this;return hh("Query.get",arguments,0,1),hm("Query.get",t),new Promise(function(n,r){t&&"cache"===t.source?e.firestore.ensureClientConfigured().getDocumentsFromLocalCache(e._query).then(function(t){n(new sm(e.firestore,e._query,t))},r):e.getViaSnapshotListener(n,r,t)})},t.prototype.getViaSnapshotListener=function(t,e,n){var r=this.onSnapshotInternal({includeMetadataChanges:!0,waitForSyncWhenOnline:!0},{next:function(i){r(),i.metadata.fromCache&&n&&"server"===n.source?e(new eh(th.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.)')):t(i)},error:e})},t.prototype.validateNewFilter=function(t){if(t instanceof Sl)if(t.isInequality()){var e=this._query.getInequalityFilterField();if(null!==e&&!e.isEqual(t.field))throw new eh(th.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+e.toString()+"' and '"+t.field.toString()+"'");var n=this._query.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(t.field,n)}else if(t.op===Tl.ARRAY_CONTAINS&&this._query.hasArrayContainsFilter())throw new eh(th.INVALID_ARGUMENT,"Invalid query. Queries only support a single array-contains filter.")},t.prototype.validateNewOrderBy=function(t){if(null===this._query.getFirstOrderByField()){var e=this._query.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.isEqual(t))throw new eh(th.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t.toString()+"' and so you must also use '"+t.toString()+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e.toString()+"' instead.")},t}(),sm=function(){function t(t,e,n){this._firestore=t,this._originalQuery=e,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new nm(n.hasPendingWrites,n.fromCache)}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach(function(e){return t.push(e)}),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this._snapshot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this._snapshot.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;hh("QuerySnapshot.forEach",arguments,1,2),lh("QuerySnapshot.forEach","function",1,t),this._snapshot.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new om(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),t.prototype.docChanges=function(t){t&&(wh("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),dh("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));var e=!(!t||!t.includeMetadataChanges);if(e&&this._snapshot.excludesMetadataChanges)throw new eh(th.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(t,e,n){if(n.oldDocs.isEmpty()){var r,i=0;return n.docChanges.map(function(e){var o=new im(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key));return Jc(e.type===hf.Added,"Invalid event type for first snapshot"),Jc(!r||n.query.docComparator(r,e.doc)<0,"Got added events in wrong order"),r=e.doc,{type:"added",doc:o,oldIndex:-1,newIndex:i++}})}var o=n.oldDocs;return n.docChanges.filter(function(t){return e||t.type!==hf.Metadata}).map(function(e){var r=new im(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key)),i=-1,s=-1;return e.type!==hf.Added&&(Jc((i=o.indexOf(e.doc.key))>=0,"Index for document not found"),o=o.delete(e.doc.key)),e.type!==hf.Removed&&(o=o.add(e.doc),s=o.indexOf(e.doc.key)),{type:function(t){switch(t){case hf.Added:return"added";case hf.Modified:case hf.Metadata:return"modified";case hf.Removed:return"removed";default:return Xc("Unknown change type: "+t)}}(e.type),doc:r,oldIndex:i,newIndex:s}})}(this._firestore,e,this._snapshot),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Eh("isEqual","QuerySnapshot",1,e);return this._firestore===e._firestore&&this._originalQuery.isEqual(e._originalQuery)&&this._snapshot.isEqual(e._snapshot)},t.prototype.convertToDocumentImpl=function(t){return new im(this._firestore,t.key,t,this.metadata.fromCache,this._snapshot.mutatedKeys.has(t.key))},t}();["length","forEach","map"].concat("undefined"!=typeof Symbol?[Symbol.iterator]:[]).forEach(function(t){try{Object.defineProperty(sm.prototype.docChanges,t,{get:function(){return function(){throw new eh(th.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}()}})}catch(t){}});var am=function(t){function e(e,n){var r=t.call(this,wl.atPath(e),n)||this;if(e.length%2!=1)throw new eh(th.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.canonicalString()+" has "+e.length);return r}return Xe(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this._query.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this._query.path.popLast();return t.isEmpty()?null:new em(new jh(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this._query.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(hh("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=Ih.newId()),lh("CollectionReference.doc","non-empty string",1,t),""===t)throw new eh(th.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=Bh.fromString(t);return em.forPath(this._query.path.child(e),this.firestore)},e.prototype.add=function(t){uh("CollectionReference.add",arguments,1),lh("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(om);function um(t,e){if(void 0===e)return{merge:!1};if(wh(t,e,["merge","mergeFields"]),dh(t,"boolean","merge",e.merge),yh(t,"mergeFields","a string or a FieldPath",e.mergeFields,function(t){return"string"==typeof t||t instanceof by}),void 0!==e.mergeFields&&void 0!==e.merge)throw new eh(th.INVALID_ARGUMENT,"Invalid options passed to function "+t+'(): You cannot specify both "merge" and "mergeFields".');return e}function cm(t,e){return void 0===e?{}:(wh(t,e,["serverTimestamps"]),mh(t,0,"serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function hm(t,e){fh(t,"object",1,e),e&&(wh(t,e,["source"]),mh(t,0,"source",e.source,["default","server","cache"]))}function lm(t,e,n){if(e instanceof em){if(e.firestore!==n)throw new eh(th.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw Eh(t,"DocumentReference",1,e)}var fm=nh($y,"Use firebase.firestore() instead."),pm=nh(Zy,"Use firebase.firestore().runTransaction() instead."),dm=nh(tm,"Use firebase.firestore().batch() instead."),ym=nh(em,"Use firebase.firestore().doc() instead."),mm=nh(rm),gm=nh(im),vm=nh(om),bm=nh(sm),_m=nh(am,"Use firebase.firestore().collection() instead."),wm={Firestore:fm,GeoPoint:Lh,Timestamp:Mh,Blob:Ph,Transaction:pm,WriteBatch:dm,DocumentReference:ym,DocumentSnapshot:mm,Query:vm,QueryDocumentSnapshot:gm,QuerySnapshot:bm,CollectionReference:_m,FieldPath:by,FieldValue:Py,setLogLevel:$y.setLogLevel,CACHE_SIZE_UNLIMITED:Yy};function Em(t){t.INTERNAL.registerService("firestore",function(t){return new $y(t)},function(t){Jc(t&&"object"==typeof t,"shallowCopy() expects object parameter.");var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}(wm))}!function(t){Em(t)}(Gn);var Tm={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"},Sm=function(t){function e(n,r,i){var o=t.call(this,r)||this;return Object.setPrototypeOf(o,e.prototype),o.code=n,o.details=i,o}return Xe(e,t),e}(Error);var Im=function(){function t(t){this.app=t}return t.prototype.getAuthToken=function(){return $e(this,void 0,void 0,function(){var t;return Ze(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.app.INTERNAL.getToken()];case 1:return(t=e.sent())?[2,t.accessToken]:[2,void 0];case 2:return e.sent(),[2,void 0];case 3:return[2]}})})},t.prototype.getInstanceIdToken=function(){return $e(this,void 0,void 0,function(){var t;return Ze(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),this.app.messaging?[4,this.app.messaging().getToken()]:[2,void 0];case 1:return(t=e.sent())?[2,t]:[2,void 0];case 2:return e.sent(),[2,void 0];case 3:return[2]}})})},t.prototype.getContext=function(){return $e(this,void 0,void 0,function(){var t,e;return Ze(this,function(n){switch(n.label){case 0:return[4,this.getAuthToken()];case 1:return t=n.sent(),[4,this.getInstanceIdToken()];case 2:return e=n.sent(),[2,{authToken:t,instanceIdToken:e}]}})})},t}();function Cm(t,e){var n={};for(var r in t)t.hasOwnProperty(r)&&(n[r]=e(t[r]));return n}var Nm=function(){function t(){}return t.prototype.encode=function(t){var e=this;if(null===t||void 0===t)return null;if(t instanceof Number&&(t=t.valueOf()),"number"==typeof t&&isFinite(t))return t;if(!0===t||!1===t)return t;if("[object String]"===Object.prototype.toString.call(t))return t;if(Array.isArray(t))return t.map(function(t){return e.encode(t)});if("function"==typeof t||"object"==typeof t)return Cm(t,function(t){return e.encode(t)});throw new Error("Data cannot be encoded in JSON: "+t)},t.prototype.decode=function(t){var e=this;if(null===t)return t;if(t["@type"])switch(t["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":var n=parseFloat(t.value);if(isNaN(n))throw new Error("Data cannot be decoded from JSON: "+t);return n;default:throw new Error("Data cannot be decoded from JSON: "+t)}return Array.isArray(t)?t.map(function(t){return e.decode(t)}):"function"==typeof t||"object"==typeof t?Cm(t,function(t){return e.decode(t)}):t},t}(),Dm=function(){function t(t,e){void 0===e&&(e="us-central1"),this.app_=t,this.region_=e,this.serializer=new Nm,this.emulatorOrigin=null,this.contextProvider=new Im(t)}return Object.defineProperty(t.prototype,"app",{get:function(){return this.app_},enumerable:!0,configurable:!0}),t.prototype._url=function(t){var e=this.app_.options.projectId,n=this.region_;return null!==this.emulatorOrigin?this.emulatorOrigin+"/"+e+"/"+n+"/"+t:"https://"+n+"-"+e+".cloudfunctions.net/"+t},t.prototype.useFunctionsEmulator=function(t){this.emulatorOrigin=t},t.prototype.httpsCallable=function(t){var e=this;return function(n){return e.call(t,n)}},t.prototype.postJSON=function(t,e,n){return $e(this,void 0,void 0,function(){var r,i;return Ze(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(t,{method:"POST",body:JSON.stringify(e),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}]}})})},t.prototype.call=function(t,e){return $e(this,void 0,void 0,function(){var n,r,i,o,s,a,u;return Ze(this,function(c){switch(c.label){case 0:return n=this._url(t),e=this.serializer.encode(e),r={data:e},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(s=c.sent(),a=function(t,e,n){var r=function(t){if(t>=200&&t<300)return"ok";switch(t){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"}(t),i=r,o=void 0;try{var s=e.error;if(s){var a=s.status;if("string"==typeof a){if(!Tm[a])return new Sm("internal","internal");r=Tm[a]}i=a;var u=s.message;"string"==typeof u&&(i=u),void 0!==(o=s.details)&&(o=n.decode(o))}}catch(t){}return"ok"===r?null:new Sm(r,i,o)}(s.status,s.json,this.serializer))throw a;if(!s.json)throw new Sm("internal","Response is not valid JSON object.");if(void 0===(u=s.json.data)&&(u=s.json.result),void 0===u)throw new Sm("internal","Response is missing data field.");return[2,{data:this.serializer.decode(u)}]}})})},t}(),Am="functions";function km(t,e,n){return new Dm(t,n)}!function(t){var e={Functions:Dm};t.INTERNAL.registerService(Am,km,e,void 0,!0)}(Gn);var Rm,Om,Pm,Lm={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"},Mm=((Rm={})[Lm.AVAILABLE_IN_WINDOW]="This method is available in a Window context.",Rm[Lm.AVAILABLE_IN_SW]="This method is available in a service worker context.",Rm[Lm.SHOULD_BE_INHERITED]="This method should be overriden by extended classes.",Rm[Lm.BAD_SENDER_ID]="Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp().",Rm[Lm.PERMISSION_DEFAULT]="The required permissions were not granted and dismissed instead.",Rm[Lm.PERMISSION_BLOCKED]="The required permissions were not granted and blocked instead.",Rm[Lm.UNSUPPORTED_BROWSER]="This browser doesn't support the API's required to use the firebase SDK.",Rm[Lm.NOTIFICATIONS_BLOCKED]="Notifications have been blocked.",Rm[Lm.FAILED_DEFAULT_REGISTRATION]="We are unable to register the default service worker. {$browserErrorMessage}",Rm[Lm.SW_REGISTRATION_EXPECTED]="A service worker registration was the expected input.",Rm[Lm.GET_SUBSCRIPTION_FAILED]="There was an error when trying to get any existing Push Subscriptions.",Rm[Lm.INVALID_SAVED_TOKEN]="Unable to access details of the saved token.",Rm[Lm.SW_REG_REDUNDANT]="The service worker being used for push was made redundant.",Rm[Lm.TOKEN_SUBSCRIBE_FAILED]="A problem occured while subscribing the user to FCM: {$message}",Rm[Lm.TOKEN_SUBSCRIBE_NO_TOKEN]="FCM returned no token when subscribing the user to push.",Rm[Lm.TOKEN_SUBSCRIBE_NO_PUSH_SET]="FCM returned an invalid response when getting an FCM token.",Rm[Lm.TOKEN_UNSUBSCRIBE_FAILED]="A problem occured while unsubscribing the user from FCM: {$message}",Rm[Lm.TOKEN_UPDATE_FAILED]="A problem occured while updating the user from FCM: {$message}",Rm[Lm.TOKEN_UPDATE_NO_TOKEN]="FCM returned no token when updating the user to push.",Rm[Lm.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.",Rm[Lm.INVALID_DELETE_TOKEN]="You must pass a valid token into deleteToken(), i.e. the token from getToken().",Rm[Lm.DELETE_TOKEN_NOT_FOUND]="The deletion attempt for token could not be performed as the token was not found.",Rm[Lm.DELETE_SCOPE_NOT_FOUND]="The deletion attempt for service worker scope could not be performed as the scope was not found.",Rm[Lm.BG_HANDLER_FUNCTION_EXPECTED]="The input to setBackgroundMessageHandler() must be a function.",Rm[Lm.NO_WINDOW_CLIENT_TO_MSG]="An attempt was made to message a non-existant window client.",Rm[Lm.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}",Rm[Lm.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.",Rm[Lm.FAILED_TO_DELETE_TOKEN]="Unable to delete the currently saved token.",Rm[Lm.NO_SW_IN_REG]="Even though the service worker registration was successful, there was a problem accessing the service worker itself.",Rm[Lm.INCORRECT_GCM_SENDER_ID]="Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging.",Rm[Lm.BAD_SCOPE]="The service worker scope must be a string with at least one character.",Rm[Lm.BAD_VAPID_KEY]="The public VAPID key is not a Uint8Array with 65 bytes.",Rm[Lm.BAD_SUBSCRIPTION]="The subscription must be a valid PushSubscription.",Rm[Lm.BAD_TOKEN]="The FCM Token used for storage / lookup was not a valid token string.",Rm[Lm.BAD_PUSH_SET]="The FCM push set used for storage / lookup was not not a valid push set string.",Rm[Lm.FAILED_DELETE_VAPID_KEY]="The VAPID key could not be deleted.",Rm[Lm.INVALID_PUBLIC_VAPID_KEY]="The public VAPID key must be a string.",Rm[Lm.PUBLIC_KEY_DECRYPTION_FAILED]="The public VAPID key did not equal 65 bytes when decrypted.",Rm),xm=new vn("messaging","Messaging",Mm),Fm=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]),Um="https://fcm.googleapis.com";function qm(t,e){if(null==t||null==e)return!1;if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(var n=new DataView(t),r=new DataView(e),i=0;i<t.byteLength;i++)if(n.getUint8(i)!==r.getUint8(i))return!1;return!0}function Bm(t){return function(t){var e=new Uint8Array(t);return btoa(String.fromCharCode.apply(null,e))}(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}!function(t){t.TYPE_OF_MSG="firebase-messaging-msg-type",t.DATA="firebase-messaging-msg-data"}(Om||(Om={})),function(t){t.PUSH_MSG_RECEIVED="push-msg-received",t.NOTIFICATION_CLICKED="notification-clicked"}(Pm||(Pm={}));var Vm=function(){function t(){}return t.prototype.getToken=function(t,e,n){return $e(this,void 0,void 0,function(){var r,i,o,s,a,u,c,h;return Ze(this,function(l){switch(l.label){case 0:r=Bm(e.getKey("p256dh")),i=Bm(e.getKey("auth")),o="authorized_entity="+t+"&endpoint="+e.endpoint+"&encryption_key="+r+"&encryption_auth="+i,qm(n.buffer,Fm.buffer)||(s=Bm(n),o+="&application_pub_key="+s),(a=new Headers).append("Content-Type","application/x-www-form-urlencoded"),u={method:"POST",headers:a,body:o},l.label=1;case 1:return l.trys.push([1,4,,5]),[4,fetch(Um+"/fcm/connect/subscribe",u)];case 2:return[4,l.sent().json()];case 3:return c=l.sent(),[3,5];case 4:throw l.sent(),xm.create(Lm.TOKEN_SUBSCRIBE_FAILED);case 5:if(c.error)throw h=c.error.message,xm.create(Lm.TOKEN_SUBSCRIBE_FAILED,{message:h});if(!c.token)throw xm.create(Lm.TOKEN_SUBSCRIBE_NO_TOKEN);if(!c.pushSet)throw xm.create(Lm.TOKEN_SUBSCRIBE_NO_PUSH_SET);return[2,{token:c.token,pushSet:c.pushSet}]}})})},t.prototype.updateToken=function(t,e,n,r,i){return $e(this,void 0,void 0,function(){var o,s,a,u,c,h,l,f;return Ze(this,function(p){switch(p.label){case 0:o=Bm(r.getKey("p256dh")),s=Bm(r.getKey("auth")),a="push_set="+n+"&token="+e+"&authorized_entity="+t+"&endpoint="+r.endpoint+"&encryption_key="+o+"&encryption_auth="+s,qm(i.buffer,Fm.buffer)||(u=Bm(i),a+="&application_pub_key="+u),(c=new Headers).append("Content-Type","application/x-www-form-urlencoded"),h={method:"POST",headers:c,body:a},p.label=1;case 1:return p.trys.push([1,4,,5]),[4,fetch(Um+"/fcm/connect/subscribe",h)];case 2:return[4,p.sent().json()];case 3:return l=p.sent(),[3,5];case 4:throw p.sent(),xm.create(Lm.TOKEN_UPDATE_FAILED);case 5:if(l.error)throw f=l.error.message,xm.create(Lm.TOKEN_UPDATE_FAILED,{message:f});if(!l.token)throw xm.create(Lm.TOKEN_UPDATE_NO_TOKEN);return[2,l.token]}})})},t.prototype.deleteToken=function(t,e,n){return $e(this,void 0,void 0,function(){var r,i,o,s,a;return Ze(this,function(u){switch(u.label){case 0:r="authorized_entity="+t+"&token="+e+"&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(Um+"/fcm/connect/unsubscribe",o)];case 2:return[4,u.sent().json()];case 3:if((s=u.sent()).error)throw a=s.error.message,xm.create(Lm.TOKEN_UNSUBSCRIBE_FAILED,{message:a});return[3,5];case 4:throw u.sent(),xm.create(Lm.TOKEN_UNSUBSCRIBE_FAILED);case 5:return[2]}})})},t}();function Wm(t){for(var e=(t+"=".repeat((4-t.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),n=atob(e),r=new Uint8Array(n.length),i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}var jm="undefined",Km="fcm_token_object_Store";function Qm(){var t=indexedDB.open(jm);t.onerror=function(t){},t.onsuccess=function(e){!function(t){if(t.objectStoreNames.contains(Km)){var e=t.transaction(Km).objectStore(Km),n=new Vm,r=e.openCursor();r.onerror=function(t){console.warn("Unable to cleanup old IDB.",t)},r.onsuccess=function(){var e=r.result;if(e){var i=e.value;n.deleteToken(i.fcmSenderId,i.fcmToken,i.fcmPushSet),e.continue()}else t.close(),indexedDB.deleteDatabase(jm)}}}(t.result)}}var Hm=function(){function t(){this.dbPromise=null}return t.prototype.get=function(t){return this.createTransaction(function(e){return e.get(t)})},t.prototype.getIndex=function(t,e){return this.createTransaction(function(n){return n.index(t).get(e)})},t.prototype.put=function(t){return this.createTransaction(function(e){return e.put(t)},"readwrite")},t.prototype.delete=function(t){return this.createTransaction(function(e){return e.delete(t)},"readwrite")},t.prototype.closeDatabase=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return this.dbPromise?[4,this.dbPromise]:[3,2];case 1:t.sent().close(),this.dbPromise=null,t.label=2;case 2:return[2]}})})},t.prototype.createTransaction=function(t,e){return void 0===e&&(e="readonly"),$e(this,void 0,void 0,function(){var n,r,i,o;return Ze(this,function(s){switch(s.label){case 0:return[4,this.getDb()];case 1:return n=s.sent(),r=n.transaction(this.objectStoreName,e),i=r.objectStore(this.objectStoreName),[4,function(t){return new Promise(function(e,n){t.onsuccess=function(){e(t.result)},t.onerror=function(){n(t.error)}})}(t(i))];case 2:return o=s.sent(),[2,new Promise(function(t,e){r.oncomplete=function(){t(o)},r.onerror=function(){e(r.error)}})]}})})},t.prototype.getDb=function(){var t=this;return this.dbPromise||(this.dbPromise=new Promise(function(e,n){var r=indexedDB.open(t.dbName,t.dbVersion);r.onsuccess=function(){e(r.result)},r.onerror=function(){t.dbPromise=null,n(r.error)},r.onupgradeneeded=function(e){return t.onDbUpgrade(r,e)}})),this.dbPromise},t}();var Gm=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.dbName="fcm_token_details_db",e.dbVersion=3,e.objectStoreName="fcm_token_object_Store",e}return Xe(e,t),e.prototype.onDbUpgrade=function(t,e){var n=t.result;switch(e.oldVersion){case 0:(r=n.createObjectStore(this.objectStoreName,{keyPath:"swScope"})).createIndex("fcmSenderId","fcmSenderId",{unique:!1}),r.createIndex("fcmToken","fcmToken",{unique:!0});case 1:Qm();case 2:var r,i=(r=t.transaction.objectStore(this.objectStoreName)).openCursor();i.onsuccess=function(){var t=i.result;if(t){var e=t.value,n=Je({},e);e.createTime||(n.createTime=Date.now()),"string"==typeof e.vapidKey&&(n.vapidKey=Wm(e.vapidKey)),"string"==typeof e.auth&&(n.auth=Wm(e.auth).buffer),"string"==typeof e.auth&&(n.p256dh=Wm(e.p256dh).buffer),t.update(n),t.continue()}}}},e.prototype.getTokenDetailsFromToken=function(t){return $e(this,void 0,void 0,function(){return Ze(this,function(e){if(!t)throw xm.create(Lm.BAD_TOKEN);return zm({fcmToken:t}),[2,this.getIndex("fcmToken",t)]})})},e.prototype.getTokenDetailsFromSWScope=function(t){return $e(this,void 0,void 0,function(){return Ze(this,function(e){if(!t)throw xm.create(Lm.BAD_SCOPE);return zm({swScope:t}),[2,this.get(t)]})})},e.prototype.saveTokenDetails=function(t){return $e(this,void 0,void 0,function(){return Ze(this,function(e){if(!t.swScope)throw xm.create(Lm.BAD_SCOPE);if(!t.vapidKey)throw xm.create(Lm.BAD_VAPID_KEY);if(!t.endpoint||!t.auth||!t.p256dh)throw xm.create(Lm.BAD_SUBSCRIPTION);if(!t.fcmSenderId)throw xm.create(Lm.BAD_SENDER_ID);if(!t.fcmToken)throw xm.create(Lm.BAD_TOKEN);if(!t.fcmPushSet)throw xm.create(Lm.BAD_PUSH_SET);return zm(t),[2,this.put(t)]})})},e.prototype.deleteToken=function(t){return $e(this,void 0,void 0,function(){var e;return Ze(this,function(n){switch(n.label){case 0:return"string"!=typeof t||0===t.length?[2,Promise.reject(xm.create(Lm.INVALID_DELETE_TOKEN))]:[4,this.getTokenDetailsFromToken(t)];case 1:if(!(e=n.sent()))throw xm.create(Lm.DELETE_TOKEN_NOT_FOUND);return[4,this.delete(e.swScope)];case 2:return n.sent(),[2,e]}})})},e}(Hm);function zm(t){if(t.fcmToken&&("string"!=typeof t.fcmToken||0===t.fcmToken.length))throw xm.create(Lm.BAD_TOKEN);if(t.swScope&&("string"!=typeof t.swScope||0===t.swScope.length))throw xm.create(Lm.BAD_SCOPE);if(t.vapidKey&&(!(t.vapidKey instanceof Uint8Array)||65!==t.vapidKey.length))throw xm.create(Lm.BAD_VAPID_KEY);if(t.endpoint&&("string"!=typeof t.endpoint||0===t.endpoint.length))throw xm.create(Lm.BAD_SUBSCRIPTION);if(t.auth&&!(t.auth instanceof ArrayBuffer))throw xm.create(Lm.BAD_SUBSCRIPTION);if(t.p256dh&&!(t.p256dh instanceof ArrayBuffer))throw xm.create(Lm.BAD_SUBSCRIPTION);if(t.fcmSenderId&&("string"!=typeof t.fcmSenderId||0===t.fcmSenderId.length))throw xm.create(Lm.BAD_SENDER_ID);if(t.fcmPushSet&&("string"!=typeof t.fcmPushSet||0===t.fcmPushSet.length))throw xm.create(Lm.BAD_PUSH_SET)}var Ym=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.dbName="fcm_vapid_details_db",e.dbVersion=1,e.objectStoreName="fcm_vapid_object_Store",e}return Xe(e,t),e.prototype.onDbUpgrade=function(t){t.result.createObjectStore(this.objectStoreName,{keyPath:"swScope"})},e.prototype.getVapidFromSWScope=function(t){return $e(this,void 0,void 0,function(){var e;return Ze(this,function(n){switch(n.label){case 0:if("string"!=typeof t||0===t.length)throw xm.create(Lm.BAD_SCOPE);return[4,this.get(t)];case 1:return[2,(e=n.sent())?e.vapidKey:void 0]}})})},e.prototype.saveVapidDetails=function(t,e){return $e(this,void 0,void 0,function(){var n;return Ze(this,function(r){if("string"!=typeof t||0===t.length)throw xm.create(Lm.BAD_SCOPE);if(null===e||65!==e.length)throw xm.create(Lm.BAD_VAPID_KEY);return n={swScope:t,vapidKey:e},[2,this.put(n)]})})},e.prototype.deleteVapidDetails=function(t){return $e(this,void 0,void 0,function(){var e;return Ze(this,function(n){switch(n.label){case 0:return[4,this.getVapidFromSWScope(t)];case 1:if(!(e=n.sent()))throw xm.create(Lm.DELETE_SCOPE_NOT_FOUND);return[4,this.delete(t)];case 2:return n.sent(),[2,e]}})})},e}(Hm),Xm="messagingSenderId",Jm=function(){function t(t){var e=this;if(!t.options[Xm]||"string"!=typeof t.options[Xm])throw xm.create(Lm.BAD_SENDER_ID);this.messagingSenderId=t.options[Xm],this.tokenDetailsModel=new Gm,this.vapidDetailsModel=new Ym,this.iidModel=new Vm,this.app=t,this.INTERNAL={delete:function(){return e.delete()}}}return t.prototype.getToken=function(){return $e(this,void 0,void 0,function(){var t,e,n,r,i;return Ze(this,function(o){switch(o.label){case 0:if("denied"===(t=this.getNotificationPermission_()))throw xm.create(Lm.NOTIFICATIONS_BLOCKED);return"granted"!==t?[2,null]:[4,this.getSWRegistration_()];case 1:return e=o.sent(),[4,this.getPublicVapidKey_()];case 2:return n=o.sent(),[4,this.getPushSubscription(e,n)];case 3:return r=o.sent(),[4,this.tokenDetailsModel.getTokenDetailsFromSWScope(e.scope)];case 4:return(i=o.sent())?[2,this.manageExistingToken(e,r,n,i)]:[2,this.getNewToken(e,r,n)]}})})},t.prototype.manageExistingToken=function(t,e,n,r){return $e(this,void 0,void 0,function(){return Ze(this,function(i){switch(i.label){case 0:return function(t,e,n){if(!n.vapidKey||!qm(e.buffer,n.vapidKey.buffer))return!1;var r=t.endpoint===n.endpoint,i=qm(t.getKey("auth"),n.auth),o=qm(t.getKey("p256dh"),n.p256dh);return r&&i&&o}(e,n,r)?Date.now()<r.createTime+6048e5?[2,r.fcmToken]:[2,this.updateToken(t,e,n,r)]:[4,this.deleteTokenFromDB(r.fcmToken)];case 1:return i.sent(),[2,this.getNewToken(t,e,n)]}})})},t.prototype.updateToken=function(t,e,n,r){return $e(this,void 0,void 0,function(){var i,o,s;return Ze(this,function(a){switch(a.label){case 0:return a.trys.push([0,4,,6]),[4,this.iidModel.updateToken(this.messagingSenderId,r.fcmToken,r.fcmPushSet,e,n)];case 1:return i=a.sent(),o={swScope:t.scope,vapidKey:n,fcmSenderId:this.messagingSenderId,fcmToken:i,fcmPushSet:r.fcmPushSet,createTime:Date.now(),endpoint:e.endpoint,auth:e.getKey("auth"),p256dh:e.getKey("p256dh")},[4,this.tokenDetailsModel.saveTokenDetails(o)];case 2:return a.sent(),[4,this.vapidDetailsModel.saveVapidDetails(t.scope,n)];case 3:return a.sent(),[2,i];case 4:return s=a.sent(),[4,this.deleteToken(r.fcmToken)];case 5:throw a.sent(),s;case 6:return[2]}})})},t.prototype.getNewToken=function(t,e,n){return $e(this,void 0,void 0,function(){var r,i;return Ze(this,function(o){switch(o.label){case 0:return[4,this.iidModel.getToken(this.messagingSenderId,e,n)];case 1:return r=o.sent(),i={swScope:t.scope,vapidKey:n,fcmSenderId:this.messagingSenderId,fcmToken:r.token,fcmPushSet:r.pushSet,createTime:Date.now(),endpoint:e.endpoint,auth:e.getKey("auth"),p256dh:e.getKey("p256dh")},[4,this.tokenDetailsModel.saveTokenDetails(i)];case 2:return o.sent(),[4,this.vapidDetailsModel.saveVapidDetails(t.scope,n)];case 3:return o.sent(),[2,r.token]}})})},t.prototype.deleteToken=function(t){return $e(this,void 0,void 0,function(){var e,n;return Ze(this,function(r){switch(r.label){case 0:return[4,this.deleteTokenFromDB(t)];case 1:return r.sent(),[4,this.getSWRegistration_()];case 2:return(e=r.sent())?[4,e.pushManager.getSubscription()]:[3,4];case 3:if(n=r.sent())return[2,n.unsubscribe()];r.label=4;case 4:return[2,!0]}})})},t.prototype.deleteTokenFromDB=function(t){return $e(this,void 0,void 0,function(){var e;return Ze(this,function(n){switch(n.label){case 0:return[4,this.tokenDetailsModel.deleteToken(t)];case 1:return e=n.sent(),[4,this.iidModel.deleteToken(e.fcmSenderId,e.fcmToken,e.fcmPushSet)];case 2:return n.sent(),[2]}})})},t.prototype.getPushSubscription=function(t,e){return t.pushManager.getSubscription().then(function(n){return n||t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e})})},t.prototype.requestPermission=function(){throw xm.create(Lm.AVAILABLE_IN_WINDOW)},t.prototype.useServiceWorker=function(t){throw xm.create(Lm.AVAILABLE_IN_WINDOW)},t.prototype.usePublicVapidKey=function(t){throw xm.create(Lm.AVAILABLE_IN_WINDOW)},t.prototype.onMessage=function(t,e,n){throw xm.create(Lm.AVAILABLE_IN_WINDOW)},t.prototype.onTokenRefresh=function(t,e,n){throw xm.create(Lm.AVAILABLE_IN_WINDOW)},t.prototype.setBackgroundMessageHandler=function(t){throw xm.create(Lm.AVAILABLE_IN_SW)},t.prototype.delete=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return[4,Promise.all([this.tokenDetailsModel.closeDatabase(),this.vapidDetailsModel.closeDatabase()])];case 1:return t.sent(),[2]}})})},t.prototype.getNotificationPermission_=function(){return Notification.permission},t.prototype.getTokenDetailsModel=function(){return this.tokenDetailsModel},t.prototype.getVapidDetailsModel=function(){return this.vapidDetailsModel},t.prototype.getIidModel=function(){return this.iidModel},t}();var $m=function(t){function e(e){var n=t.call(this,e)||this;return n.bgMessageHandler=null,self.addEventListener("push",function(t){n.onPush(t)}),self.addEventListener("pushsubscriptionchange",function(t){n.onSubChange(t)}),self.addEventListener("notificationclick",function(t){n.onNotificationClick(t)}),n}return Xe(e,t),e.prototype.onPush=function(t){t.waitUntil(this.onPush_(t))},e.prototype.onSubChange=function(t){t.waitUntil(this.onSubChange_(t))},e.prototype.onNotificationClick=function(t){t.waitUntil(this.onNotificationClick_(t))},e.prototype.onPush_=function(t){return $e(this,void 0,void 0,function(){var e,n,r,i,o,s;return Ze(this,function(a){switch(a.label){case 0:if(!t.data)return[2];try{e=t.data.json()}catch(t){return[2]}return[4,this.hasVisibleClients_()];case 1:return a.sent()?[2,this.sendMessageToWindowClients_(e)]:(n=this.getNotificationData_(e))?(r=n.title||"",[4,this.getSWRegistration_()]):[3,3];case 2:return i=a.sent(),o=n.actions,s=Notification.maxActions,o&&s&&o.length>s&&console.warn("This browser only supports "+s+" actions.The remaining actions will not be displayed."),[2,i.showNotification(r,n)];case 3:return this.bgMessageHandler?[4,this.bgMessageHandler(e)]:[3,5];case 4:return a.sent(),[2];case 5:return[2]}})})},e.prototype.onSubChange_=function(t){return $e(this,void 0,void 0,function(){var t,e,n,r;return Ze(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.getSWRegistration_()];case 1:return t=i.sent(),[3,3];case 2:throw e=i.sent(),xm.create(Lm.UNABLE_TO_RESUBSCRIBE,{message:e});case 3:return i.trys.push([3,5,,8]),[4,t.pushManager.getSubscription()];case 4:return i.sent(),[3,8];case 5:return n=i.sent(),[4,this.getTokenDetailsModel().getTokenDetailsFromSWScope(t.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]}})})},e.prototype.onNotificationClick_=function(t){return $e(this,void 0,void 0,function(){var e,n,r,i;return Ze(this,function(o){switch(o.label){case 0:return t.notification&&t.notification.data&&t.notification.data.FCM_MSG?t.action?[2]:(t.stopImmediatePropagation(),t.notification.close(),(e=t.notification.data.FCM_MSG).notification&&(n=e.fcmOptions&&e.fcmOptions.link||e.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 e.notification,delete e.fcmOptions,i=tg(Pm.NOTIFICATION_CLICKED,e),[2,this.attemptToMessageClient_(r,i)]):[2]}})})},e.prototype.getNotificationData_=function(t){if(t&&"object"==typeof t.notification){var e,n=Je({},t.notification);return n.data=Je({},t.notification.data,((e={}).FCM_MSG=t,e)),n}},e.prototype.setBackgroundMessageHandler=function(t){if(!t||"function"!=typeof t)throw xm.create(Lm.BG_HANDLER_FUNCTION_EXPECTED);this.bgMessageHandler=t},e.prototype.getWindowClient_=function(t){return $e(this,void 0,void 0,function(){var e,n,r,i;return Ze(this,function(o){switch(o.label){case 0:return e=new URL(t,self.location.href).href,[4,Zm()];case 1:for(n=o.sent(),r=null,i=0;i<n.length;i++)if(new URL(n[i].url,self.location.href).href===e){r=n[i];break}return[2,r]}})})},e.prototype.attemptToMessageClient_=function(t,e){return $e(this,void 0,void 0,function(){return Ze(this,function(n){if(!t)throw xm.create(Lm.NO_WINDOW_CLIENT_TO_MSG);return t.postMessage(e),[2]})})},e.prototype.hasVisibleClients_=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){switch(t.label){case 0:return[4,Zm()];case 1:return[2,t.sent().some(function(t){return"visible"===t.visibilityState})]}})})},e.prototype.sendMessageToWindowClients_=function(t){return $e(this,void 0,void 0,function(){var e,n,r=this;return Ze(this,function(i){switch(i.label){case 0:return[4,Zm()];case 1:return e=i.sent(),n=tg(Pm.PUSH_MSG_RECEIVED,t),[4,Promise.all(e.map(function(t){return r.attemptToMessageClient_(t,n)}))];case 2:return i.sent(),[2]}})})},e.prototype.getSWRegistration_=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){return[2,self.registration]})})},e.prototype.getPublicVapidKey_=function(){return $e(this,void 0,void 0,function(){var t,e;return Ze(this,function(n){switch(n.label){case 0:return[4,this.getSWRegistration_()];case 1:if(!(t=n.sent()))throw xm.create(Lm.SW_REGISTRATION_EXPECTED);return[4,this.getVapidDetailsModel().getVapidFromSWScope(t.scope)];case 2:return null==(e=n.sent())?[2,Fm]:[2,e]}})})},e}(Jm);function Zm(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function tg(t,e){return(n={})[Om.TYPE_OF_MSG]=t,n[Om.DATA]=e,n;var n}var eg=function(t){function e(e){var n=t.call(this,e)||this;return n.registrationToUse=null,n.publicVapidKeyToUse=null,n.manifestCheckPromise=null,n.messageObserver=null,n.tokenRefreshObserver=null,n.onMessageInternal=On(function(t){n.messageObserver=t}),n.onTokenRefreshInternal=On(function(t){n.tokenRefreshObserver=t}),n.setupSWMessageListener_(),n}return Xe(e,t),e.prototype.getToken=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(e){switch(e.label){case 0:return this.manifestCheckPromise||(this.manifestCheckPromise=function(){return $e(this,void 0,void 0,function(){var t,e;return Ze(this,function(n){switch(n.label){case 0:if(!(t=document.querySelector('link[rel="manifest"]')))return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(t.href)];case 2:return[4,n.sent().json()];case 3:return e=n.sent(),[3,5];case 4:return n.sent(),[2];case 5:if(!e||!e.gcm_sender_id)return[2];if("103953800507"!==e.gcm_sender_id)throw xm.create(Lm.INCORRECT_GCM_SENDER_ID);return[2]}})})}()),[4,this.manifestCheckPromise];case 1:return e.sent(),[2,t.prototype.getToken.call(this)]}})})},e.prototype.requestPermission=function(){return $e(this,void 0,void 0,function(){var t;return Ze(this,function(e){switch(e.label){case 0:return"granted"===this.getNotificationPermission_()?[2]:[4,Notification.requestPermission()];case 1:if("granted"===(t=e.sent()))return[2];throw"denied"===t?xm.create(Lm.PERMISSION_BLOCKED):xm.create(Lm.PERMISSION_DEFAULT)}})})},e.prototype.useServiceWorker=function(t){if(!(t instanceof ServiceWorkerRegistration))throw xm.create(Lm.SW_REGISTRATION_EXPECTED);if(null!=this.registrationToUse)throw xm.create(Lm.USE_SW_BEFORE_GET_TOKEN);this.registrationToUse=t},e.prototype.usePublicVapidKey=function(t){if("string"!=typeof t)throw xm.create(Lm.INVALID_PUBLIC_VAPID_KEY);if(null!=this.publicVapidKeyToUse)throw xm.create(Lm.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);var e=Wm(t);if(65!==e.length)throw xm.create(Lm.PUBLIC_KEY_DECRYPTION_FAILED);this.publicVapidKeyToUse=e},e.prototype.onMessage=function(t,e,n){return"function"==typeof t?this.onMessageInternal(t,e,n):this.onMessageInternal(t)},e.prototype.onTokenRefresh=function(t,e,n){return"function"==typeof t?this.onTokenRefreshInternal(t,e,n):this.onTokenRefreshInternal(t)},e.prototype.waitForRegistrationToActivate_=function(t){var e=t.installing||t.waiting||t.active;return new Promise(function(n,r){if(e)if("activated"!==e.state)if("redundant"!==e.state){var i=function(){if("activated"===e.state)n(t);else{if("redundant"!==e.state)return;r(xm.create(Lm.SW_REG_REDUNDANT))}e.removeEventListener("statechange",i)};e.addEventListener("statechange",i)}else r(xm.create(Lm.SW_REG_REDUNDANT));else n(t);else r(xm.create(Lm.NO_SW_IN_REG))})},e.prototype.getSWRegistration_=function(){var t=this;return this.registrationToUse?this.waitForRegistrationToActivate_(this.registrationToUse):(this.registrationToUse=null,navigator.serviceWorker.register("/firebase-messaging-sw.js",{scope:"/firebase-cloud-messaging-push-scope"}).catch(function(t){throw xm.create(Lm.FAILED_DEFAULT_REGISTRATION,{browserErrorMessage:t.message})}).then(function(e){return t.waitForRegistrationToActivate_(e).then(function(){return t.registrationToUse=e,e.update(),e})}))},e.prototype.getPublicVapidKey_=function(){return $e(this,void 0,void 0,function(){return Ze(this,function(t){return this.publicVapidKeyToUse?[2,this.publicVapidKeyToUse]:[2,Fm]})})},e.prototype.setupSWMessageListener_=function(){var t=this;navigator.serviceWorker.addEventListener("message",function(e){if(e.data&&e.data[Om.TYPE_OF_MSG]){var n=e.data;switch(n[Om.TYPE_OF_MSG]){case Pm.PUSH_MSG_RECEIVED:case Pm.NOTIFICATION_CLICKED:var r=n[Om.DATA];t.messageObserver&&t.messageObserver.next(r)}}},!1)},e}(Jm);function ng(){return self&&"ServiceWorkerGlobalScope"in self?"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):navigator.cookieEnabled&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}!function(t){var e={isSupported:ng};t.INTERNAL.registerService("messaging",function(t){if(!ng())throw xm.create(Lm.UNSUPPORTED_BROWSER);return self&&"ServiceWorkerGlobalScope"in self?new $m(t):new eg(t)},e)}(Gn);var rg="https://firebasestorage.googleapis.com",ig="https://firebasestorage.googleapis.com",og="/v0",sg="/v0",ag=12e4,ug=6e4,cg=-9007199254740991,hg=function(){function t(t,e){this.code_=fg(t),this.message_="Firebase Storage: "+e,this.serverResponse_=null,this.name_="FirebaseError"}return t.prototype.codeProp=function(){return this.code},t.prototype.codeEquals=function(t){return fg(t)===this.codeProp()},t.prototype.serverResponseProp=function(){return this.serverResponse_},t.prototype.setServerResponseProp=function(t){this.serverResponse_=t},Object.defineProperty(t.prototype,"name",{get:function(){return this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"code",{get:function(){return this.code_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"message",{get:function(){return this.message_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"serverResponse",{get:function(){return this.serverResponse_},enumerable:!0,configurable:!0}),t}(),lg={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 fg(t){return"storage/"+t}function pg(){return new hg(lg.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function dg(){return new hg(lg.CANCELED,"User canceled the upload/download.")}function yg(){return new hg(lg.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function mg(t,e,n){return new hg(lg.INVALID_ARGUMENT,"Invalid argument in `"+e+"` at index "+t+": "+n)}function gg(){return new hg(lg.APP_DELETED,"The Firebase app was deleted.")}function vg(t,e){return new hg(lg.INVALID_FORMAT,"String does not match format '"+t+"': "+e)}function bg(t){throw new hg(lg.INTERNAL_ERROR,"Internal error: "+t)}var _g={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};function wg(t){switch(t){case _g.RAW:case _g.BASE64:case _g.BASE64URL:case _g.DATA_URL:return;default:throw"Expected one of the event types: ["+_g.RAW+", "+_g.BASE64+", "+_g.BASE64URL+", "+_g.DATA_URL+"]."}}var Eg=function(){return function(t,e){this.data=t,this.contentType=e||null}}();function Tg(t,e){switch(t){case _g.RAW:return new Eg(Sg(e));case _g.BASE64:case _g.BASE64URL:return new Eg(Ig(t,e));case _g.DATA_URL:return new Eg(function(t){var e=new Cg(t);return e.base64?Ig(_g.BASE64,e.rest):function(t){var e;try{e=decodeURIComponent(t)}catch(t){throw vg(_g.DATA_URL,"Malformed data URL.")}return Sg(e)}(e.rest)}(e),function(t){return new Cg(t).contentType}(e))}throw pg()}function Sg(t){for(var e=[],n=0;n<t.length;n++){var r=t.charCodeAt(n);if(r<=127)e.push(r);else if(r<=2047)e.push(192|r>>6,128|63&r);else if(55296==(64512&r))if(n<t.length-1&&56320==(64512&t.charCodeAt(n+1)))r=65536|(1023&r)<<10|1023&t.charCodeAt(++n),e.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r);else e.push(239,191,189);else 56320==(64512&r)?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(e)}function Ig(t,e){switch(t){case _g.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw vg(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case _g.BASE64URL:var i=-1!==e.indexOf("+"),o=-1!==e.indexOf("/");if(i||o)throw vg(t,"Invalid character '"+(i?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}var s;try{s=atob(e)}catch(e){throw vg(t,"Invalid character found")}for(var a=new Uint8Array(s.length),u=0;u<s.length;u++)a[u]=s.charCodeAt(u);return a}var Cg=function(){return function(t){this.base64=!1,this.contentType=null;var e=t.match(/^data:([^,]+)?,/);if(null===e)throw vg(_g.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");var n=e[1]||null;null!=n&&(this.base64=(r=n,i=";base64",r.length>=i.length&&r.substring(r.length-i.length)===i),this.contentType=this.base64?n.substring(0,n.length-";base64".length):n),this.rest=t.substring(t.indexOf(",")+1);var r,i}}();var Ng,Dg={STATE_CHANGED:"state_changed"},Ag={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},kg={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function Rg(t){switch(t){case Ag.RUNNING:case Ag.PAUSING:case Ag.CANCELING:return kg.RUNNING;case Ag.PAUSED:return kg.PAUSED;case Ag.SUCCESS:return kg.SUCCESS;case Ag.CANCELED:return kg.CANCELED;case Ag.ERROR:default:return kg.ERROR}}function Og(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Pg(t,e){for(var n in t)Og(t,n)&&e(n,t[n])}function Lg(t){if(null==t)return{};var e={};return Pg(t,function(t,n){e[t]=n}),e}function Mg(t){return new Promise(t)}function xg(t){return Promise.resolve(t)}function Fg(t){return null!=t}function Ug(t){return void 0!==t}function qg(t){return"function"==typeof t}function Bg(t){return"object"==typeof t}function Vg(t){return Bg(t)&&null!==t}function Wg(t){return"string"==typeof t||t instanceof String}function jg(t){return Kg()&&t instanceof Blob}function Kg(){return"undefined"!=typeof Blob}!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(Ng||(Ng={}));var Qg=function(){function t(){var t=this;this.sent_=!1,this.xhr_=new XMLHttpRequest,this.errorCode_=Ng.NO_ERROR,this.sendPromise_=Mg(function(e,n){t.xhr_.addEventListener("abort",function(n){t.errorCode_=Ng.ABORT,e(t)}),t.xhr_.addEventListener("error",function(n){t.errorCode_=Ng.NETWORK_ERROR,e(t)}),t.xhr_.addEventListener("load",function(n){e(t)})})}return t.prototype.send=function(t,e,n,r){var i=this;if(this.sent_)throw bg("cannot .send() more than once");(this.sent_=!0,this.xhr_.open(e,t,!0),Fg(r))&&Pg(r,function(t,e){i.xhr_.setRequestHeader(t,e.toString())});return Fg(n)?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_},t.prototype.getErrorCode=function(){if(!this.sent_)throw bg("cannot .getErrorCode() before sending");return this.errorCode_},t.prototype.getStatus=function(){if(!this.sent_)throw bg("cannot .getStatus() before sending");try{return this.xhr_.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.sent_)throw bg("cannot .getResponseText() before sending");return this.xhr_.responseText},t.prototype.abort=function(){this.xhr_.abort()},t.prototype.getResponseHeader=function(t){return this.xhr_.getResponseHeader(t)},t.prototype.addUploadProgressListener=function(t){Fg(this.xhr_.upload)&&this.xhr_.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){Fg(this.xhr_.upload)&&this.xhr_.upload.removeEventListener("progress",t)},t}(),Hg=function(){function t(){}return t.prototype.createXhrIo=function(){return new Qg},t}();function Gg(t){var e,n;try{e=JSON.parse(t)}catch(t){return null}return Bg(n=e)&&!Array.isArray(n)?e:null}var zg=function(){function t(t,e){this.bucket=t,this.path_=e}return Object.defineProperty(t.prototype,"path",{get:function(){return this.path_},enumerable:!0,configurable:!0}),t.prototype.fullServerUrl=function(){var t=encodeURIComponent;return"/b/"+t(this.bucket)+"/o/"+t(this.path)},t.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},t.makeFromBucketSpec=function(e){var n,r;try{n=t.makeFromUrl(e)}catch(n){return new t(e,"")}if(""===n.path)return n;throw r=e,new hg(lg.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+r+"'.")},t.makeFromUrl=function(e){var n=null;for(var r=[{regex:new RegExp("^gs://([A-Za-z0-9.\\-_]+)(/(.*))?$","i"),indices:{bucket:1,path:3},postModify:function(t){"/"===t.path.charAt(t.path.length-1)&&(t.path_=t.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(t){t.path_=decodeURIComponent(t.path)}}],i=0;i<r.length;i++){var o=r[i],s=o.regex.exec(e);if(s){var a=s[o.indices.bucket],u=s[o.indices.path];u||(u=""),n=new t(a,u),o.postModify(n);break}}if(null==n)throw function(t){return new hg(lg.INVALID_URL,"Invalid URL '"+t+"'.")}(e);return n},t}();function Yg(t){var e=t.lastIndexOf("/",t.length-2);return-1===e?t:t.slice(e+1)}function Xg(t){return rg+og+t}function Jg(t){return rg+sg+t}function $g(t){var e=encodeURIComponent,n="?";return Pg(t,function(t,r){var i=e(t)+"="+e(r);n=n+i+"&"}),n=n.slice(0,-1)}function Zg(t,e){return e}var tv=function(){return function(t,e,n,r){this.server=t,this.local=e||t,this.writable=!!n,this.xform=r||Zg}}(),ev=null;function nv(){if(ev)return ev;var t=[];t.push(new tv("bucket")),t.push(new tv("generation")),t.push(new tv("metageneration")),t.push(new tv("name","fullPath",!0));var e=new tv("name");e.xform=function(t,e){return function(t){return!Wg(t)||t.length<2?t:Yg(t=t)}(e)},t.push(e);var n=new tv("size");return n.xform=function(t,e){return Fg(e)?+e:e},t.push(n),t.push(new tv("timeCreated")),t.push(new tv("updated")),t.push(new tv("md5Hash",null,!0)),t.push(new tv("cacheControl",null,!0)),t.push(new tv("contentDisposition",null,!0)),t.push(new tv("contentEncoding",null,!0)),t.push(new tv("contentLanguage",null,!0)),t.push(new tv("contentType",null,!0)),t.push(new tv("metadata","customMetadata",!0)),ev=t}function rv(t,e,n){for(var r={type:"file"},i=n.length,o=0;o<i;o++){var s=n[o];r[s.local]=s.xform(r,e[s.server])}return function(t,e){Object.defineProperty(t,"ref",{get:function(){var n=t.bucket,r=t.fullPath,i=new zg(n,r);return e.makeStorageReference(i)}})}(r,t),r}function iv(t,e,n){var r=Gg(e);return null===r?null:rv(t,r,n)}function ov(t,e){var n=Gg(e);if(null===n)return null;if(!Wg(n.downloadTokens))return null;var r=n.downloadTokens;if(0===r.length)return null;var i=encodeURIComponent;return r.split(",").map(function(e){var n=t.bucket,r=t.fullPath;return function(t){return ig+og+t}("/b/"+i(n)+"/o/"+i(r))+$g({alt:"media",token:e})})[0]}function sv(t,e){for(var n={},r=e.length,i=0;i<r;i++){var o=e[i];o.writable&&(n[o.server]=t[o.local])}return JSON.stringify(n)}function av(t){if(!(t&&Bg(t)))throw"Expected Metadata object.";for(var e in t){var n=t[e];if("customMetadata"===e){if(!Bg(n))throw"Expected object for 'customMetadata' mapping."}else if(Vg(n))throw"Mapping for '"+e+"' cannot be an object."}}function uv(t,e,n){for(var r=e.length,i=e.length,o=0;o<e.length;o++)if(e[o].optional){r=o;break}var s,a,u,c,h,l;if(!(r<=n.length&&n.length<=i))throw s=r,a=i,u=t,c=n.length,s===a?(h=s,l=1===s?"argument":"arguments"):(h="between "+s+" and "+a,l="arguments"),new hg(lg.INVALID_ARGUMENT_COUNT,"Invalid argument count in `"+u+"`: Expected "+h+" "+l+", received "+c+".");for(o=0;o<n.length;o++)try{e[o].validator(n[o])}catch(e){throw e instanceof Error?mg(o,t,e.message):mg(o,t,e)}}var cv=function(){return function(t,e){var n=this;this.validator=function(e){n.optional&&!Ug(e)||t(e)},this.optional=!!e}}();function hv(t,e){function n(t){if(!Wg(t))throw"Expected string."}var r,i,o;return t?(i=n,o=t,r=function(t){i(t),o(t)}):r=n,new cv(r,e)}function lv(t){return new cv(av,t)}function fv(){return new cv(function(t){if(!(function(t){return"number"==typeof t||t instanceof Number}(t)&&t>=0))throw"Expected a number 0 or greater."})}function pv(t,e){return new cv(function(e){if(!(null===e||Fg(e)&&e instanceof Object))throw"Expected an Object.";void 0!==t&&null!==t&&t(e)},e)}function dv(t){return new cv(function(t){if(null!==t&&!qg(t))throw"Expected a Function."},t)}function yv(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}var mv=function(){function t(t,e){var n=0,r="";jg(t)?(this.data_=t,n=t.size,r=t.type):t instanceof ArrayBuffer?(e?this.data_=new Uint8Array(t):(this.data_=new Uint8Array(t.byteLength),this.data_.set(new Uint8Array(t))),n=this.data_.length):t instanceof Uint8Array&&(e?this.data_=t:(this.data_=new Uint8Array(t.length),this.data_.set(t)),n=t.length),this.size_=n,this.type_=r}return t.prototype.size=function(){return this.size_},t.prototype.type=function(){return this.type_},t.prototype.slice=function(e,n){if(jg(this.data_)){var r=this.data_,i=(s=e,a=n,(o=r).webkitSlice?o.webkitSlice(s,a):o.mozSlice?o.mozSlice(s,a):o.slice?o.slice(s,a):null);return null===i?null:new t(i)}var o,s,a;return new t(new Uint8Array(this.data_.buffer,e,n-e),!0)},t.getBlob=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];if(Kg()){var r=e.map(function(e){return e instanceof t?e.data_:e});return new t(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=yv();if(void 0!==n){for(var r=new n,i=0;i<t.length;i++)r.append(t[i]);return r.getBlob()}if(Kg())return new Blob(t);throw Error("This browser doesn't seem to support creating Blobs")}.apply(null,r))}var i=e.map(function(t){return Wg(t)?Tg(_g.RAW,t).data:t.data_}),o=0;i.forEach(function(t){o+=t.byteLength});var s=new Uint8Array(o),a=0;return i.forEach(function(t){for(var e=0;e<t.length;e++)s[a++]=t[e]}),new t(s,!0)},t.prototype.uploadData=function(){return this.data_},t}();function gv(t,e){return-1!==t.indexOf(e)}var vv=function(){return function(t,e,n,r){this.url=t,this.method=e,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 bv(t){if(!t)throw pg()}function _v(t,e){return function(n,r){var i=iv(t,r,e);return bv(null!==i),i}}function wv(t){return function(e,n){var r,i,o;return 401===e.getStatus()?r=new hg(lg.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(o=t.bucket,r=new hg(lg.QUOTA_EXCEEDED,"Quota for bucket '"+o+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(i=t.path,r=new hg(lg.UNAUTHORIZED,"User does not have permission to access '"+i+"'.")):r=n,r.setServerResponseProp(n.serverResponseProp()),r}}function Ev(t){var e=wv(t);return function(n,r){var i,o=e(n,r);return 404===n.getStatus()&&(i=t.path,o=new hg(lg.OBJECT_NOT_FOUND,"Object '"+i+"' does not exist.")),o.setServerResponseProp(r.serverResponseProp()),o}}function Tv(t,e,n){var r=Xg(e.fullServerUrl()),i=t.maxOperationRetryTime(),o=new vv(r,"GET",_v(t,n),i);return o.errorHandler=Ev(e),o}function Sv(t,e,n){var r=Xg(e.fullServerUrl()),i=t.maxOperationRetryTime(),o=new vv(r,"GET",function(t,e){return function(n,r){var i=iv(t,r,e);return bv(null!==i),ov(i,r)}}(t,n),i);return o.errorHandler=Ev(e),o}function Iv(t,e,n){var r=Lg(n);return r.fullPath=t.path,r.size=e.size(),r.contentType||(r.contentType=function(t,e){return t&&t.contentType||e&&e.type()||"application/octet-stream"}(null,e)),r}var Cv=function(){return function(t,e,n,r){this.current=t,this.total=e,this.finalized=!!n,this.metadata=r||null}}();function Nv(t,e){var n;try{n=t.getResponseHeader("X-Goog-Upload-Status")}catch(t){bv(!1)}return bv(gv(e||["active"],n)),n}function Dv(t,e,n,r,i,o,s,a){var u=new Cv(0,0);if(s?(u.current=s.current,u.total=s.total):(u.current=0,u.total=r.size()),r.size()!==u.total)throw new hg(lg.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var c=u.total-u.current,h=c;i>0&&(h=Math.min(h,i));var l=u.current,f=l+h,p={"X-Goog-Upload-Command":h===c?"upload, finalize":"upload","X-Goog-Upload-Offset":u.current},d=r.slice(l,f);if(null===d)throw yg();var y=e.maxUploadRetryTime(),m=new vv(n,"POST",function(t,n){var i,s=Nv(t,["active","final"]),a=u.current+h,c=r.size();return i="final"===s?_v(e,o)(t,n):null,new Cv(a,c,"final"===s,i)},y);return m.headers=p,m.body=d.uploadData(),m.progressCallback=a||null,m.errorHandler=wv(t),m}var Av=function(){return function(t,e,n){if(qg(t)||Fg(e)||Fg(n))this.next=t,this.error=e||null,this.complete=n||null;else{var r=t;this.next=r.next||null,this.error=r.error||null,this.complete=r.complete||null}}}(),kv=function(){return function(t,e,n,r,i,o){this.bytesTransferred=t,this.totalBytes=e,this.state=n,this.metadata=r,this.task=i,this.ref=o}}();function Rv(t){return function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];xg(!0).then(function(){t.apply(null,e)})}}var Ov=function(){function t(t,e,n,r,i,o){void 0===o&&(o=null);var s=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_=t,this.authWrapper_=e,this.location_=n,this.blob_=i,this.metadata_=o,this.mappings_=r,this.resumable_=this.shouldDoResumable_(this.blob_),this.state_=Ag.RUNNING,this.errorHandler_=function(t){s.request_=null,s.chunkMultiplier_=1,t.codeEquals(lg.CANCELED)?(s.needToFetchStatus_=!0,s.completeTransitions_()):(s.error_=t,s.transition_(Ag.ERROR))},this.metadataErrorHandler_=function(t){s.request_=null,t.codeEquals(lg.CANCELED)?s.completeTransitions_():(s.error_=t,s.transition_(Ag.ERROR))},this.promise_=Mg(function(t,e){s.resolve_=t,s.reject_=e,s.start_()}),this.promise_.then(null,function(){})}return t.prototype.makeProgressCallback_=function(){var t=this,e=this.transferred_;return function(n,r){t.updateProgress_(e+n)}},t.prototype.shouldDoResumable_=function(t){return t.size()>262144},t.prototype.start_=function(){this.state_===Ag.RUNNING&&null===this.request_&&(this.resumable_?null===this.uploadUrl_?this.createResumable_():this.needToFetchStatus_?this.fetchStatus_():this.needToFetchMetadata_?this.fetchMetadata_():this.continueUpload_():this.oneShotUpload_())},t.prototype.resolveToken_=function(t){var e=this;this.authWrapper_.getAuthToken().then(function(n){switch(e.state_){case Ag.RUNNING:t(n);break;case Ag.CANCELING:e.transition_(Ag.CANCELED);break;case Ag.PAUSING:e.transition_(Ag.PAUSED)}})},t.prototype.createResumable_=function(){var t=this;this.resolveToken_(function(e){var n=function(t,e,n,r,i){var o=e.bucketOnlyServerUrl(),s=Iv(e,r,i),a={name:s.fullPath},u=Jg(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":s.contentType,"Content-Type":"application/json; charset=utf-8"},h=sv(s,n),l=t.maxUploadRetryTime(),f=new vv(u,"POST",function(t,e){var n;Nv(t);try{n=t.getResponseHeader("X-Goog-Upload-URL")}catch(t){bv(!1)}return bv(Wg(n)),n},l);return f.urlParams=a,f.headers=c,f.body=h,f.errorHandler=wv(e),f}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.uploadUrl_=e,t.needToFetchStatus_=!1,t.completeTransitions_()},t.errorHandler_)})},t.prototype.fetchStatus_=function(){var t=this,e=this.uploadUrl_;this.resolveToken_(function(n){var r=function(t,e,n,r){var i=t.maxUploadRetryTime(),o=new vv(n,"POST",function(t,e){var n,i=Nv(t,["active","final"]);try{n=t.getResponseHeader("X-Goog-Upload-Size-Received")}catch(t){bv(!1)}var o=parseInt(n,10);return bv(!isNaN(o)),new Cv(o,r.size(),"final"===i)},i);return o.headers={"X-Goog-Upload-Command":"query"},o.errorHandler=wv(e),o}(t.authWrapper_,t.location_,e,t.blob_),i=t.authWrapper_.makeRequest(r,n);t.request_=i,i.getPromise().then(function(e){e=e,t.request_=null,t.updateProgress_(e.current),t.needToFetchStatus_=!1,e.finalized&&(t.needToFetchMetadata_=!0),t.completeTransitions_()},t.errorHandler_)})},t.prototype.continueUpload_=function(){var t=this,e=262144*this.chunkMultiplier_,n=new Cv(this.transferred_,this.blob_.size()),r=this.uploadUrl_;this.resolveToken_(function(i){var o;try{o=Dv(t.location_,t.authWrapper_,r,t.blob_,e,t.mappings_,n,t.makeProgressCallback_())}catch(e){return t.error_=e,void t.transition_(Ag.ERROR)}var s=t.authWrapper_.makeRequest(o,i);t.request_=s,s.getPromise().then(function(e){t.increaseMultiplier_(),t.request_=null,t.updateProgress_(e.current),e.finalized?(t.metadata_=e.metadata,t.transition_(Ag.SUCCESS)):t.completeTransitions_()},t.errorHandler_)})},t.prototype.increaseMultiplier_=function(){262144*this.chunkMultiplier_<33554432&&(this.chunkMultiplier_*=2)},t.prototype.fetchMetadata_=function(){var t=this;this.resolveToken_(function(e){var n=Tv(t.authWrapper_,t.location_,t.mappings_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.metadata_=e,t.transition_(Ag.SUCCESS)},t.metadataErrorHandler_)})},t.prototype.oneShotUpload_=function(){var t=this;this.resolveToken_(function(e){var n=function(t,e,n,r,i){var o=e.bucketOnlyServerUrl(),s={"X-Goog-Upload-Protocol":"multipart"},a=function(){for(var t="",e=0;e<2;e++)t+=Math.random().toString().slice(2);return t}();s["Content-Type"]="multipart/related; boundary="+a;var u=Iv(e,r,i),c="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+sv(u,n)+"\r\n--"+a+"\r\nContent-Type: "+u.contentType+"\r\n\r\n",h="\r\n--"+a+"--",l=mv.getBlob(c,r,h);if(null===l)throw yg();var f={name:u.fullPath},p=Jg(o),d=t.maxUploadRetryTime(),y=new vv(p,"POST",_v(t,n),d);return y.urlParams=f,y.headers=s,y.body=l.uploadData(),y.errorHandler=wv(e),y}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.metadata_=e,t.updateProgress_(t.blob_.size()),t.transition_(Ag.SUCCESS)},t.errorHandler_)})},t.prototype.updateProgress_=function(t){var e=this.transferred_;this.transferred_=t,this.transferred_!==e&&this.notifyObservers_()},t.prototype.transition_=function(t){if(this.state_!==t)switch(t){case Ag.CANCELING:case Ag.PAUSING:this.state_=t,null!==this.request_&&this.request_.cancel();break;case Ag.RUNNING:var e=this.state_===Ag.PAUSED;this.state_=t,e&&(this.notifyObservers_(),this.start_());break;case Ag.PAUSED:this.state_=t,this.notifyObservers_();break;case Ag.CANCELED:this.error_=dg(),this.state_=t,this.notifyObservers_();break;case Ag.ERROR:case Ag.SUCCESS:this.state_=t,this.notifyObservers_()}},t.prototype.completeTransitions_=function(){switch(this.state_){case Ag.PAUSING:this.transition_(Ag.PAUSED);break;case Ag.CANCELING:this.transition_(Ag.CANCELED);break;case Ag.RUNNING:this.start_()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=Rg(this.state_);return new kv(this.transferred_,this.blob_.size(),t,this.metadata_,this,this.ref_)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){void 0===e&&(e=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=dv(!0).validator,s=pv(null,!0).validator;function a(t){try{return void o(t)}catch(t){}try{if(s(t),!(Ug(t.next)||Ug(t.error)||Ug(t.complete)))throw"";return}catch(t){throw i}}uv("on",[hv(function(e){if(t!==Dg.STATE_CHANGED)throw"Expected one of the event types: ["+Dg.STATE_CHANGED+"]."}),pv(a,!0),dv(!0),dv(!0)],arguments);var u=this;function c(t){return function(e,n,i){null!==t&&uv("on",t,arguments);var o=new Av(e,n,r);return u.addObserver_(o),function(){u.removeObserver_(o)}}}var h=[pv(function(t){if(null===t)throw i;a(t)}),dv(!0),dv(!0)];return!(Ug(e)||Ug(n)||Ug(r))?c(h):c(null)(e,n,r)},t.prototype.then=function(t,e){return this.promise_.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.addObserver_=function(t){this.observers_.push(t),this.notifyObserver_(t)},t.prototype.removeObserver_=function(t){var e,n,r;e=this.observers_,n=t,-1!==(r=e.indexOf(n))&&e.splice(r,1)},t.prototype.notifyObservers_=function(){var t,e=this;this.finishPromise_(),(t=this.observers_,Array.prototype.slice.call(t)).forEach(function(t){e.notifyObserver_(t)})},t.prototype.finishPromise_=function(){if(null!==this.resolve_){var t=!0;switch(Rg(this.state_)){case kg.SUCCESS:Rv(this.resolve_.bind(null,this.snapshot))();break;case kg.CANCELED:case kg.ERROR:Rv(this.reject_.bind(null,this.error_))();break;default:t=!1}t&&(this.resolve_=null,this.reject_=null)}},t.prototype.notifyObserver_=function(t){switch(Rg(this.state_)){case kg.RUNNING:case kg.PAUSED:null!==t.next&&Rv(t.next.bind(t,this.snapshot))();break;case kg.SUCCESS:null!==t.complete&&Rv(t.complete.bind(t))();break;case kg.CANCELED:case kg.ERROR:null!==t.error&&Rv(t.error.bind(t,this.error_))();break;default:null!==t.error&&Rv(t.error.bind(t,this.error_))()}},t.prototype.resume=function(){uv("resume",[],arguments);var t=this.state_===Ag.PAUSED||this.state_===Ag.PAUSING;return t&&this.transition_(Ag.RUNNING),t},t.prototype.pause=function(){uv("pause",[],arguments);var t=this.state_===Ag.RUNNING;return t&&this.transition_(Ag.PAUSING),t},t.prototype.cancel=function(){uv("cancel",[],arguments);var t=this.state_===Ag.RUNNING||this.state_===Ag.PAUSING;return t&&this.transition_(Ag.CANCELING),t},t}(),Pv=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof zg?e:zg.makeFromUrl(e)}return t.prototype.toString=function(){return uv("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return nv()},t.prototype.child=function(t){uv("child",[hv()],arguments);var e=function(t,e){var n=e.split("/").filter(function(t){return t.length>0}).join("/");return 0===t.length?n:t+"/"+n}(this.location.path,t),n=new zg(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=function(t){if(0==t.length)return null;var e=t.lastIndexOf("/");return-1===e?"":t.slice(0,e)}(this.location.path);if(null===t)return null;var e=new zg(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new zg(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return Yg(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(t,e){return void 0===e&&(e=null),uv("put",[new cv(function(t){if(!(t instanceof Uint8Array||t instanceof ArrayBuffer||Kg()&&t instanceof Blob))throw"Expected Blob or File."}),lv(!0)],arguments),this.throwIfRoot_("put"),new Ov(this,this.authWrapper,this.location,this.mappings(),new mv(t),e)},t.prototype.putString=function(t,e,n){void 0===e&&(e=_g.RAW),uv("putString",[hv(),hv(wg,!0),lv(!0)],arguments),this.throwIfRoot_("putString");var r=Tg(e,t),i=Lg(n);return!Fg(i.contentType)&&Fg(r.contentType)&&(i.contentType=r.contentType),new Ov(this,this.authWrapper,this.location,this.mappings(),new mv(r.data,!0),i)},t.prototype.delete=function(){uv("delete",[],arguments),this.throwIfRoot_("delete");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=function(t,e){var n=Xg(e.fullServerUrl()),r=t.maxOperationRetryTime(),i=new vv(n,"DELETE",function(t,e){},r);return i.successCodes=[200,204],i.errorHandler=Ev(e),i}(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.getMetadata=function(){uv("getMetadata",[],arguments),this.throwIfRoot_("getMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Tv(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){uv("updateMetadata",[lv()],arguments),this.throwIfRoot_("updateMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=function(t,e,n,r){var i=Xg(e.fullServerUrl()),o=sv(n,r),s=t.maxOperationRetryTime(),a=new vv(i,"PATCH",_v(t,r),s);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=o,a.errorHandler=Ev(e),a}(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){uv("getDownloadURL",[],arguments),this.throwIfRoot_("getDownloadURL");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Sv(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise().then(function(t){if(null===t)throw new hg(lg.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return t})})},t.prototype.throwIfRoot_=function(t){if(""===this.location.path)throw function(t){return new hg(lg.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}(t)},t}(),Lv=function(){function t(t){this.promise_=function(t){return Promise.reject(t)}(t)}return t.prototype.getPromise=function(){return this.promise_},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),Mv=function(){function t(){this.map_={},this.id_=cg}return t.prototype.addRequest=function(t){var e=this.id_;this.id_++,this.map_[e]=t;var n=this;function r(){delete n.map_[e]}t.getPromise().then(r,r)},t.prototype.clear=function(){Pg(this.map_,function(t,e){e&&e.cancel(!0)}),this.map_={}},t}(),xv=function(){function t(e,n,r,i,o){if(this.bucket_=null,this.deleted_=!1,this.app_=e,null!==this.app_){var s=this.app_.options;Fg(s)&&(this.bucket_=t.extractBucket_(s))}this.storageRefMaker_=n,this.requestMaker_=r,this.pool_=o,this.service_=i,this.maxOperationRetryTime_=ag,this.maxUploadRetryTime_=ug,this.requestMap_=new Mv}return t.extractBucket_=function(t){var e=t.storageBucket||null;return null==e?null:zg.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.app_&&Fg(this.app_.INTERNAL)&&Fg(this.app_.INTERNAL.getToken)?this.app_.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(t){return null}):xg(null)},t.prototype.bucket=function(){if(this.deleted_)throw gg();return this.bucket_},t.prototype.service=function(){return this.service_},t.prototype.makeStorageReference=function(t){return this.storageRefMaker_(this,t)},t.prototype.makeRequest=function(t,e){if(this.deleted_)return new Lv(gg());var n=this.requestMaker_(t,e,this.pool_);return this.requestMap_.addRequest(n),n},t.prototype.deleteApp=function(){this.deleted_=!0,this.app_=null,this.requestMap_.clear()},t.prototype.maxUploadRetryTime=function(){return this.maxUploadRetryTime_},t.prototype.setMaxUploadRetryTime=function(t){this.maxUploadRetryTime_=t},t.prototype.maxOperationRetryTime=function(){return this.maxOperationRetryTime_},t.prototype.setMaxOperationRetryTime=function(t){this.maxOperationRetryTime_=t},t}();var Fv=function(){function t(t,e,n,r,i,o,s,a,u,c,h){this.pendingXhr_=null,this.backoffId_=null,this.resolve_=null,this.reject_=null,this.canceled_=!1,this.appDelete_=!1,this.url_=t,this.method_=e,this.headers_=n,this.body_=r,this.successCodes_=i.slice(),this.additionalRetryCodes_=o.slice(),this.callback_=s,this.errorCallback_=a,this.progressCallback_=c,this.timeout_=u,this.pool_=h;var l=this;this.promise_=Mg(function(t,e){l.resolve_=t,l.reject_=e,l.start_()})}return t.prototype.start_=function(){var t=this;function e(e,n){var r,i=t.resolve_,o=t.reject_,s=n.xhr;if(n.wasSuccessCode)try{var a=t.callback_(s,s.getResponseText());Ug(a)?i(a):i()}catch(t){o(t)}else null!==s?((r=pg()).setServerResponseProp(s.getResponseText()),t.errorCallback_?o(t.errorCallback_(s,r)):o(r)):n.canceled?o(r=t.appDelete_?gg():dg()):o(r=new hg(lg.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again."))}this.canceled_?e(0,new Uv(!1,null,!0)):this.backoffId_=function(t,e,n){var r=1,i=null,o=!1,s=0;function a(){return 2===s}var u=!1;function c(){u||(u=!0,e.apply(null,arguments))}function h(e){i=setTimeout(function(){i=null,t(l,a())},e)}function l(t){for(var e,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];u||(t?c.apply(null,arguments):a()||o?c.apply(null,arguments):(r<64&&(r*=2),1===s?(s=2,e=0):e=1e3*(r+Math.random()),h(e)))}var f=!1;function p(t){f||(f=!0,u||(null!==i?(t||(s=2),clearTimeout(i),h(0)):t||(s=1)))}return h(0),setTimeout(function(){o=!0,p(!0)},n),p}(function(e,n){if(n)e(!1,new Uv(!1,null,!0));else{var r=t.pool_.createXhrIo();t.pendingXhr_=r,null!==t.progressCallback_&&r.addUploadProgressListener(i),r.send(t.url_,t.method_,t.body_,t.headers_).then(function(n){null!==t.progressCallback_&&n.removeUploadProgressListener(i),t.pendingXhr_=null;var r=(n=n).getErrorCode()===Ng.NO_ERROR,o=n.getStatus();if(r&&!t.isRetryStatusCode_(o)){var s=gv(t.successCodes_,o);e(!0,new Uv(s,n))}else{var a=n.getErrorCode()===Ng.ABORT;e(!1,new Uv(!1,null,a))}})}function i(e){var n=e.loaded,r=e.lengthComputable?e.total:-1;null!==t.progressCallback_&&t.progressCallback_(n,r)}},e,this.timeout_)},t.prototype.getPromise=function(){return this.promise_},t.prototype.cancel=function(t){this.canceled_=!0,this.appDelete_=t||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingXhr_&&this.pendingXhr_.abort()},t.prototype.isRetryStatusCode_=function(t){var e=t>=500&&t<600,n=gv([408,429],t),r=gv(this.additionalRetryCodes_,t);return e||n||r},t}(),Uv=function(){return function(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n}}();function qv(t,e,n){var r=$g(t.urlParams),i=t.url+r,o=Lg(t.headers);return function(t,e){null!==e&&e.length>0&&(t.Authorization="Firebase "+e)}(o,e),function(t){var e=void 0!==Gn?Gn.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}(o),new Fv(i,t.method,o,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}var Bv=function(){function t(t,e,n){if(this.bucket_=null,this.authWrapper_=new xv(t,function(t,e){return new Pv(t,e)},qv,this,e),this.app_=t,null!=n)this.bucket_=zg.makeFromBucketSpec(n);else{var r=this.authWrapper_.bucket();null!=r&&(this.bucket_=new zg(r,""))}this.internals_=new Vv(this)}return t.prototype.ref=function(t){if(uv("ref",[hv(function(t){if(/^[A-Za-z]+:\/\//.test(t))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 e=new Pv(this.authWrapper_,this.bucket_);return null!=t?e.child(t):e},t.prototype.refFromURL=function(t){return uv("refFromURL",[hv(function(t){if(!/^[A-Za-z]+:\/\//.test(t))throw"Expected full URL but got a child path, use ref instead.";try{zg.makeFromUrl(t)}catch(t){throw"Expected valid full URL but got an invalid one."}},!1)],arguments),new Pv(this.authWrapper_,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.authWrapper_.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(t){uv("setMaxUploadRetryTime",[fv()],arguments),this.authWrapper_.setMaxUploadRetryTime(t)},Object.defineProperty(t.prototype,"maxOperationRetryTime",{get:function(){return this.authWrapper_.maxOperationRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxOperationRetryTime=function(t){uv("setMaxOperationRetryTime",[fv()],arguments),this.authWrapper_.setMaxOperationRetryTime(t)},Object.defineProperty(t.prototype,"app",{get:function(){return this.app_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.internals_},enumerable:!0,configurable:!0}),t}(),Vv=function(){function t(t){this.service_=t}return t.prototype.delete=function(){return this.service_.authWrapper_.deleteApp(),xg(void 0)},t}(),Wv="storage";function jv(t,e,n){return new Bv(t,new Hg,n)}return function(t){var e={TaskState:kg,TaskEvent:Dg,StringFormat:_g,Storage:Bv,Reference:Pv};t.INTERNAL.registerService(Wv,jv,e,void 0,!0)}(Gn),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"),Gn});