Няма описание
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12
  1. !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)}(this,function(gg,mg){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(gg);function n(t){const n=[];let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&s+1<t.length&&56320==(64512&t.charCodeAt(s+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++s)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}const r={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(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const s=[];for(let h=0;h<n.length;h+=3){var i=n[h],a=h+1<n.length,o=a?n[h+1]:0,u=h+2<n.length,c=u?n[h+2]:0;let e=(15&o)<<2|c>>6,t=63&c;u||(t=64,a||(e=64)),s.push(r[i>>2],r[(3&i)<<4|o>>4],r[e],r[t])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var s,i,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(s=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&s)):239<a&&a<365?(i=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(i>>10)),t[r++]=String.fromCharCode(56320+(1023&i))):(s=e[n++],i=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&s)<<6|63&i))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let u=0;u<e.length;){var s=n[e.charAt(u++)],i=u<e.length?n[e.charAt(u)]:0;++u;var a=u<e.length?n[e.charAt(u)]:64;++u;var o=u<e.length?n[e.charAt(u)]:64;if(++u,null==s||null==i||null==a||null==o)throw Error();r.push(s<<2|i>>4),64!==a&&(r.push(i<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},a=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const s=()=>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.")}().__FIREBASE_DEFAULTS__,i=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)}},o=()=>{try{return s()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||i()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}};function u(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function c(){return!function(){var e=null===(e=o())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return 1;if("browser"!==e)try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return}}()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class h extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,h.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,d.prototype.create)}}class d{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},s=`${this.service}/${e}`,i=this.errors[e],i=i?(r=n,i.replace(f,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",i=`${this.serviceName}: ${i} (${s}).`;return new h(s,i,n)}}const f=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class g{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}(gd=l=l||{})[gd.DEBUG=0]="DEBUG",gd[gd.VERBOSE=1]="VERBOSE",gd[gd.INFO=2]="INFO",gd[gd.WARN=3]="WARN",gd[gd.ERROR=4]="ERROR",gd[gd.SILENT=5]="SILENT";const p={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},y=l.INFO,v={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},w=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),s=v[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${r}] ${e.name}:`,...n)}};var I,b="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},E={},T=b||self;function _(){}function S(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function x(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var D="closure_uid_"+(1e9*Math.random()>>>0),A=0;function C(e,t,n){return e.call.apply(e.bind,arguments)}function N(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function k(e,t,n){return(k=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?C:N).apply(null,arguments)}function R(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function L(e,i){function t(){}t.prototype=i.prototype,e.X=i.prototype,e.prototype=new t,(e.prototype.constructor=e).Wb=function(e,t,n){for(var r=Array(arguments.length-2),s=2;s<arguments.length;s++)r[s-2]=arguments[s];return i.prototype[t].apply(e,r)}}function M(){this.s=this.s,this.o=this.o}M.prototype.s=!1,M.prototype.na=function(){var e;!this.s&&(this.s=!0,this.M(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,D)&&e[D]||(e[D]=++A))},M.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const F=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function O(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function V(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(S(n)){var r=t.length||0,s=n.length||0;t.length=r+s;for(let e=0;e<s;e++)t[r+e]=n[e]}else t.push(n)}}function P(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}P.prototype.h=function(){this.defaultPrevented=!0};var q=function(){if(!T.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{T.addEventListener("test",_,t),T.removeEventListener("test",_,t)}catch(e){}return e}();function B(e){return/^[\s\xa0]*$/.test(e)}var U=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function G(e,t){return e<t?-1:t<e?1:0}function K(){var e=T.navigator;return(e=e&&e.userAgent)?e:""}function j(e){return-1!=K().indexOf(e)}function $(e){return $[" "](e),e}$[" "]=_;var Q,z=j("Opera"),W=j("Trident")||j("MSIE"),H=j("Edge"),Y=H||W,X=j("Gecko")&&!(-1!=K().toLowerCase().indexOf("webkit")&&!j("Edge"))&&!(j("Trident")||j("MSIE"))&&!j("Edge"),J=-1!=K().toLowerCase().indexOf("webkit")&&!j("Edge");function Z(){var e=T.document;return e?e.documentMode:void 0}e:{var ee="",te=(te=K(),X?/rv:([^\);]+)(\)|;)/.exec(te):H?/Edge\/([\d\.]+)/.exec(te):W?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(te):J?/WebKit\/(\S+)/.exec(te):z?/(?:Version)[ \/]?(\S+)/.exec(te):void 0);if(te&&(ee=te?te[1]:""),W){te=Z();if(null!=te&&te>parseFloat(ee)){Q=String(te);break e}}Q=ee}var ne={};function re(){return e=function(){let e=0;var t=U(String(Q)).split("."),n=U("9").split("."),r=Math.max(t.length,n.length);for(let a=0;0==e&&a<r;a++)for(var s=t[a]||"",i=n[a]||"";s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],(0!=s[0].length||0!=i[0].length)&&(e=G(0==s[1].length?0:parseInt(s[1],10),0==i[1].length?0:parseInt(i[1],10))||G(0==s[2].length,0==i[2].length)||G(s[2],i[2]),s=s[3],i=i[3],0==e););return 0<=e},t=ne,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var se=T.document&&W&&(Z()||parseInt(Q,10))||void 0;function ie(e,t){if(P.call(this,e?e.type:""),this.relatedTarget=this.g=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.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(X){e:{try{$(t.nodeName);var s=!0;break e}catch(e){}s=!1}s||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:ae[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&ie.X.h.call(this)}}L(ie,P);var ae={2:"touch",3:"pen",4:"mouse"};ie.prototype.h=function(){ie.X.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var oe="closure_listenable_"+(1e6*Math.random()|0),ue=0;function ce(e,t,n,r,s){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=s,this.key=++ue,this.ba=this.ea=!1}function he(e){e.ba=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function le(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function de(e){const t={};for(const n in e)t[n]=e[n];return t}const fe="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ge(t){let n,r;for(let s=1;s<arguments.length;s++){for(n in r=arguments[s])t[n]=r[n];for(let e=0;e<fe.length;e++)n=fe[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function me(e){this.src=e,this.g={},this.h=0}function pe(e,t){var n,r,s,i=t.type;i in e.g&&(n=e.g[i],(s=0<=(r=F(n,t)))&&Array.prototype.splice.call(n,r,1),s&&(he(t),0==e.g[i].length&&(delete e.g[i],e.h--)))}function ye(e,t,n,r){for(var s=0;s<e.length;++s){var i=e[s];if(!i.ba&&i.listener==t&&i.capture==!!n&&i.ha==r)return s}return-1}me.prototype.add=function(e,t,n,r,s){var i=e.toString();(e=this.g[i])||(e=this.g[i]=[],this.h++);var a=ye(e,t,r,s);return-1<a?(t=e[a],n||(t.ea=!1)):((t=new ce(t,this.src,i,!!r,s)).ea=n,e.push(t)),t};var ve="closure_lm_"+(1e6*Math.random()|0),we={};function Ie(e,t,n,r,s){if(r&&r.once)return function e(t,n,r,s,i){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,s,i);return null}r=De(r);return t&&t[oe]?t.O(n,r,x(s)?!!s.capture:!!s,i):be(t,n,r,!0,s,i)}(e,t,n,r,s);if(Array.isArray(t)){for(var i=0;i<t.length;i++)Ie(e,t[i],n,r,s);return null}return n=De(n),e&&e[oe]?e.N(t,n,x(r)?!!r.capture:!!r,s):be(e,t,n,!1,r,s)}function be(e,t,n,r,s,i){if(!t)throw Error("Invalid event type");var a=x(s)?!!s.capture:!!s,o=Se(e);if(o||(e[ve]=o=new me(e)),(n=o.add(t,n,r,a,i)).proxy)return n;if(r=function(){const n=_e;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(s=!q?a:s)&&(s=!1),e.addEventListener(t.toString(),r,s);else if(e.attachEvent)e.attachEvent(Te(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Ee(e){var t,n,r;"number"!=typeof e&&e&&!e.ba&&((t=e.src)&&t[oe]?pe(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(Te(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Se(t))?(pe(n,e),0==n.h&&(n.src=null,t[ve]=null)):he(e)))}function Te(e){return e in we?we[e]:we[e]="on"+e}function _e(e,t){var n,r;return e=!!e.ba||(t=new ie(t,this),n=e.listener,r=e.ha||e.src,e.ea&&Ee(e),n.call(r,t))}function Se(e){return(e=e[ve])instanceof me?e:null}var xe="__closure_events_fn_"+(1e9*Math.random()>>>0);function De(t){return"function"==typeof t?t:(t[xe]||(t[xe]=function(e){return t.handleEvent(e)}),t[xe])}function Ae(){M.call(this),this.i=new me(this),(this.P=this).I=null}function Ce(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new P(t,e):t instanceof P?t.target=t.target||e:(a=t,ge(t=new P(r,e),a)),a=!0,n)for(var s=n.length-1;0<=s;s--)var i=t.g=n[s],a=Ne(i,r,!0,t)&&a;if(a=Ne(i=t.g=e,r,!0,t)&&a,a=Ne(i,r,!1,t)&&a,n)for(s=0;s<n.length;s++)a=Ne(i=t.g=n[s],r,!1,t)&&a}function Ne(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var s=!0,i=0;i<t.length;++i){var a,o,u=t[i];u&&!u.ba&&u.capture==n&&(a=u.listener,o=u.ha||u.src,u.ea&&pe(e.i,u),s=!1!==a.call(o,r)&&s)}return s&&!r.defaultPrevented}L(Ae,M),Ae.prototype[oe]=!0,Ae.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,s,i){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,s,i);else s=x(s)?!!s.capture:!!s,r=De(r),t&&t[oe]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=ye(a=t.g[n],r,s,i))&&(he(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&Se(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?ye(n,r,s,i):t)?n[t]:null)&&Ee(r))}(this,e,t,n,r)},Ae.prototype.M=function(){if(Ae.X.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)he(n[r]);delete t.g[e],t.h--}}this.I=null},Ae.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Ae.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var ke=T.JSON.stringify;var Re,Le=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new Me,e=>e.reset());class Me{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function Fe(e,t){var n;Re||(n=T.Promise.resolve(void 0),Re=function(){n.then(Pe)}),Oe||(Re(),Oe=!0),Ve.add(e,t)}var Oe=!1,Ve=new class{constructor(){this.h=this.g=null}add(e,t){const n=Le.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function Pe(){for(var e;e=function(){var e=Ve;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){T.setTimeout(()=>{throw e},0)}(e)}var t=Le;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Oe=!1}function qe(e,t){Ae.call(this),this.h=e||1,this.g=t||T,this.j=k(this.lb,this),this.l=Date.now()}function Be(e){e.ca=!1,e.R&&(e.g.clearTimeout(e.R),e.R=null)}function Ue(e,t,n){if("function"==typeof e)n&&(e=k(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=k(e.handleEvent,e)}return 2147483647<Number(t)?-1:T.setTimeout(e,t||0)}L(qe,Ae),(I=qe.prototype).ca=!1,I.R=null,I.lb=function(){var e;this.ca&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.R=this.g.setTimeout(this.j,this.h-e):(this.R&&(this.g.clearTimeout(this.R),this.R=null),Ce(this,"tick"),this.ca&&(Be(this),this.start())))},I.start=function(){this.ca=!0,this.R||(this.R=this.g.setTimeout(this.j,this.h),this.l=Date.now())},I.M=function(){qe.X.M.call(this),Be(this),delete this.g};class Ge extends M{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=Ue(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(T.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Ke(e){M.call(this),this.h=e,this.g={}}L(Ke,M);var je=[];function $e(e,t,n,r){Array.isArray(n)||(n&&(je[0]=n.toString()),n=je);for(var s=0;s<n.length;s++){var i=Ie(t,n[s],r||e.handleEvent,!1,e.h||e);if(!i)break;e.g[i.key]=i}}function Qe(e){le(e.g,function(e,t){this.g.hasOwnProperty(t)&&Ee(e)},e),e.g={}}function ze(){this.g=!0}function We(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var s=r[1];if(Array.isArray(s)&&!(s.length<1)){var i=s[0];if("noop"!=i&&"stop"!=i&&"close"!=i)for(var a=1;a<s.length;a++)s[a]=""}}}return ke(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Ke.prototype.M=function(){Ke.X.M.call(this),Qe(this)},Ke.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},ze.prototype.Aa=function(){this.g=!1},ze.prototype.info=function(){};var He={},Ye=null;function Xe(){return Ye=Ye||new Ae}function Je(e){P.call(this,He.Pa,e)}function Ze(){var e=Xe();Ce(e,new Je(e))}function et(e,t){P.call(this,He.STAT_EVENT,e),this.stat=t}function tt(e){var t=Xe();Ce(t,new et(t,e))}function nt(e,t){P.call(this,He.Qa,e),this.size=t}function rt(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return T.setTimeout(function(){e()},t)}He.Pa="serverreachability",L(Je,P),He.STAT_EVENT="statevent",L(et,P),He.Qa="timingevent",L(nt,P);var st={NO_ERROR:0,mb:1,zb:2,yb:3,tb:4,xb:5,Ab:6,Ma:7,TIMEOUT:8,Db:9},it={rb:"complete",Nb:"success",Na:"error",Ma:"abort",Fb:"ready",Gb:"readystatechange",TIMEOUT:"timeout",Bb:"incrementaldata",Eb:"progress",ub:"downloadprogress",Vb:"uploadprogress"};function at(){}function ot(e){return e.h||(e.h=e.i())}function ut(){}at.prototype.h=null;b={OPEN:"a",qb:"b",Na:"c",Cb:"d"};function ct(){P.call(this,"d")}function ht(){P.call(this,"c")}function lt(){}function dt(e,t,n,r){this.l=e,this.j=t,this.m=n,this.U=r||1,this.S=new Ke(this),this.O=mt,this.T=new qe(e=Y?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.V=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.Y=-1,this.I=!1,this.N=0,this.L=null,this.$=this.J=this.Z=this.P=!1,this.h=new ft}function ft(){this.i=null,this.g="",this.h=!1}L(ct,P),L(ht,P),L(lt,at),lt.prototype.g=function(){return new XMLHttpRequest},lt.prototype.i=function(){return{}};var gt=new lt,mt=45e3,pt={},yt={};function vt(e,t,n){e.K=1,e.v=Ot(kt(t)),e.s=n,e.P=!0,wt(e,null)}function wt(e,t){e.F=Date.now(),Et(e),e.A=kt(e.v);var a,o,u,c,h,l,n=e.A,r=e.U;Array.isArray(r)||(r=[String(r)]),Ht(n.i,"t",r),e.C=0,n=e.l.H,e.h=new ft,e.g=Hn(e.l,n?t:null,!e.s),0<e.N&&(e.L=new Ge(k(e.La,e,e.g),e.N)),$e(e.S,e.g,"readystatechange",e.ib),t=e.H?de(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.da(e.A,e.u,e.s,t)):(e.u="GET",e.g.da(e.A,e.u,null,t)),Ze(),a=e.j,o=e.u,u=e.A,c=e.m,h=e.U,l=e.s,a.info(function(){if(a.g)if(l)for(var e="",t=l.split("&"),n=0;n<t.length;n++){var r,s,i=t[n].split("=");1<i.length&&(r=i[0],i=i[1],e=2<=(s=r.split("_")).length&&"type"==s[1]?e+(r+"=")+i+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+c+") [attempt "+h+"]: "+o+"\n"+u+"\n"+e})}function It(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Da)}function bt(e,t,n){let r=!0,s;for(;!e.I&&e.C<n.length;){if(s=(a=n,u=o=void 0,o=(i=e).C,-1==(u=a.indexOf("\n",o))?yt:(o=Number(a.substring(o,u)),isNaN(o)?pt:(u+=1)+o>a.length?yt:(a=a.substr(u,o),i.C=u+o,a))),s==yt){4==t&&(e.o=4,tt(14),r=!1),We(e.j,e.m,null,"[Incomplete Response]");break}if(s==pt){e.o=4,tt(15),We(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}We(e.j,e.m,s,null),Dt(e,s)}var i,a,o,u;It(e)&&s!=yt&&s!=pt&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,tt(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.$&&(e.$=!0,(t=e.l).g==e&&t.$&&!t.K&&(t.j.info("Great, no buffering proxy detected. Bytes received: "+n.length),Un(t),t.K=!0,tt(11))):(We(e.j,e.m,n,"[Invalid Chunked Response]"),xt(e),St(e))}function Et(e){e.V=Date.now()+e.O,Tt(e,e.O)}function Tt(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=rt(k(e.gb,e),t)}function _t(e){e.B&&(T.clearTimeout(e.B),e.B=null)}function St(e){0==e.l.G||e.I||jn(e.l,e)}function xt(e){_t(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,Be(e.T),Qe(e.S),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function Dt(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||nn(n.h,e)))if(!e.J&&nn(n.h,e)&&3==n.G){try{var r=n.Fa.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var s=r;if(0==s[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Kn(n),Ln(n)}Bn(n),tt(18)}}else n.Ba=s[1],0<n.Ba-n.T&&s[2]<37500&&n.L&&0==n.A&&!n.v&&(n.v=rt(k(n.cb,n),6e3));if(tn(n.h)<=1&&n.ja){try{n.ja()}catch(e){}n.ja=void 0}}else Qn(n,11)}else if(!e.J&&n.g!=e||Kn(n),!B(t))for(s=n.Fa.g.parse(t),t=0;t<s.length;t++){var i=s[t];if(n.T=i[0],i=i[1],2==n.G)if("c"==i[0]){n.I=i[1],n.ka=i[2];var a=i[3];null!=a&&(n.ma=a,n.j.info("VER="+n.ma));var o=i[4];null!=o&&(n.Ca=o,n.j.info("SVER="+n.Ca));var u,c,h=i[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.J=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const g=e.g;if(g){const m=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null;m&&((u=r.h).g||-1==m.indexOf("spdy")&&-1==m.indexOf("quic")&&-1==m.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(rn(u,u.h),u.h=null))),!r.D||(c=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.za=c,Ft(r.F,r.D,c))}n.G=3,n.l&&n.l.xa(),n.$&&(n.P=Date.now()-e.F,n.j.info("Handshake RTT: "+n.P+"ms"));var l,d,f=e;(r=n).sa=Wn(r,r.H?r.ka:null,r.V),f.J?(sn(r.h,f),l=f,(d=r.J)&&l.setTimeout(d),l.B&&(_t(l),Et(l)),r.g=f):qn(r),0<n.i.length&&Fn(n)}else"stop"!=i[0]&&"close"!=i[0]||Qn(n,7);else 3==n.G&&("stop"==i[0]||"close"==i[0]?"stop"==i[0]?Qn(n,7):Rn(n):"noop"!=i[0]&&n.l&&n.l.wa(i),n.A=0)}Ze()}catch(e){}}function At(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(S(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.oa&&"function"==typeof e.oa)return e.oa();if(!e.W||"function"!=typeof e.W){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(S(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.W&&"function"==typeof e.W)return e.W();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(S(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),s=r.length,i=0;i<s;i++)t.call(void 0,r[i],n&&n[i],e)}(I=dt.prototype).setTimeout=function(e){this.O=e},I.ib=function(e){e=e.target;const t=this.L;t&&3==xn(e)?t.l():this.La(e)},I.La=function(e){try{if(e==this.g)e:{var t=xn(this.g),n=this.g.Ea();this.g.aa();if(!(t<3)&&(3!=t||Y||this.g&&(this.h.h||this.g.fa()||Dn(this.g)))){this.I||4!=t||7==n||Ze(),_t(this);var r=this.g.aa();this.Y=r;t:if(It(this)){var s=Dn(this.g);e="";var i=s.length,a=4==xn(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){xt(this),St(this);var o="";break t}this.h.i=new T.TextDecoder}for(n=0;n<i;n++)this.h.h=!0,e+=this.h.i.decode(s[n],{stream:a&&n==i-1});s.splice(0,i),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.fa();if(this.i=200==r,l=this.j,d=this.u,f=this.A,g=this.m,m=this.U,p=t,y=r,l.info(function(){return"XMLHTTP RESP ("+g+") [ attempt "+m+"]: "+d+"\n"+f+"\n"+p+" "+y}),this.i){if(this.Z&&!this.J){t:{if(this.g){var u,c=this.g;if((u=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!B(u)){var h=u;break t}}h=null}if(!(r=h)){this.i=!1,this.o=3,tt(12),xt(this),St(this);break e}We(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,Dt(this,r)}this.P?(bt(this,t,o),Y&&this.i&&3==t&&($e(this.S,this.T,"tick",this.hb),this.T.start())):(We(this.j,this.m,o,null),Dt(this,o)),4==t&&xt(this),this.i&&!this.I&&(4==t?jn(this.l,this):(this.i=!1,Et(this)))}else 400==r&&0<o.indexOf("Unknown SID")?(this.o=3,tt(12)):(this.o=0,tt(13)),xt(this),St(this)}}}catch(e){}var l,d,f,g,m,p,y},I.hb=function(){var e,t;this.g&&(e=xn(this.g),t=this.g.fa(),this.C<t.length&&(_t(this),bt(this,e,t),this.i&&4!=e&&Et(this)))},I.cancel=function(){this.I=!0,xt(this)},I.gb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.V?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.K&&(Ze(),tt(17)),xt(this),this.o=2,St(this)):Tt(this,this.V-n)};var Ct=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Nt(e,t){var n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof Nt?(this.h=void 0!==t?t:e.h,Rt(this,e.j),this.s=e.s,this.g=e.g,Lt(this,e.m),this.l=e.l,t=e.i,(n=new $t).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Mt(this,n),this.o=e.o):e&&(n=String(e).match(Ct))?(this.h=!!t,Rt(this,n[1]||"",!0),this.s=Vt(n[2]||""),this.g=Vt(n[3]||"",!0),Lt(this,n[4]),this.l=Vt(n[5]||"",!0),Mt(this,n[6]||"",!0),this.o=Vt(n[7]||"")):(this.h=!!t,this.i=new $t(null,this.h))}function kt(e){return new Nt(e)}function Rt(e,t,n){e.j=n?Vt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Lt(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function Mt(e,t,n){var r,s;t instanceof $t?(e.i=t,r=e.i,(s=e.h)&&!r.j&&(Qt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(zt(this,t),Ht(this,n,e))},r)),r.j=s):(n||(t=Pt(t,Kt)),e.i=new $t(t,e.h))}function Ft(e,t,n){e.i.set(t,n)}function Ot(e){return Ft(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Vt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Pt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,qt),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function qt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Nt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Pt(t,Bt,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Pt(t,Bt,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Pt(n,"/"==n.charAt(0)?Gt:Ut,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Pt(n,jt)),e.join("")};var Bt=/[#\/\?@]/g,Ut=/[#\?:]/g,Gt=/[#\?]/g,Kt=/[#\?@]/g,jt=/#/g;function $t(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Qt(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,s=e[n].indexOf("="),i=null;0<=s?(r=e[n].substring(0,s),i=e[n].substring(s+1)):r=e[n],t(r,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function zt(e,t){Qt(e),t=Yt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Wt(e,t){return Qt(e),t=Yt(e,t),e.g.has(t)}function Ht(e,t,n){zt(e,t),0<n.length&&(e.i=null,e.g.set(Yt(e,t),O(n)),e.h+=n.length)}function Yt(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(I=$t.prototype).add=function(e,t){Qt(this),this.i=null,e=Yt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},I.forEach=function(n,r){Qt(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},I.oa=function(){Qt(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let i=0;i<n.length;i++){var s=t[i];for(let e=0;e<s.length;e++)r.push(n[i])}return r},I.W=function(t){Qt(this);let n=[];if("string"==typeof t)Wt(this,t)&&(n=n.concat(this.g.get(Yt(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},I.set=function(e,t){return Qt(this),this.i=null,Wt(this,e=Yt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},I.get=function(e,t){return e&&0<(e=this.W(e)).length?String(e[0]):t},I.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],s=encodeURIComponent(String(r)),i=this.W(r),r=0;r<i.length;r++){var a=s;""!==i[r]&&(a+="="+encodeURIComponent(String(i[r]))),e.push(a)}return this.i=e.join("&")};var Xt=class{constructor(e,t){this.h=e,this.g=t}};function Jt(e){this.l=e||10,e=T.PerformanceNavigationTiming?0<(e=T.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(T.g&&T.g.Ga&&T.g.Ga()&&T.g.Ga().$b),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var Zt;function en(e){return e.h||e.g&&e.g.size>=e.j}function tn(e){return e.h?1:e.g?e.g.size:0}function nn(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function rn(e,t){e.g?e.g.add(t):e.h=t}function sn(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function an(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return O(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function on(){}function un(){this.g=new on}function cn(e,t,n,r,s){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,s(r)}catch(e){}}function hn(e){this.l=e.ac||null,this.j=e.jb||!1}function ln(e,t){Ae.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=dn,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Jt.prototype.cancel=function(){if(this.i=an(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},on.prototype.stringify=function(e){return T.JSON.stringify(e,void 0)},on.prototype.parse=function(e){return T.JSON.parse(e,void 0)},L(hn,at),hn.prototype.g=function(){return new ln(this.l,this.j)},hn.prototype.i=(Zt={},function(){return Zt}),L(ln,Ae);var dn=0;function fn(e){e.j.read().then(e.Ta.bind(e)).catch(e.ga.bind(e))}function gn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,mn(e)}function mn(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(I=ln.prototype).open=function(e,t){if(this.readyState!=dn)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,mn(this)},I.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||T).fetch(new Request(this.B,t)).then(this.Wa.bind(this),this.ga.bind(this))},I.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,gn(this)),this.readyState=dn},I.Wa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,mn(this)),this.g&&(this.readyState=3,mn(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ua.bind(this),this.ga.bind(this));else if(void 0!==T.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;fn(this)}else e.text().then(this.Va.bind(this),this.ga.bind(this))},I.Ta=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?gn:mn)(this),3==this.readyState&&fn(this))},I.Va=function(e){this.g&&(this.response=this.responseText=e,gn(this))},I.Ua=function(e){this.g&&(this.response=e,gn(this))},I.ga=function(){this.g&&gn(this)},I.setRequestHeader=function(e,t){this.v.append(e,t)},I.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},I.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(ln.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var pn=T.JSON.parse;function yn(e){Ae.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=vn,this.K=this.L=!1}L(yn,Ae);var vn="",wn=/^https?$/i,In=["POST","PUT"];function bn(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,En(e),_n(e)}function En(e){e.D||(e.D=!0,Ce(e,"complete"),Ce(e,"error"))}function Tn(e){if(e.h&&void 0!==E&&(!e.C[1]||4!=xn(e)||2!=e.aa()))if(e.v&&4==xn(e))Ue(e.Ha,0,e);else if(Ce(e,"readystatechange"),4==xn(e)){e.h=!1;try{var t,n,r,s,i=e.aa();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var a=!0;break e;default:a=!1}if((t=a)||((n=0===i)&&(!(s=String(e.H).match(Ct)[1]||null)&&T.self&&T.self.location&&(s=(r=T.self.location.protocol).substr(0,r.length-1)),n=!wn.test(s?s.toLowerCase():"")),t=n),t)Ce(e,"complete"),Ce(e,"success");else{e.m=6;try{var o=2<xn(e)?e.g.statusText:""}catch(e){o=""}e.j=o+" ["+e.aa()+"]",En(e)}}finally{_n(e)}}}function _n(e,t){if(e.g){Sn(e);const n=e.g,r=e.C[0]?_:null;e.g=null,e.C=null,t||Ce(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Sn(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(T.clearTimeout(e.A),e.A=null)}function xn(e){return e.g?e.g.readyState:0}function Dn(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case vn:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function An(e){let n="";return le(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Cn(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=An(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):Ft(e,t,n))}function Nn(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function kn(e){this.Ca=0,this.i=[],this.j=new ze,this.ka=this.sa=this.F=this.V=this.g=this.za=this.D=this.ia=this.o=this.S=this.s=null,this.ab=this.U=0,this.Za=Nn("failFast",!1,e),this.L=this.v=this.u=this.m=this.l=null,this.Y=!0,this.pa=this.Ba=this.T=-1,this.Z=this.A=this.C=0,this.Xa=Nn("baseRetryDelayMs",5e3,e),this.bb=Nn("retryDelaySeedMs",1e4,e),this.$a=Nn("forwardChannelMaxRetries",2,e),this.ta=Nn("forwardChannelRequestTimeoutMs",2e4,e),this.ra=e&&e.xmlHttpFactory||void 0,this.Da=e&&e.Zb||!1,this.J=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.I="",this.h=new Jt(e&&e.concurrentRequestLimit),this.Fa=new un,this.O=e&&e.fastHandshake||!1,this.N=e&&e.encodeInitMessageHeaders||!1,this.O&&this.N&&(this.N=!1),this.Ya=e&&e.Xb||!1,e&&e.Aa&&this.j.Aa(),e&&e.forceLongPolling&&(this.Y=!1),this.$=!this.O&&this.Y&&e&&e.detectBufferingProxy||!1,this.ja=void 0,this.P=0,this.K=!1,this.la=this.B=null}function Rn(e){var t,n;Mn(e),3==e.G&&(t=e.U++,Ft(n=kt(e.F),"SID",e.I),Ft(n,"RID",t),Ft(n,"TYPE","terminate"),Vn(e,n),(t=new dt(e,e.j,t,void 0)).K=2,t.v=Ot(kt(n)),n=!1,!(n=T.navigator&&T.navigator.sendBeacon?T.navigator.sendBeacon(t.v.toString(),""):n)&&T.Image&&((new Image).src=t.v,n=!0),n||(t.g=Hn(t.l,null),t.g.da(t.v)),t.F=Date.now(),Et(t)),zn(e)}function Ln(e){e.g&&(Un(e),e.g.cancel(),e.g=null)}function Mn(e){Ln(e),e.u&&(T.clearTimeout(e.u),e.u=null),Kn(e),e.h.cancel(),e.m&&("number"==typeof e.m&&T.clearTimeout(e.m),e.m=null)}function Fn(e){en(e.h)||e.m||(e.m=!0,Fe(e.Ja,e),e.C=0)}function On(e,t){var n=t?t.m:e.U++,r=kt(e.F);Ft(r,"SID",e.I),Ft(r,"RID",n),Ft(r,"AID",e.T),Vn(e,r),e.o&&e.s&&Cn(r,e.o,e.s),n=new dt(e,e.j,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.i=t.D.concat(e.i)),t=Pn(e,n,1e3),n.setTimeout(Math.round(.5*e.ta)+Math.round(.5*e.ta*Math.random())),rn(e.h,n),vt(n,r,t)}function Vn(e,n){e.ia&&le(e.ia,function(e,t){Ft(n,t,e)}),e.l&&At({},function(e,t){Ft(n,t,e)})}function Pn(e,t,r){r=Math.min(e.i.length,r);var s=e.l?k(e.l.Ra,e.l,e):null;e:{var i=e.i;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=i[0].h,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=i[t].h,o=i[t].g;if((a-=n)<0)n=Math.max(0,i[t].h-100),e=!1;else try{!function(e,r,t){const s=t||"";try{At(e,function(e,t){let n=e;x(e)&&(n=ke(e)),r.push(s+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(s+"type="+encodeURIComponent("_badmap")),e}}(o,u,"req"+a+"_")}catch(e){s&&s(o)}}if(e){s=u.join("&");break e}}}return e=e.i.splice(0,r),t.D=e,s}function qn(e){e.g||e.u||(e.Z=1,Fe(e.Ia,e),e.A=0)}function Bn(e){return!(e.g||e.u||3<=e.A)&&(e.Z++,e.u=rt(k(e.Ia,e),$n(e,e.A)),e.A++,1)}function Un(e){null!=e.B&&(T.clearTimeout(e.B),e.B=null)}function Gn(e){e.g=new dt(e,e.j,"rpc",e.Z),null===e.o&&(e.g.H=e.s),e.g.N=0;var t=kt(e.sa);Ft(t,"RID","rpc"),Ft(t,"SID",e.I),Ft(t,"CI",e.L?"0":"1"),Ft(t,"AID",e.T),Ft(t,"TYPE","xmlhttp"),Vn(e,t),e.o&&e.s&&Cn(t,e.o,e.s),e.J&&e.g.setTimeout(e.J);var n=e.g;e=e.ka,n.K=1,n.v=Ot(kt(t)),n.s=null,n.P=!0,wt(n,e)}function Kn(e){null!=e.v&&(T.clearTimeout(e.v),e.v=null)}function jn(e,t){var n,r,s,i=null;if(e.g==t){Kn(e),Un(e),e.g=null;var a=2}else{if(!nn(e.h,t))return;i=t.D,sn(e.h,t),a=1}if(0!=e.G)if(e.pa=t.Y,t.i)1==a?(i=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,Ce(a=Xe(),new nt(a,i)),Fn(e)):qn(e);else if(3==(n=t.o)||0==n&&0<e.pa||(1!=a||(s=t,tn((r=e).h)>=r.h.j-(r.m?1:0)||(r.m?(r.i=s.D.concat(r.i),0):1==r.G||2==r.G||r.C>=(r.Za?0:r.$a)||(r.m=rt(k(r.Ja,r,s),$n(r,r.C)),r.C++,0))))&&(2!=a||!Bn(e)))switch(i&&0<i.length&&(t=e.h,t.i=t.i.concat(i)),n){case 1:Qn(e,5);break;case 4:Qn(e,10);break;case 3:Qn(e,6);break;default:Qn(e,2)}}function $n(e,t){let n=e.Xa+Math.floor(Math.random()*e.bb);return e.l||(n*=2),n*t}function Qn(e,t){var n,r;e.j.info("Error code "+t),2==t?(n=null,e.l&&(n=null),r=k(e.kb,e),n||(n=new Nt("//www.google.com/images/cleardot.gif"),T.location&&"http"==T.location.protocol||Rt(n,"https"),Ot(n)),function(e,t){var n=new ze;if(T.Image){const r=new Image;r.onload=R(cn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=R(cn,n,r,"TestLoadImage: error",!1,t),r.onabort=R(cn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=R(cn,n,r,"TestLoadImage: timeout",!1,t),T.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):tt(2),e.G=0,e.l&&e.l.va(t),zn(e),Mn(e)}function zn(e){var t;e.G=0,e.la=[],e.l&&(0==(t=an(e.h)).length&&0==e.i.length||(V(e.la,t),V(e.la,e.i),e.h.i.length=0,O(e.i),e.i.length=0),e.l.ua())}function Wn(e,t,n){var r,s,i=n instanceof Nt?kt(n):new Nt(n,void 0);return""!=i.g?(t&&(i.g=t+"."+i.g),Lt(i,i.m)):(i=(r=T.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,s=new Nt(null,void 0),i&&Rt(s,i),t&&(s.g=t),r&&Lt(s,r),n&&(s.l=n),i=s),n=e.D,t=e.za,n&&t&&Ft(i,n,t),Ft(i,"VER",e.ma),Vn(e,i),i}function Hn(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Da&&!e.ra?new yn(new hn({jb:!0})):new yn(e.ra)).Ka(e.H),t}function Yn(){}function Xn(){if(W&&!(10<=Number(se)))throw Error("Environmental error: no available transport.")}function Jn(e,t){Ae.call(this),this.g=new kn(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.S=e,(e=t&&t.Yb)&&!B(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!B(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new tr(this)}function Zn(e){ct.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function er(){ht.call(this),this.status=1}function tr(e){this.g=e}(I=yn.prototype).Ka=function(e){this.L=e},I.da=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||gt).g(),this.C=this.u?ot(this.u):ot(gt),this.g.onreadystatechange=k(this.Ha,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void bn(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var s in r)n.set(s,r[s]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const u of r.keys())n.set(u,r.get(u))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),s=T.FormData&&e instanceof T.FormData,0<=F(In,t)&&!r&&!s&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[i,a]of n)this.g.setRequestHeader(i,a);this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Sn(this),0<this.B&&((this.K=(o=this.g,W&&re()&&"number"==typeof o.timeout&&void 0!==o.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=k(this.qa,this)):this.A=Ue(this.qa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){bn(this,e)}var o},I.qa=function(){void 0!==E&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Ce(this,"timeout"),this.abort(8))},I.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Ce(this,"complete"),Ce(this,"abort"),_n(this))},I.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),_n(this,!0)),yn.X.M.call(this)},I.Ha=function(){this.s||(this.F||this.v||this.l?Tn(this):this.fb())},I.fb=function(){Tn(this)},I.aa=function(){try{return 2<xn(this)?this.g.status:-1}catch(e){return-1}},I.fa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},I.Sa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),pn(t)}},I.Ea=function(){return this.m},I.Oa=function(){return"string"==typeof this.j?this.j:String(this.j)},(I=kn.prototype).ma=8,I.G=1,I.Ja=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;const i=new dt(this,this.j,t,void 0);let e=this.s;if(this.S&&(e?(e=de(e),ge(e,this.S)):e=this.S),null!==this.o||this.N||(i.H=e,e=null),this.O)e:{for(var n=0,r=0;r<this.i.length;r++){var s=this.i[r];if("__data__"in s.g&&"string"==typeof(s=s.g.__data__)?s=s.length:s=void 0,void 0===s)break;if(4096<(n+=s)){n=r;break e}if(4096===n||r===this.i.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Pn(this,i,n),Ft(r=kt(this.F),"RID",t),Ft(r,"CVER",22),this.D&&Ft(r,"X-HTTP-Session-Id",this.D),Vn(this,r),e&&(this.N?n="headers="+encodeURIComponent(String(An(e)))+"&"+n:this.o&&Cn(r,this.o,e)),rn(this.h,i),this.Ya&&Ft(r,"TYPE","init"),this.O?(Ft(r,"$req",n),Ft(r,"SID","null"),i.Z=!0,vt(i,r,null)):vt(i,r,n),this.G=2}}else 3==this.G&&(t?On(this,t):0==this.i.length||en(this.h)||On(this))},I.Ia=function(){var e;this.u=null,Gn(this),this.$&&!(this.K||null==this.g||this.P<=0)&&(e=2*this.P,this.j.info("BP detection timer enabled: "+e),this.B=rt(k(this.eb,this),e))},I.eb=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.L=!1,this.K=!0,tt(10),Ln(this),Gn(this))},I.cb=function(){null!=this.v&&(this.v=null,Ln(this),Bn(this),tt(19))},I.kb=function(e){e?(this.j.info("Successfully pinged google.com"),tt(2)):(this.j.info("Failed to ping google.com"),tt(1))},(I=Yn.prototype).xa=function(){},I.wa=function(){},I.va=function(){},I.ua=function(){},I.Ra=function(){},Xn.prototype.g=function(e,t){return new Jn(e,t)},L(Jn,Ae),Jn.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;tt(0),e.V=t,e.ia=n||{},e.L=e.Y,e.F=Wn(e,null,e.V),Fn(e)},Jn.prototype.close=function(){Rn(this.g)},Jn.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=ke(e),e=t),n.i.push(new Xt(n.ab++,e)),3==n.G&&Fn(n)},Jn.prototype.M=function(){this.g.l=null,delete this.j,Rn(this.g),delete this.g,Jn.X.M.call(this)},L(Zn,ct),L(er,ht),L(tr,Yn),tr.prototype.xa=function(){Ce(this.g,"a")},tr.prototype.wa=function(e){Ce(this.g,new Zn(e))},tr.prototype.va=function(e){Ce(this.g,new er)},tr.prototype.ua=function(){Ce(this.g,"b")},Xn.prototype.createWebChannel=Xn.prototype.g,Jn.prototype.send=Jn.prototype.u,Jn.prototype.open=Jn.prototype.m,st.NO_ERROR=0,st.TIMEOUT=8,st.HTTP_ERROR=6,it.COMPLETE="complete",(ut.EventType=b).OPEN="a",b.CLOSE="b",b.ERROR="c",b.MESSAGE="d",Ae.prototype.listen=Ae.prototype.N,yn.prototype.listenOnce=yn.prototype.O,yn.prototype.getLastError=yn.prototype.Oa,yn.prototype.getLastErrorCode=yn.prototype.Ea,yn.prototype.getStatus=yn.prototype.aa,yn.prototype.getResponseJson=yn.prototype.Sa,yn.prototype.getResponseText=yn.prototype.fa,yn.prototype.send=yn.prototype.da,yn.prototype.setWithCredentials=yn.prototype.Ka;var nr,rr=Xe,sr=st,ir=it,ar=He,or=10,ur=11,cr=hn,hr=ut,lr=yn;const dr="@firebase/firestore";class fr{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}fr.UNAUTHENTICATED=new fr(null),fr.GOOGLE_CREDENTIALS=new fr("google-credentials-uid"),fr.FIRST_PARTY=new fr("first-party-uid"),fr.MOCK_USER=new fr("mock-user");let gr="9.16.0";const mr=new class{constructor(e){this.name=e,this._logLevel=y,this._logHandler=w,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in l))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?p[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,l.DEBUG,...e),this._logHandler(this,l.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,l.VERBOSE,...e),this._logHandler(this,l.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,l.INFO,...e),this._logHandler(this,l.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,l.WARN,...e),this._logHandler(this,l.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,l.ERROR,...e),this._logHandler(this,l.ERROR,...e)}}("@firebase/firestore");function pr(){return mr.logLevel}function yr(e,...t){var n;mr.logLevel<=l.DEBUG&&(n=t.map(Ir),mr.debug(`Firestore (${gr}): ${e}`,...n))}function vr(e,...t){var n;mr.logLevel<=l.ERROR&&(n=t.map(Ir),mr.error(`Firestore (${gr}): ${e}`,...n))}function wr(e,...t){var n;mr.logLevel<=l.WARN&&(n=t.map(Ir),mr.warn(`Firestore (${gr}): ${e}`,...n))}function Ir(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function br(e="Unexpected state"){var t=`FIRESTORE (${gr}) INTERNAL ASSERTION FAILED: `+e;throw vr(t),new Error(t)}function Er(e){e||br()}const Tr={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"};class _r extends h{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Sr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class xr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Dr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(fr.UNAUTHENTICATED))}shutdown(){}}class Ar{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Cr{constructor(e){this.t=e,this.currentUser=fr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const s=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let i=new Sr;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new Sr,t.enqueueRetryable(()=>s(this.currentUser))};const a=()=>{const e=i;t.enqueueRetryable(async()=>{await e.promise,await s(this.currentUser)})},o=e=>{yr("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),a()};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(yr("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new Sr))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(yr("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Er("string"==typeof e.accessToken),new xr(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return Er(null===e||"string"==typeof e),new fr(e)}}class Nr{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r,this.type="FirstParty",this.user=fr.FIRST_PARTY,this.p=new Map}I(){return this.g?this.g():(Er(!("object"!=typeof this.h||null===this.h||!this.h.auth||!this.h.auth.getAuthHeaderValueForFirstParty)),this.h.auth.getAuthHeaderValueForFirstParty([]))}get headers(){this.p.set("X-Goog-AuthUser",this.l);var e=this.I();return e&&this.p.set("Authorization",e),this.m&&this.p.set("X-Goog-Iam-Authorization-Token",this.m),this.p}}class kr{constructor(e,t,n,r){this.h=e,this.l=t,this.m=n,this.g=r}getToken(){return Promise.resolve(new Nr(this.h,this.l,this.m,this.g))}start(e,t){e.enqueueRetryable(()=>t(fr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Rr{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class Lr{constructor(e){this.T=e,this.forceRefresh=!1,this.appCheck=null,this.A=null}start(t,n){const r=e=>{null!=e.error&&yr("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.A;return this.A=e.token,yr("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const s=e=>{yr("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.T.onInit(e=>s(e)),setTimeout(()=>{var e;this.appCheck||((e=this.T.getImmediate({optional:!0}))?s(e):yr("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Er("string"==typeof e.token),this.A=e.token,new Rr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Mr{static R(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var s=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<s.length;++e)r.length<20&&s[e]<n&&(r+=t.charAt(s[e]%t.length))}return r}}function Fr(e,t){return e<t?-1:t<e?1:0}function Or(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function Vr(e){return e+"\0"}class Pr{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new _r(Tr.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Pr.fromMillis(Date.now())}static fromDate(e){return Pr.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new Pr(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Fr(this.nanoseconds,e.nanoseconds):Fr(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class qr{constructor(e){this.timestamp=e}static fromTimestamp(e){return new qr(e)}static min(){return new qr(new Pr(0,0))}static max(){return new qr(new Pr(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class Br{constructor(e,t,n){void 0===t?t=0:t>e.length&&br(),void 0===n?n=e.length-t:n>e.length-t&&br(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===Br.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof Br?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),s=t.get(r);if(n<s)return-1;if(n>s)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class Ur extends Br{construct(e,t,n){return new Ur(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new _r(Tr.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new Ur(t)}static emptyPath(){return new Ur([])}}const Gr=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Kr extends Br{construct(e,t,n){return new Kr(e,t,n)}static isValidIdentifier(e){return Gr.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!Kr.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Kr(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var s=()=>{if(0===n.length)throw new _r(Tr.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new _r(Tr.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new _r(Tr.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?i=!i:"."!==t||i?n+=t:s(),r++}if(s(),i)throw new _r(Tr.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Kr(t)}static emptyPath(){return new Kr([])}}class jr{constructor(e){this.path=e}static fromPath(e){return new jr(Ur.fromString(e))}static fromName(e){return new jr(Ur.fromString(e).popFirst(5))}static empty(){return new jr(Ur.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===Ur.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Ur.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new jr(new Ur(e.slice()))}}class $r{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Qr(e){return e.fields.find(e=>2===e.kind)}function zr(e){return e.fields.filter(e=>2!==e.kind)}$r.UNKNOWN_ID=-1;class Wr{constructor(e,t){this.fieldPath=e,this.kind=t}}class Hr{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Hr(0,Jr.min())}}function Yr(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=qr.fromTimestamp(1e9===r?new Pr(n+1,0):new Pr(n,r));return new Jr(r,jr.empty(),t)}function Xr(e){return new Jr(e.readTime,e.key,-1)}class Jr{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Jr(qr.min(),jr.empty(),-1)}static max(){return new Jr(qr.max(),jr.empty(),-1)}}function Zr(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=jr.comparator(e.documentKey,t.documentKey),0!==n?n:Fr(e.largestBatchId,t.largestBatchId))}const es="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ts{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function ns(e){if(e.code!==Tr.FAILED_PRECONDITION||e.message!==es)throw e;yr("LocalStore","Unexpectedly lost primary lease")}class rs{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,s){return this.callbackAttached&&br(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(s,this.error):this.wrapSuccess(r,this.result):new rs((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(s,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof rs?t:rs.resolve(t)}catch(e){return rs.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):rs.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):rs.reject(t)}static resolve(n){return new rs((e,t)=>{e(n)})}static reject(n){return new rs((e,t)=>{t(n)})}static waitFor(e){return new rs((t,n)=>{let r=0,s=0,i=!1;e.forEach(e=>{++r,e.next(()=>{++s,i&&s===r&&t()},e=>n(e))}),i=!0,s===r&&t()})}static or(e){let t=rs.resolve(!1);for(const n of e)t=t.next(e=>e?rs.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,u){return new rs((t,n)=>{const r=o.length,s=new Array(r);let i=0;for(let e=0;e<r;e++){const a=e;u(o[a]).next(e=>{s[a]=e,++i,i===r&&t(s)},e=>n(e))}})}static doWhile(r,s){return new rs((e,t)=>{const n=()=>{!0===r()?s().next(()=>{n()},t):e()};n()})}}class ss{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.P=new Sr,this.transaction.oncomplete=()=>{this.P.resolve()},this.transaction.onabort=()=>{e.error?this.P.reject(new os(n,e.error)):this.P.resolve()},this.transaction.onerror=e=>{var t=ds(e.target.error);this.P.reject(new os(n,t))}}static open(e,t,n,r){try{return new ss(t,e.transaction(r,n))}catch(e){throw new os(t,e)}}get v(){return this.P.promise}abort(e){e&&this.P.reject(e),this.aborted||(yr("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}V(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new cs(t)}}class is{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===is.D(u())&&vr("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return yr("SimpleDb","Removing database:",e),hs(window.indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!function(){try{return"object"==typeof indexedDB}catch(e){return}}())return!1;if(is.N())return!0;const e=u(),t=is.D(e),n=0<t&&t<10,r=is.k(e),s=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||s)}static N(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.O)}static M(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static k(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async F(i){return this.db||(yr("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const s=indexedDB.open(this.name,this.version);s.onsuccess=e=>{var t=e.target.result;n(t)},s.onblocked=()=>{r(new os(i,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},s.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new _r(Tr.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new _r(Tr.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new os(i,t))},s.onupgradeneeded=e=>{yr("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.$(t,s.transaction,e.oldVersion,this.version).next(()=>{yr("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.B&&(this.db.onversionchange=e=>this.B(e)),this.db}L(t){this.B=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var s="readonly"===t;let i=0;for(;;){++i;try{this.db=await this.F(e);const t=ss.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).next(e=>(t.V(),e)).catch(e=>(t.abort(e),rs.reject(e))).toPromise();return i.catch(()=>{}),await t.v,i}catch(e){const t=e,n="FirebaseError"!==t.name&&i<3;if(yr("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class as{constructor(e){this.q=e,this.U=!1,this.K=null}get isDone(){return this.U}get G(){return this.K}set cursor(e){this.q=e}done(){this.U=!0}j(e){this.K=e}delete(){return hs(this.q.delete())}}class os extends _r{constructor(e,t){super(Tr.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function us(e){return"IndexedDbTransactionError"===e.name}class cs{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(yr("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(yr("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),hs(n)}add(e){return yr("SimpleDb","ADD",this.store.name,e,e),hs(this.store.add(e))}get(t){return hs(this.store.get(t)).next(e=>(yr("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return yr("SimpleDb","DELETE",this.store.name,e),hs(this.store.delete(e))}count(){return yr("SimpleDb","COUNT",this.store.name),hs(this.store.count())}W(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.H(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new rs((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}J(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new rs((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}Y(e,t){yr("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.X=!1;var r=this.cursor(n);return this.H(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.H(r,t)}tt(s){const e=this.cursor({});return new rs((n,r)=>{e.onerror=e=>{var t=ds(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?s(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}H(e,i){const a=[];return new rs((s,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new as(t),r=i(t.primaryKey,t.value,n);if(r instanceof rs){const e=r.catch(e=>(n.done(),rs.reject(e)));a.push(e)}n.isDone?s():null===n.G?t.continue():t.continue(n.G)}else s()}}).next(()=>rs.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.X?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function hs(e){return new rs((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=ds(e.target.error);r(t)}})}let ls=!1;function ds(e){const t=is.D(u());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new _r("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return ls||(ls=!0,setTimeout(()=>{throw e},0)),e}}return e}class fs{constructor(e,t){this.asyncQueue=e,this.et=t,this.task=null}start(){this.nt(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}nt(e){yr("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{yr("IndexBackiller",`Documents written: ${await this.et.st()}`)}catch(e){us(e)?yr("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await ns(e)}await this.nt(6e4)})}}class gs{constructor(e,t){this.localStore=e,this.persistence=t}async st(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.it(e,t))}it(e,t){const n=new Set;let r=t,s=!0;return rs.doWhile(()=>!0===s&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(s=!1):(yr("IndexBackiller",`Processing collection: ${t}`),this.rt(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}rt(r,s,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,s).next(n=>this.localStore.localDocuments.getNextDocuments(r,s,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.ot(n,e)).next(e=>(yr("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,s,e))).next(()=>t.size)}))}ot(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=Xr(t);0<Zr(n,r)&&(r=n)}),new Jr(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ms{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ut(e),this.ct=e=>t.writeSequenceNumber(e))}ut(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.ct&&this.ct(e),e}}ms.at=-1;class ps{constructor(e,t,n,r,s,i,a,o){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=a,this.useFetchStreams=o}}class ys{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new ys("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof ys&&e.projectId===this.projectId&&e.database===this.database}}function vs(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ws(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function Is(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function bs(e){return null==e}function Es(e){return 0===e&&1/e==-1/0}function Ts(e){return"number"==typeof e&&Number.isInteger(e)&&!Es(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class _s{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new _s(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new _s(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Fr(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}_s.EMPTY_BYTE_STRING=new _s("");const Ss=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function xs(t){if(Er(!!t),"string"!=typeof t)return{seconds:Ds(t.seconds),nanos:Ds(t.nanos)};{let e=0;var n=Ss.exec(t);Er(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Ds(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function As(e){return"string"==typeof e?_s.fromBase64String(e):_s.fromUint8Array(e)}function Cs(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function Ns(e){var t=xs(e.mapValue.fields.__local_write_time__.timestampValue);return new Pr(t.seconds,t.nanos)}const ks={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Rs={nullValue:"NULL_VALUE"};function Ls(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?Cs(e)?4:Qs(e)?9007199254740991:10:br()}function Ms(r,s){if(r===s)return!0;var e,t,n=Ls(r);if(n!==Ls(s))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return r.booleanValue===s.booleanValue;case 4:return Ns(r).isEqual(Ns(s));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=xs(r.timestampValue),n=xs(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(s);case 5:return r.stringValue===s.stringValue;case 6:return t=s,As(r.bytesValue).isEqual(As(t.bytesValue));case 7:return r.referenceValue===s.referenceValue;case 8:return e=s,Ds((t=r).geoPointValue.latitude)===Ds(e.geoPointValue.latitude)&&Ds(t.geoPointValue.longitude)===Ds(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Ds(e.integerValue)===Ds(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Ds(e.doubleValue),r=Ds(t.doubleValue);return n===r?Es(n)===Es(r):isNaN(n)&&isNaN(r)}return!1}(r,s);case 9:return Or(r.arrayValue.values||[],s.arrayValue.values||[],Ms);case 10:return function(e){const t=e.mapValue.fields||{},n=s.mapValue.fields||{};if(vs(t)!==vs(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!Ms(t[e],n[e])))return!1;return!0}(r);default:return br()}}function Fs(e,t){return void 0!==(e.values||[]).find(e=>Ms(e,t))}function Os(e,t){if(e===t)return 0;var n,r,s,i,a=Ls(e),o=Ls(t);if(a!==o)return Fr(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Fr(e.booleanValue,t.booleanValue);case 2:return r=t,s=Ds(e.integerValue||e.doubleValue),i=Ds(r.integerValue||r.doubleValue),s<i?-1:i<s?1:s===i?0:isNaN(s)?isNaN(i)?0:-1:1;case 3:return Vs(e.timestampValue,t.timestampValue);case 4:return Vs(Ns(e),Ns(t));case 5:return Fr(e.stringValue,t.stringValue);case 6:return function(e,t){const n=As(e),r=As(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let s=0;s<n.length&&s<r.length;s++){const t=Fr(n[s],r[s]);if(0!==t)return t}return Fr(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(i=Fr(Ds(n.latitude),Ds(r.latitude)))?i:Fr(Ds(n.longitude),Ds(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let s=0;s<n.length&&s<r.length;++s){const t=Os(n[s],r[s]);if(t)return t}return Fr(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===ks.mapValue&&t===ks.mapValue)return 0;if(e===ks.mapValue)return 1;if(t===ks.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),s=t.fields||{},i=Object.keys(s);r.sort(),i.sort();for(let o=0;o<r.length&&o<i.length;++o){const t=Fr(r[o],i[o]);if(0!==t)return t;var a=Os(n[r[o]],s[i[o]]);if(0!==a)return a}return Fr(r.length,i.length)}(e.mapValue,t.mapValue);default:throw br()}}function Vs(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Fr(e,t);var n=xs(e),r=xs(t),s=Fr(n.seconds,r.seconds);return 0!==s?s:Fr(n.nanos,r.nanos)}function Ps(e){return function i(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=xs(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?As(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,jr.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=i(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const s of t)r?r=!1:n+=",",n+=`${s}:${i(e.fields[s])}`;return n+"}"}(e.mapValue):br();var t}(e)}function qs(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Bs(e){return e&&"integerValue"in e}function Us(e){return!!e&&"arrayValue"in e}function Gs(e){return e&&"nullValue"in e}function Ks(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function js(e){return e&&"mapValue"in e}function $s(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return ws(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=$s(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=$s(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Qs(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function zs(e,t){var n=Os(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Ws(e,t){var n=Os(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Hs{constructor(e,t){this.position=e,this.inclusive=t}}function Ys(e,t,n){let r=0;for(let s=0;s<e.position.length;s++){const i=t[s],a=e.position[s];if(r=i.field.isKeyField()?jr.comparator(jr.fromName(a.referenceValue),n.key):Os(a,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return r}function Xs(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ms(e.position[n],t.position[n]))return!1;return!0}class Js{}class Zs extends Js{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new oi(e,t,n):"array-contains"===t?new li(e,n):"in"===t?new di(e,n):"not-in"===t?new fi(e,n):"array-contains-any"===t?new gi(e,n):new Zs(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?ui:ci)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Os(t,this.value)):null!==t&&Ls(this.value)===Ls(t)&&this.matchesComparison(Os(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return br()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class ei extends Js{constructor(e,t){super(),this.filters=e,this.op=t,this.ht=null}static create(e,t){return new ei(e,t)}matches(t){return ti(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ht||(this.ht=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ht}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){var e=this.lt(e=>e.isInequality());return null!==e?e.field:null}lt(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function ti(e){return"and"===e.op}function ni(e){return"or"===e.op}function ri(e){return si(e)&&ti(e)}function si(e){for(const t of e.filters)if(t instanceof ei)return!1;return!0}function ii(e,t){var n=e.filters.concat(t);return ei.create(n,e.op)}function ai(e){return e instanceof Zs?`${(t=e).field.canonicalString()} ${t.op} ${Ps(t.value)}`:e instanceof ei?(e=e).op.toString()+" {"+e.getFilters().map(ai).join(" ,")+"}":"Filter";var t}class oi extends Zs{constructor(e,t,n){super(e,t,n),this.key=jr.fromName(n.referenceValue)}matches(e){var t=jr.comparator(e.key,this.key);return this.matchesComparison(t)}}class ui extends Zs{constructor(e,t){super(e,"in",t),this.keys=hi(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class ci extends Zs{constructor(e,t){super(e,"not-in",t),this.keys=hi(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function hi(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>jr.fromName(e.referenceValue))}class li extends Zs{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Us(t)&&Fs(t.arrayValue,this.value)}}class di extends Zs{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Fs(this.value.arrayValue,t)}}class fi extends Zs{constructor(e,t){super(e,"not-in",t)}matches(e){if(Fs(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Fs(this.value.arrayValue,t)}}class gi extends Zs{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Us(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Fs(this.value.arrayValue,e))}}class mi{constructor(e,t="asc"){this.field=e,this.dir=t}}class pi{constructor(e,t){this.comparator=e,this.root=t||vi.EMPTY}insert(e,t){return new pi(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,vi.BLACK,null,null))}remove(e){return new pi(this.comparator,this.root.remove(e,this.comparator).copy(null,null,vi.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new yi(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new yi(this.root,e,this.comparator,!1)}getReverseIterator(){return new yi(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new yi(this.root,e,this.comparator,!0)}}class yi{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class vi{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:vi.RED,this.left=null!=r?r:vi.EMPTY,this.right=null!=s?s:vi.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new vi(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=s?s:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var s=n(e,r.key);return r=s<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===s?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return vi.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return vi.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,vi.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,vi.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw br();if(this.right.isRed())throw br();var e=this.left.check();if(e!==this.right.check())throw br();return e+(this.isRed()?0:1)}}vi.EMPTY=null,vi.RED=!0,vi.BLACK=!1,vi.EMPTY=new class{constructor(){this.size=0}get key(){throw br()}get value(){throw br()}get color(){throw br()}get left(){throw br()}get right(){throw br()}copy(e,t,n,r,s){return this}insert(e,t,n){return new vi(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class wi{constructor(e){this.comparator=e,this.data=new pi(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new Ii(this.data.getIterator())}getIteratorFrom(e){return new Ii(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof wi))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new wi(this.comparator);return t.data=e,t}}class Ii{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function bi(e){return e.hasNext()?e.getNext():void 0}class Ei{constructor(e){(this.fields=e).sort(Kr.comparator)}static empty(){return new Ei([])}unionWith(e){let t=new wi(Kr.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new Ei(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Or(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class Ti{constructor(e){this.value=e}static empty(){return new Ti({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!js(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=$s(t)}setAll(e){let n=Kr.emptyPath(),r={},s=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,s),r={},s=[],n=t.popLast()}e?r[t.lastSegment()]=$s(e):s.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,s)}delete(e){const t=this.field(e.popLast());js(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ms(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];js(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){ws(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Ti($s(this.value))}}class _i{constructor(e,t,n,r,s,i,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=s,this.data=i,this.documentState=a}static newInvalidDocument(e){return new _i(e,0,qr.min(),qr.min(),qr.min(),Ti.empty(),0)}static newFoundDocument(e,t,n,r){return new _i(e,1,t,qr.min(),n,r,0)}static newNoDocument(e,t){return new _i(e,2,t,qr.min(),qr.min(),Ti.empty(),0)}static newUnknownDocument(e,t){return new _i(e,3,t,qr.min(),qr.min(),Ti.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(qr.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Ti.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Ti.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=qr.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof _i&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new _i(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Si{constructor(e,t=null,n=[],r=[],s=null,i=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=a,this.ft=null}}function xi(e,t=null,n=[],r=[],s=null,i=null,a=null){return new Si(e,t,n,r,s,i,a)}function Di(e){const t=e;if(null===t.ft){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function t(e){if(e instanceof Zs)return e.field.canonicalString()+e.op.toString()+Ps(e.value);if(ri(e))return e.filters.map(e=>t(e)).join(",");var n=e.filters.map(e=>t(e)).join(",");return`${e.op}(${n})`}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),bs(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ps(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ps(e)).join(",")),t.ft=e}return t.ft}function Ai(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let s=0;s<e.orderBy.length;s++)if(n=e.orderBy[s],r=t.orderBy[s],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r;if(e.filters.length!==t.filters.length)return!1;for(let i=0;i<e.filters.length;i++)if(!function r(e,t){return e instanceof Zs?(n=e,(i=t)instanceof Zs&&n.op===i.op&&n.field.isEqual(i.field)&&Ms(n.value,i.value)):e instanceof ei?(s=t)instanceof ei&&e.op===s.op&&e.filters.length===s.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,s.filters[n]),!0):void br();var s,n,i}(e.filters[i],t.filters[i]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Xs(e.startAt,t.startAt)&&Xs(e.endAt,t.endAt)}function Ci(e){return jr.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Ni(e,t){return e.filters.filter(e=>e instanceof Zs&&e.field.isEqual(t))}function ki(t,n,r){let s=Rs,i=!0;for(const r of Ni(t,n)){let e=Rs,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Rs:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?qs(ys.empty(),jr.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:br();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Rs}zs({value:s,inclusive:i},{value:e,inclusive:t})<0&&(s=e,i=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];zs({value:s,inclusive:i},{value:t,inclusive:r.inclusive})<0&&(s=t,i=r.inclusive);break}return{value:s,inclusive:i}}function Ri(t,n,r){let s=ks,i=!0;for(const r of Ni(t,n)){let e=ks,t=!0;switch(r.op){case">=":case">":e="nullValue"in(a=r.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?qs(ys.empty(),jr.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?ks:br(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=ks}0<Ws({value:s,inclusive:i},{value:e,inclusive:t})&&(s=e,i=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Ws({value:s,inclusive:i},{value:t,inclusive:r.inclusive})&&(s=t,i=r.inclusive);break}return{value:s,inclusive:i}}class Li{constructor(e,t=null,n=[],r=[],s=null,i="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=s,this.limitType=i,this.startAt=a,this.endAt=o,this.dt=null,this._t=null,this.startAt,this.endAt}}function Mi(e,t,n,r,s,i,a,o){return new Li(e,t,n,r,s,i,a,o)}function Fi(e){return new Li(e)}function Oi(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function Vi(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Pi(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function qi(e){return null!==e.collectionGroup}function Bi(t){const n=t;if(null===n.dt){n.dt=[];const t=Pi(n),e=Vi(n);if(null!==t&&null===e)t.isKeyField()||n.dt.push(new mi(t)),n.dt.push(new mi(Kr.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.dt.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.dt.push(new mi(Kr.keyField(),t))}}}return n.dt}function Ui(e){const t=e;if(!t._t)if("F"===t.limitType)t._t=xi(t.path,t.collectionGroup,Bi(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const s of Bi(t)){const t="desc"===s.dir?"asc":"desc";e.push(new mi(s.field,t))}var n=t.endAt?new Hs(t.endAt.position,t.endAt.inclusive):null,r=t.startAt?new Hs(t.startAt.position,t.startAt.inclusive):null;t._t=xi(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t._t}function Gi(e,t){t.getFirstInequalityField(),Pi(e);var n=e.filters.concat([t]);return new Li(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Ki(e,t,n){return new Li(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function ji(e,t){return Ai(Ui(e),Ui(t))&&e.limitType===t.limitType}function $i(e){return`${Di(Ui(e))}|lt:${e.limitType}`}function Qi(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>ai(e)).join(", ")}]`),bs(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>Ps(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ps(e)).join(",")),`Target(${t})`}(Ui(e))}; limitType=${e.limitType})`}function zi(n,e){return e.isFoundDocument()&&(s=n,a=(i=e).key.path,null!==s.collectionGroup?i.key.hasCollectionId(s.collectionGroup)&&s.path.isPrefixOf(a):jr.isDocumentKey(s.path)?s.path.isEqual(a):s.path.isImmediateParentOf(a))&&function(e){for(const t of Bi(n))if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(s=e,(!(e=n).startAt||(t=e.startAt,r=Ys(t,Bi(e),s),t.inclusive?r<=0:r<0))&&(!e.endAt||(t=e.endAt,r=Ys(t,Bi(e),s),t.inclusive?0<=r:0<r)));var t,r,s,i,a}function Wi(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Hi(s){return(e,t)=>{let n=!1;for(const r of Bi(s)){const s=function(e,s,t){var n=e.field.isKeyField()?jr.comparator(s.key,t.key):function(e,t){var n=s.data.field(e),r=t.data.field(e);return null!==n&&null!==r?Os(n,r):br()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return br()}}(r,e,t);if(0!==s)return s;n=n||r.field.isKeyField()}return 0}}function Yi(e,t){if(e.wt){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Es(t)?"-0":t}}function Xi(e){return{integerValue:""+e}}function Ji(e,t){return Ts(t)?Xi(t):Yi(e,t)}class Zi{constructor(){this._=void 0}}function ea(e,t){return e instanceof aa?Bs(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class ta extends Zi{}class na extends Zi{constructor(e){super(),this.elements=e}}function ra(e,t){const n=ua(t);for(const t of e.elements)n.some(e=>Ms(e,t))||n.push(t);return{arrayValue:{values:n}}}class sa extends Zi{constructor(e){super(),this.elements=e}}function ia(e,t){let n=ua(t);for(const t of e.elements)n=n.filter(e=>!Ms(e,t));return{arrayValue:{values:n}}}class aa extends Zi{constructor(e,t){super(),this.yt=e,this.gt=t}}function oa(e){return Ds(e.integerValue||e.doubleValue)}function ua(e){return Us(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class ca{constructor(e,t){this.field=e,this.transform=t}}class ha{constructor(e,t){this.version=e,this.transformResults=t}}class la{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new la}static exists(e){return new la(void 0,e)}static updateTime(e){return new la(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function da(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class fa{}function ga(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new Ta(e.key,la.none()):new va(e.key,e.data,la.none());{const s=e.data,i=Ti.empty();let t=new wi(Kr.comparator);for(var r of n.fields)if(!t.has(r)){let e=s.field(r);null===e&&1<r.length&&(r=r.popLast(),e=s.field(r)),null===e?i.delete(r):i.set(r,e),t=t.add(r)}return new wa(e.key,i,new Ei(t.toArray()),la.none())}}function ma(e,t,n){e instanceof va?function(e,t,n){const r=e.value.clone(),s=ba(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof wa?function(e,t,n){if(!da(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=ba(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(Ia(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function pa(e,t,n,r){return e instanceof va?function(e,t,n,r){if(!da(e.precondition,t))return n;const s=e.value.clone(),i=Ea(e.fieldTransforms,r,t);return s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null}(e,t,n,r):e instanceof wa?function(e,t,n,r){if(!da(e.precondition,t))return n;const s=Ea(e.fieldTransforms,r,t),i=t.data;return i.setAll(Ia(e)),i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,da(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function ya(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&Or(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof na&&t instanceof na||e instanceof sa&&t instanceof sa?Or(e.elements,t.elements,Ms):e instanceof aa&&t instanceof aa?Ms(e.gt,t.gt):e instanceof ta&&t instanceof ta)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class va extends fa{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class wa extends fa{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}getFieldMask(){return this.fieldMask}}function Ia(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function ba(e,t,n){const r=new Map;Er(e.length===n.length);for(let h=0;h<n.length;h++){var s=e[h],i=s.transform,a=t.data.field(s.field);r.set(s.field,(o=i,u=a,c=n[h],o instanceof na?ra(o,u):o instanceof sa?ia(o,u):c))}var o,u,c;return r}function Ea(e,t,n){const r=new Map;for(const c of e){const e=c.transform,h=n.data.field(c.field);r.set(c.field,(s=e,i=h,a=t,u=o=void 0,s instanceof ta?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:a.seconds,nanos:a.nanoseconds}}}};return i&&(e.fields.__previous_value__=i),{mapValue:e}}():s instanceof na?ra(s,i):s instanceof sa?ia(s,i):(o=ea(s=s,i),u=oa(o)+oa(s.gt),Bs(o)&&Bs(s.gt)?Xi(u):Yi(s.yt,u))))}var s,i,a,o,u;return r}class Ta extends fa{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class _a extends fa{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Sa{constructor(e){this.count=e}}function xa(e){switch(e){default:return br(),0;case Tr.CANCELLED:case Tr.UNKNOWN:case Tr.DEADLINE_EXCEEDED:case Tr.RESOURCE_EXHAUSTED:case Tr.INTERNAL:case Tr.UNAVAILABLE:case Tr.UNAUTHENTICATED:return;case Tr.INVALID_ARGUMENT:case Tr.NOT_FOUND:case Tr.ALREADY_EXISTS:case Tr.PERMISSION_DENIED:case Tr.FAILED_PRECONDITION:case Tr.ABORTED:case Tr.OUT_OF_RANGE:case Tr.UNIMPLEMENTED:case Tr.DATA_LOSS:return 1}}function Da(e){if(void 0===e)return vr("GRPC error has no .code"),Tr.UNKNOWN;switch(e){case nr.OK:return Tr.OK;case nr.CANCELLED:return Tr.CANCELLED;case nr.UNKNOWN:return Tr.UNKNOWN;case nr.DEADLINE_EXCEEDED:return Tr.DEADLINE_EXCEEDED;case nr.RESOURCE_EXHAUSTED:return Tr.RESOURCE_EXHAUSTED;case nr.INTERNAL:return Tr.INTERNAL;case nr.UNAVAILABLE:return Tr.UNAVAILABLE;case nr.UNAUTHENTICATED:return Tr.UNAUTHENTICATED;case nr.INVALID_ARGUMENT:return Tr.INVALID_ARGUMENT;case nr.NOT_FOUND:return Tr.NOT_FOUND;case nr.ALREADY_EXISTS:return Tr.ALREADY_EXISTS;case nr.PERMISSION_DENIED:return Tr.PERMISSION_DENIED;case nr.FAILED_PRECONDITION:return Tr.FAILED_PRECONDITION;case nr.ABORTED:return Tr.ABORTED;case nr.OUT_OF_RANGE:return Tr.OUT_OF_RANGE;case nr.UNIMPLEMENTED:return Tr.UNIMPLEMENTED;case nr.DATA_LOSS:return Tr.DATA_LOSS;default:return br()}}(it=nr=nr||{})[it.OK=0]="OK",it[it.CANCELLED=1]="CANCELLED",it[it.UNKNOWN=2]="UNKNOWN",it[it.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",it[it.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",it[it.NOT_FOUND=5]="NOT_FOUND",it[it.ALREADY_EXISTS=6]="ALREADY_EXISTS",it[it.PERMISSION_DENIED=7]="PERMISSION_DENIED",it[it.UNAUTHENTICATED=16]="UNAUTHENTICATED",it[it.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",it[it.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",it[it.ABORTED=10]="ABORTED",it[it.OUT_OF_RANGE=11]="OUT_OF_RANGE",it[it.UNIMPLEMENTED=12]="UNIMPLEMENTED",it[it.INTERNAL=13]="INTERNAL",it[it.UNAVAILABLE=14]="UNAVAILABLE",it[it.DATA_LOSS=15]="DATA_LOSS";class Aa{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let s=0;s<r.length;s++)if(this.equalsFn(r[s][0],e))return void(r[s]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){ws(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return Is(this.inner)}size(){return this.innerSize}}const Ca=new pi(jr.comparator);const Na=new pi(jr.comparator);function ka(...e){let t=Na;for(const n of e)t=t.insert(n.key,n);return t}function Ra(e){let n=Na;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function La(){return new Aa(e=>e.toString(),(e,t)=>e.isEqual(t))}const Ma=new pi(jr.comparator),Fa=new wi(jr.comparator);function Oa(...e){let t=Fa;for(const n of e)t=t.add(n);return t}const Va=new wi(Fr);class Pa{constructor(e,t,n,r,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,qa.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Pa(qr.min(),r,Va,Ca,Oa())}}class qa{constructor(e,t,n,r,s){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new qa(n,t,Oa(),Oa(),Oa())}}class Ba{constructor(e,t,n,r){this.It=e,this.removedTargetIds=t,this.key=n,this.Tt=r}}class Ua{constructor(e,t){this.targetId=e,this.Et=t}}class Ga{constructor(e,t,n=_s.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Ka{constructor(){this.At=0,this.Rt=Qa(),this.bt=_s.EMPTY_BYTE_STRING,this.Pt=!1,this.vt=!0}get current(){return this.Pt}get resumeToken(){return this.bt}get Vt(){return 0!==this.At}get St(){return this.vt}Dt(e){0<e.approximateByteSize()&&(this.vt=!0,this.bt=e)}Ct(){let n=Oa(),r=Oa(),s=Oa();return this.Rt.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:s=s.add(e);break;default:br()}}),new qa(this.bt,this.Pt,n,r,s)}xt(){this.vt=!1,this.Rt=Qa()}Nt(e,t){this.vt=!0,this.Rt=this.Rt.insert(e,t)}kt(e){this.vt=!0,this.Rt=this.Rt.remove(e)}Ot(){this.At+=1}Mt(){--this.At}Ft(){this.vt=!0,this.Pt=!0}}class ja{constructor(e){this.$t=e,this.Bt=new Map,this.Lt=Ca,this.qt=$a(),this.Ut=new wi(Fr)}Kt(e){for(const t of e.It)e.Tt&&e.Tt.isFoundDocument()?this.Gt(t,e.Tt):this.Qt(t,e.key,e.Tt);for(const n of e.removedTargetIds)this.Qt(n,e.key,e.Tt)}jt(n){this.forEachTarget(n,e=>{const t=this.Wt(e);switch(n.state){case 0:this.zt(e)&&t.Dt(n.resumeToken);break;case 1:t.Mt(),t.Vt||t.xt(),t.Dt(n.resumeToken);break;case 2:t.Mt(),t.Vt||this.removeTarget(e);break;case 3:this.zt(e)&&(t.Ft(),t.Dt(n.resumeToken));break;case 4:this.zt(e)&&(this.Ht(e),t.Dt(n.resumeToken));break;default:br()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Bt.forEach((e,t)=>{this.zt(t)&&n(t)})}Jt(e){const t=e.targetId,n=e.Et.count,r=this.Yt(t);if(r){const e=r.target;if(Ci(e))if(0===n){const n=new jr(e.path);this.Qt(t,n,_i.newNoDocument(n,qr.min()))}else Er(1===n);else this.Xt(t)!==n&&(this.Ht(t),this.Ut=this.Ut.add(t))}}Zt(r){const s=new Map;this.Bt.forEach((e,t)=>{var n=this.Yt(t);if(n){if(e.current&&Ci(n.target)){const s=new jr(n.target.path);null!==this.Lt.get(s)||this.te(t,s)||this.Qt(t,s,_i.newNoDocument(s,r))}e.St&&(s.set(t,e.Ct()),e.xt())}});let i=Oa();this.qt.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Yt(e);return!t||2===t.purpose||(n=!1)}),n&&(i=i.add(e))}),this.Lt.forEach((e,t)=>t.setReadTime(r));var e=new Pa(r,s,this.Ut,this.Lt,i);return this.Lt=Ca,this.qt=$a(),this.Ut=new wi(Fr),e}Gt(e,t){var n;this.zt(e)&&(n=this.te(e,t.key)?2:0,this.Wt(e).Nt(t.key,n),this.Lt=this.Lt.insert(t.key,t),this.qt=this.qt.insert(t.key,this.ee(t.key).add(e)))}Qt(e,t,n){if(this.zt(e)){const r=this.Wt(e);this.te(e,t)?r.Nt(t,1):r.kt(t),this.qt=this.qt.insert(t,this.ee(t).delete(e)),n&&(this.Lt=this.Lt.insert(t,n))}}removeTarget(e){this.Bt.delete(e)}Xt(e){var t=this.Wt(e).Ct();return this.$t.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ot(e){this.Wt(e).Ot()}Wt(e){let t=this.Bt.get(e);return t||(t=new Ka,this.Bt.set(e,t)),t}ee(e){let t=this.qt.get(e);return t||(t=new wi(Fr),this.qt=this.qt.insert(e,t)),t}zt(e){var t=null!==this.Yt(e);return t||yr("WatchChangeAggregator","Detected inactive target",e),t}Yt(e){var t=this.Bt.get(e);return t&&t.Vt?null:this.$t.ne(e)}Ht(t){this.Bt.set(t,new Ka),this.$t.getRemoteKeysForTarget(t).forEach(e=>{this.Qt(t,e,null)})}te(e,t){return this.$t.getRemoteKeysForTarget(e).has(t)}}function $a(){return new pi(jr.comparator)}function Qa(){return new pi(jr.comparator)}const za={asc:"ASCENDING",desc:"DESCENDING"},Wa={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},Ha={and:"AND",or:"OR"};class Ya{constructor(e,t){this.databaseId=e,this.wt=t}}function Xa(e,t){return e.wt?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function Ja(e,t){return e.wt?t.toBase64():t.toUint8Array()}function Za(e){return Er(!!e),qr.fromTimestamp((t=xs(e),new Pr(t.seconds,t.nanos)));var t}function eo(e,t){return e=e,new Ur(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function to(e){var t=Ur.fromString(e);return Er(Io(t)),t}function no(e,t){return eo(e.databaseId,t.path)}function ro(e,t){const n=to(t);if(n.get(1)!==e.databaseId.projectId)throw new _r(Tr.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new _r(Tr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new jr(oo(n))}function so(e,t){return eo(e.databaseId,t)}function io(e){var t=to(e);return 4===t.length?Ur.emptyPath():oo(t)}function ao(e){return new Ur(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function oo(e){return Er(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function uo(e,t,n){return{name:no(e,t),fields:n.value.mapValue.fields}}function co(e,t,n){const r=ro(e,t.name),s=Za(t.updateTime),i=t.createTime?Za(t.createTime):qr.min(),a=new Ti({mapValue:{fields:t.fields}}),o=_i.newFoundDocument(r,s,i,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function ho(e,t){let n;if(t instanceof va)n={update:uo(e,t.key,t.value)};else if(t instanceof Ta)n={delete:no(e,t.key)};else if(t instanceof wa)n={update:uo(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof _a))return br();n={verify:no(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof ta)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof na)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof sa)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof aa)return{fieldPath:e.field.canonicalString(),increment:t.gt};throw br()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,Xa(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:br()),n;var r}function lo(t,n){const e=n.currentDocument?void 0!==(s=n.currentDocument).updateTime?la.updateTime(Za(s.updateTime)):void 0!==s.exists?la.exists(s.exists):la.none():la.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Er("REQUEST_TIME"===t.setToServerValue),n=new ta;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new na(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new sa(e)}else"increment"in t?n=new aa(e,t.increment):br();var r=Kr.fromServerFormat(t.fieldPath);return new ca(r,n)}(t,e)):[];var s;if(n.update){n.update.name;var i=ro(t,n.update.name),a=new Ti({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new Ei(e.map(e=>Kr.fromServerFormat(e)))}();return new wa(i,a,t,e,r)}return new va(i,a,e,r)}if(n.delete){const r=ro(t,n.delete);return new Ta(r,e)}if(n.verify){const r=ro(t,n.verify);return new _a(r,e)}return br()}function fo(e,t){return{documents:[so(e,t.path)]}}function go(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=so(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=so(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var s=function(e){if(0!==e.length)return function n(e){return e instanceof Zs?function(e){if("=="===e.op){if(Ks(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NAN"}};if(Gs(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ks(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NOT_NAN"}};if(Gs(e.value))return{unaryFilter:{field:vo(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:vo(e.field),op:po(e.op),value:e.value}}}(e):e instanceof ei?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:yo(e.op),filters:t}}}(e):br()}(ei.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:vo(e.field),direction:(e=e.dir,za[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);var i,s=(i=t.limit,e.wt||bs(i)?i:{value:i});return null!==s&&(n.structuredQuery.limit=s),t.startAt&&(n.structuredQuery.startAt={before:(s=t.startAt).inclusive,values:s.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function mo(e){let t=io(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(0<r){Er(1===r);const g=n.from[0];g.allDescendants?s=g.collectionId:t=t.child(g.collectionId)}let i=[];n.where&&(i=function(){const e=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=wo(e.unaryFilter.field);return Zs.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=wo(e.unaryFilter.field);return Zs.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=wo(e.unaryFilter.field);return Zs.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const s=wo(e.unaryFilter.field);return Zs.create(s,"!=",{nullValue:"NULL_VALUE"});default:return br()}}(e):void 0!==e.fieldFilter?function(e){return Zs.create(wo(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return br()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return ei.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return br()}}(e.compositeFilter.op))}(e):br()}(n.where);return e instanceof ei&&ri(e)?e.getFilters():[e]}());let a=[];n.orderBy&&(a=n.orderBy.map(e=>function(e){return new mi(wo(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let o=null;var u,c,h,l;n.limit&&(o=(e=n.limit,bs(u="object"==typeof e?e.value:e)?null:u));let d=null;n.startAt&&(d=(c=n.startAt,l=!!c.before,h=c.values||[],new Hs(h,l)));let f=null;return n.endAt&&(f=(c=n.endAt,h=!c.before,l=c.values||[],new Hs(l,h))),Mi(t,s,a,i,o,"F",d,f)}function po(e){return Wa[e]}function yo(e){return Ha[e]}function vo(e){return{fieldPath:e.canonicalString()}}function wo(e){return Kr.fromServerFormat(e.fieldPath)}function Io(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function bo(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Eo(t)),t=function(e,t){let n=t;const r=e.length;for(let s=0;s<r;s++){const r=e.charAt(s);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Eo(t)}function Eo(e){return e+""}function To(t){const n=t.length;if(Er(2<=n),2===n)return Er(""===t.charAt(0)&&""===t.charAt(1)),Ur.emptyPath();const r=n-2,s=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>r)&&br(),t.charAt(n+1)){case"":const r=t.substring(a,n);let e;0===i.length?e=r:(i+=r,e=i,i=""),s.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:br()}a=n+2}return new Ur(s)}const _o=["userId","batchId"];function So(e,t){return[e,bo(t)]}function xo(e,t,n){return[e,bo(t),n]}const Do={},Ao=["prefixPath","collectionGroup","readTime","documentId"],Co=["prefixPath","collectionGroup","documentId"],No=["collectionGroup","readTime","prefixPath","documentId"],ko=["canonicalId","targetId"],Ro=["targetId","path"],Lo=["path","targetId"],Mo=["collectionId","parent"],Fo=["indexId","uid"],Oo=["uid","sequenceNumber"],Vo=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Po=["indexId","uid","orderedDocumentKey"],qo=["userId","collectionPath","documentId"],Bo=["userId","collectionPath","largestBatchId"],Uo=["userId","collectionGroup","largestBatchId"],Go=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],Ko=[...Go,"documentOverlays"],jo=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],$o=jo,Qo=[...$o,"indexConfiguration","indexState","indexEntries"];class zo extends ts{constructor(e,t){super(),this.se=e,this.currentSequenceNumber=t}}function Wo(e,t){var n=e;return is.M(n.se,t)}class Ho{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const s=this.mutations[r];s.key.isEqual(e.key)&&ma(s,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=pa(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=pa(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(i,a){const o=La();return this.mutations.forEach(e=>{const t=i.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var s=ga(n,r);null!==s&&o.set(e.key,s),n.isValidDocument()||n.convertToNoDocument(qr.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Oa())}isEqual(e){return this.batchId===e.batchId&&Or(this.mutations,e.mutations,(e,t)=>ya(e,t))&&Or(this.baseMutations,e.baseMutations,(e,t)=>ya(e,t))}}class Yo{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Er(e.mutations.length===n.length);let r=Ma;var s=e.mutations;for(let i=0;i<s.length;i++)r=r.insert(s[i].key,n[i].version);return new Yo(e,t,n,r)}}class Xo{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Jo{constructor(e,t,n,r,s=qr.min(),i=qr.min(),a=_s.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=a}withSequenceNumber(e){return new Jo(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new Jo(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new Jo(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class Zo{constructor(e){this.ie=e}}function eu(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:tu(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:no(s=e.ie,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:Xa(s,e.version.toTimestamp()),createTime:Xa(s,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:nu(t.version)};else{if(!t.isUnknownDocument())return br();r.unknownDocument={path:n.path.toArray(),version:nu(t.version)}}var s;return r}function tu(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function nu(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function ru(e){var t=new Pr(e.seconds,e.nanoseconds);return qr.fromTimestamp(t)}function su(t,e){const n=(e.baseMutations||[]).map(e=>lo(t.ie,e));for(let i=0;i<e.mutations.length-1;++i){const n=e.mutations[i];if(i+1<e.mutations.length&&void 0!==e.mutations[i+1].transform){const r=e.mutations[i+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(i+1,1),++i}}const r=e.mutations.map(e=>lo(t.ie,e)),s=Pr.fromMillis(e.localWriteTimeMs);return new Ho(e.batchId,s,n,r)}function iu(e){var t,n=ru(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?ru(e.lastLimboFreeSnapshotVersion):qr.min();let s;return s=void 0!==e.query.documents?(Er(1===(t=e.query).documents.length),Ui(Fi(io(t.documents[0])))):Ui(mo(e.query)),new Jo(s,e.targetId,0,e.lastListenSequenceNumber,n,r,_s.fromBase64String(e.resumeToken))}function au(e,t){var n=nu(t.snapshotVersion),r=nu(t.lastLimboFreeSnapshotVersion),s=(Ci(t.target)?fo:go)(e.ie,t.target),i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Di(t.target),readTime:n,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:s}}function ou(e){var t=mo({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Ki(t,t.limit,"L"):t}function uu(e,t){return new Xo(t.largestBatchId,lo(e.ie,t.overlayMutation))}function cu(e,t){var n=t.path.lastSegment();return[e,bo(t.path.popLast()),n]}function hu(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:nu(r.readTime),documentKey:bo(r.documentKey.path),largestBatchId:r.largestBatchId}}class lu{getBundleMetadata(e,t){return du(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:ru(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return du(e).put({bundleId:(n=t).id,createTime:nu(Za(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return fu(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:ou(t.bundledQuery),readTime:ru(t.readTime)};var t})}saveNamedQuery(e,t){return fu(e).put({name:(t=t).name,readTime:nu(Za(t.readTime)),bundledQuery:t.bundledQuery})}}function du(e){return Wo(e,"bundles")}function fu(e){return Wo(e,"namedQueries")}class gu{constructor(e,t){this.yt=e,this.userId=t}static re(e,t){var n=t.uid||"";return new gu(e,n)}getOverlay(e,t){return mu(e).get(cu(this.userId,t)).next(e=>e?uu(this.yt,e):null)}getOverlays(e,t){const n=La();return rs.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,s,e){const i=[];return e.forEach((e,t)=>{var n=new Xo(s,t);i.push(this.oe(r,n))}),rs.waitFor(i)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(bo(e.getCollectionPath())));const s=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);s.push(mu(n).Y("collectionPathOverlayIndex",t))}),rs.waitFor(s)}getOverlaysForCollection(e,t,n){const r=La(),s=bo(t),i=IDBKeyRange.bound([this.userId,s,n],[this.userId,s,Number.POSITIVE_INFINITY],!0);return mu(e).W("collectionPathOverlayIndex",i).next(e=>{for(const t of e){const e=uu(this.yt,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,s){const i=La();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return mu(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=uu(this.yt,t);i.size()<s||r.largestBatchId===a?(i.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>i)}oe(e,t){return mu(e).put(function(e,t,n){var[,r,s]=cu(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:ho(e.ie,n.mutation)}}(this.yt,this.userId,t))}}function mu(e){return Wo(e,"documentOverlays")}class pu{constructor(){}ue(e,t){this.ce(e,t),t.ae()}ce(e,t){var n,r;"nullValue"in e?this.he(t,5):"booleanValue"in e?(this.he(t,10),t.le(e.booleanValue?1:0)):"integerValue"in e?(this.he(t,15),t.le(Ds(e.integerValue))):"doubleValue"in e?(n=Ds(e.doubleValue),isNaN(n)?this.he(t,13):(this.he(t,15),Es(n)?t.le(0):t.le(n))):"timestampValue"in e?(r=e.timestampValue,this.he(t,20),"string"==typeof r?t.fe(r):(t.fe(`${r.seconds||""}`),t.le(r.nanos||0))):"stringValue"in e?(this.de(e.stringValue,t),this._e(t)):"bytesValue"in e?(this.he(t,30),t.we(As(e.bytesValue)),this._e(t)):"referenceValue"in e?this.me(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.he(t,45),t.le(r.latitude||0),t.le(r.longitude||0)):"mapValue"in e?Qs(e)?this.he(t,Number.MAX_SAFE_INTEGER):(this.ge(e.mapValue,t),this._e(t)):"arrayValue"in e?(this.ye(e.arrayValue,t),this._e(t)):br()}de(e,t){this.he(t,25),this.pe(e,t)}pe(e,t){t.fe(e)}ge(e,t){var n=e.fields||{};this.he(t,55);for(const e of Object.keys(n))this.de(e,t),this.ce(n[e],t)}ye(e,t){var n=e.values||[];this.he(t,50);for(const e of n)this.ce(e,t)}me(e,t){this.he(t,37),jr.fromName(e).path.forEach(e=>{this.he(t,60),this.pe(e,t)})}he(e,t){e.le(t)}_e(e){e.le(2)}}function yu(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}pu.Ie=new pu;class vu{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Te(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ee(n.value),n=t.next();this.Ae()}Re(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.be(n.value),n=t.next();this.Pe()}ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ee(e);else if(e<2048)this.Ee(960|e>>>6),this.Ee(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ee(480|e>>>12),this.Ee(128|63&e>>>6),this.Ee(128|63&e);else{const e=t.codePointAt(0);this.Ee(240|e>>>18),this.Ee(128|63&e>>>12),this.Ee(128|63&e>>>6),this.Ee(128|63&e)}}this.Ae()}Ve(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.be(e);else if(e<2048)this.be(960|e>>>6),this.be(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.be(480|e>>>12),this.be(128|63&e>>>6),this.be(128|63&e);else{const e=t.codePointAt(0);this.be(240|e>>>18),this.be(128|63&e>>>12),this.be(128|63&e>>>6),this.be(128|63&e)}}this.Pe()}Se(e){var t=this.De(e),n=yu(t);this.Ce(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}xe(e){var t=this.De(e),n=yu(t);this.Ce(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}Ne(){this.ke(255),this.ke(255)}Oe(){this.Me(255),this.Me(255)}reset(){this.position=0}seed(e){this.Ce(e.length),this.buffer.set(e,this.position),this.position+=e.length}Fe(){return this.buffer.slice(0,this.position)}De(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ee(e){var t=255&e;0==t?(this.ke(0),this.ke(255)):255==t?(this.ke(255),this.ke(0)):this.ke(t)}be(e){var t=255&e;0==t?(this.Me(0),this.Me(255)):255==t?(this.Me(255),this.Me(0)):this.Me(e)}Ae(){this.ke(0),this.ke(1)}Pe(){this.Me(0),this.Me(1)}ke(e){this.Ce(1),this.buffer[this.position++]=e}Me(e){this.Ce(1),this.buffer[this.position++]=~e}Ce(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class wu{constructor(e){this.$e=e}we(e){this.$e.Te(e)}fe(e){this.$e.ve(e)}le(e){this.$e.Se(e)}ae(){this.$e.Ne()}}class Iu{constructor(e){this.$e=e}we(e){this.$e.Re(e)}fe(e){this.$e.Ve(e)}le(e){this.$e.xe(e)}ae(){this.$e.Oe()}}class bu{constructor(){this.$e=new vu,this.Be=new wu(this.$e),this.Le=new Iu(this.$e)}seed(e){this.$e.seed(e)}qe(e){return 0===e?this.Be:this.Le}Fe(){return this.$e.Fe()}reset(){this.$e.reset()}}class Eu{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Ue(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new Eu(this.indexId,this.documentKey,this.arrayValue,n)}}function Tu(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=_u(e.arrayValue,t.arrayValue),0!==n?n:(n=_u(e.directionalValue,t.directionalValue),0!==n?n:jr.comparator(e.documentKey,t.documentKey)))}function _u(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class Su{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Ke=e.orderBy,this.Ge=[];for(const t of e.filters){const e=t;e.isInequality()?this.Qe=e:this.Ge.push(e)}}je(e){Er(e.collectionGroup===this.collectionId);var t=Qr(e);if(void 0!==t&&!this.We(t))return!1;var n=zr(e);let r=0,s=0;for(;r<n.length&&this.We(n[r]);++r);if(r===n.length)return!0;if(void 0!==this.Qe){const e=n[r];if(!this.ze(this.Qe,e)||!this.He(this.Ke[s++],e))return!1;++r}for(;r<n.length;++r){const e=n[r];if(s>=this.Ke.length||!this.He(this.Ke[s++],e))return!1}return!0}We(e){for(const t of this.Ge)if(this.ze(t,e))return!0;return!1}ze(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}He(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function xu(e){if(0===e.getFilters().length)return[];const t=function t(e){if(Er(e instanceof Zs||e instanceof ei),e instanceof Zs)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=ei.create(n,e.op);return r=Ru(r),Cu(r)?r:(Er(r instanceof ei),Er(ti(r)),Er(1<r.filters.length),r.filters.reduce((e,t)=>Nu(e,t)))}(function t(n){var e;if(Er(n instanceof Zs||n instanceof ei),n instanceof Zs){if(n instanceof di){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>Zs.create(n.field,"==",e)))||[];return ei.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return ei.create(r,n.op)}(e));return Er(Cu(t)),Du(t)||Au(t)?[t]:t.getFilters()}function Du(e){return e instanceof Zs}function Au(e){return e instanceof ei&&ri(e)}function Cu(e){return Du(e)||Au(e)||function(e){if(e instanceof ei&&ni(e)){for(const t of e.getFilters())if(!Du(t)&&!Au(t))return!1;return!0}return!1}(e)}function Nu(e,t){var n,r;return Er(e instanceof Zs||e instanceof ei),Er(t instanceof Zs||t instanceof ei),Ru(e instanceof Zs?t instanceof Zs?(n=e,r=t,ei.create([n,r],"and")):ku(e,t):t instanceof Zs?ku(t,e):function(e,t){if(Er(0<e.filters.length&&0<t.filters.length),ti(e)&&ti(t))return ii(e,t.getFilters());const n=ni(e)?e:t,r=ni(e)?t:e,s=n.filters.map(e=>Nu(e,r));return ei.create(s,"or")}(e,t))}function ku(t,e){if(ti(e))return ii(e,t.getFilters());var n=e.filters.map(e=>Nu(t,e));return ei.create(n,"or")}function Ru(t){if(Er(t instanceof Zs||t instanceof ei),t instanceof Zs)return t;const e=t.getFilters();if(1===e.length)return Ru(e[0]);if(si(t))return t;const n=e.map(e=>Ru(e)),r=[];return n.forEach(e=>{e instanceof Zs?r.push(e):e instanceof ei&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:ei.create(r,t.op)}class Lu{constructor(){this.Je=new Mu}addToCollectionParentIndex(e,t){return this.Je.add(t),rs.resolve()}getCollectionParents(e,t){return rs.resolve(this.Je.getEntries(t))}addFieldIndex(e,t){return rs.resolve()}deleteFieldIndex(e,t){return rs.resolve()}getDocumentsMatchingTarget(e,t){return rs.resolve(null)}getIndexType(e,t){return rs.resolve(0)}getFieldIndexes(e,t){return rs.resolve([])}getNextCollectionGroupToUpdate(e){return rs.resolve(null)}getMinOffset(e,t){return rs.resolve(Jr.min())}getMinOffsetFromCollectionGroup(e,t){return rs.resolve(Jr.min())}updateCollectionGroup(e,t,n){return rs.resolve()}updateIndexEntries(e,t){return rs.resolve()}}class Mu{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new wi(Ur.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new wi(Ur.comparator)).toArray()}}const Fu=new Uint8Array(0);class Ou{constructor(e,t){this.user=e,this.databaseId=t,this.Ye=new Mu,this.Xe=new Aa(e=>Di(e),(e,t)=>Ai(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.Ye.has(t))return rs.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Ye.add(t)});r={collectionId:n,parent:bo(r)};return Vu(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[Vr(n),""],!1,!0);return Vu(e).W(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(To(t.parent))}return r})}addFieldIndex(e,t){const n=qu(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const s=n.add(r);if(t.indexState){const n=Bu(e);return s.next(e=>{n.put(hu(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return s.next()}deleteFieldIndex(e,t){const n=qu(e),r=Bu(e),s=Pu(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>s.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,c){const h=Pu(e);let l=!0;const n=new Map;return rs.forEach(this.Ze(c),t=>this.tn(e,t).next(e=>{l=l&&!!e,n.set(t,e)})).next(()=>{if(l){let u=Oa();const l=[];return rs.forEach(n,(e,t)=>{yr("IndexedDbIndexManager",`Using index ${o=e,`id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${Di(c)}`);var n=function(e,t){var n=Qr(t);if(void 0===n)return null;for(const t of Ni(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),r=function(e,t){const n=new Map;for(const r of zr(t))for(const t of Ni(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const s of zr(t)){const t=(0===s.kind?ki:Ri)(e,s.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Hs(n,r)}(t,e),i=function(e,t){const n=[];let r=!0;for(const s of zr(t)){const t=(0===s.kind?Ri:ki)(e,s.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Hs(n,r)}(t,e),a=this.en(e,t,s),o=this.en(e,t,i),r=this.nn(e,t,r),r=this.sn(e.indexId,n,a,s.inclusive,o,i.inclusive,r);return rs.forEach(r,e=>h.J(e,c.limit).next(e=>{e.forEach(e=>{var t=jr.fromSegments(e.documentKey);u.has(t)||(u=u.add(t),l.push(t))})}))}).next(()=>l)}return rs.resolve(null)})}Ze(t){let e=this.Xe.get(t);return e||(e=0===t.filters.length?[t]:xu(ei.create(t.filters,"and")).map(e=>xi(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.Xe.set(t,e),e)}sn(t,e,n,r,s,i,a){const o=(null!=e?e.length:1)*Math.max(n.length,s.length),u=o/(null!=e?e.length:1),c=[];for(let h=0;h<o;++h){const o=e?this.rn(e[h/u]):Fu,l=this.on(t,o,n[h%u],r),d=this.un(t,o,s[h%u],i),f=a.map(e=>this.on(t,o,e,!0));c.push(...this.createRange(l,d,f))}return c}on(e,t,n,r){const s=new Eu(e,jr.empty(),t,n);return r?s:s.Ue()}un(e,t,n,r){const s=new Eu(e,jr.empty(),t,n);return r?s.Ue():s}tn(e,t){const r=new Su(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.je(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.Ze(t);return rs.forEach(r,t=>this.tn(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new wi(Kr.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>null!==t.limit&&1<r.length&&2===n?1:n)}cn(e,t){const n=new bu;for(const s of zr(e)){const e=t.data.field(s.fieldPath);if(null==e)return null;var r=n.qe(s.kind);pu.Ie.ue(e,r)}return n.Fe()}rn(e){const t=new bu;return pu.Ie.ue(e,t.qe(0)),t.Fe()}an(e,t){const n=new bu;return pu.Ie.ue(qs(this.databaseId,t),n.qe(0===(r=zr(e)).length?0:r[r.length-1].kind)),n.Fe();var r}nn(e,t,n){if(null===n)return[];let r=[];r.push(new bu);let s=0;for(const i of zr(e)){const e=n[s++];for(const n of r)if(this.hn(t,i.fieldPath)&&Us(e))r=this.ln(r,i,e);else{const t=n.qe(i.kind);pu.Ie.ue(e,t)}}return this.fn(r)}en(e,t,n){return this.nn(e,t,n.position)}fn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Fe();return t}ln(e,t,n){const r=[...e],s=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new bu;r.seed(n.Fe()),pu.Ie.ue(e,r.qe(t.kind)),s.push(r)}return s}hn(e,t){return!!e.filters.find(e=>e instanceof Zs&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=qu(e),r=Bu(e);return(t?n.W("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.W()).next(e=>{const i=[];return rs.forEach(e,s=>r.get([s.indexId,this.uid]).next(e=>{var t,n,r;i.push((t=s,n=(e=e)?new Hr(e.sequenceNumber,new Jr(ru(e.readTime),new jr(To(e.documentKey)),e.largestBatchId)):Hr.empty(),r=t.fields.map(([e,t])=>new Wr(Kr.fromServerFormat(e),t)),new $r(t.indexId,t.collectionGroup,r,n)))})).next(()=>i)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Fr(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const s=qu(e),i=Bu(e);return this.dn(e).next(t=>s.W("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>rs.forEach(e,e=>i.put(hu(e.indexId,this.user,t,r)))))}updateIndexEntries(s,e){const n=new Map;return rs.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?rs.resolve(e):this.getFieldIndexes(s,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),rs.forEach(e,n=>this._n(s,t,n).next(e=>{var t=this.wn(r,n);return e.isEqual(t)?rs.resolve():this.mn(s,r,n,e,t)}))))})}gn(e,t,n,r){return Pu(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.an(n,t.key),documentKey:t.key.path.toArray()})}yn(e,t,n,r){return Pu(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.an(n,t.key),t.key.path.toArray()])}_n(e,n,r){const t=Pu(e);let s=new wi(Tu);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.an(r,n)])},(e,t)=>{s=s.add(new Eu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>s)}wn(e,t){let n=new wi(Tu);var r=this.cn(t,e);if(null==r)return n;const s=Qr(t);if(null!=s){var i=e.data.field(s.fieldPath);if(Us(i))for(const s of i.arrayValue.values||[])n=n.add(new Eu(t.indexId,e.key,this.rn(s),r))}else n=n.add(new Eu(t.indexId,e.key,Fu,r));return n}mn(t,n,r,c,e){yr("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,n,r,s){var i=c.getIterator(),a=e.getIterator();let o=bi(i),u=bi(a);for(;o||u;){let e=!1,t=!1;if(o&&u){const r=n(o,u);r<0?t=!0:0<r&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(u),u=bi(a)):t?(s(o),o=bi(i)):(o=bi(i),u=bi(a))}}(e,Tu,e=>{s.push(this.gn(t,n,r,e))},e=>{s.push(this.yn(t,n,r,e))}),rs.waitFor(s)}dn(e){let r=1;return Bu(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>Tu(e,t)).filter((e,t,n)=>!t||0!==Tu(e,n[t-1]));const r=[];r.push(e);for(const s of n){const n=Tu(s,e),i=Tu(s,t);if(0===n)r[0]=e.Ue();else if(0<n&&i<0)r.push(s),r.push(s.Ue());else if(0<i)break}r.push(t);const s=[];for(let a=0;a<r.length;a+=2){if(this.pn(r[a],r[a+1]))return[];const t=[r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,Fu,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,Fu,[]];s.push(IDBKeyRange.bound(t,n))}return s}pn(e,t){return 0<Tu(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Uu)}getMinOffset(t,e){return rs.mapArray(this.Ze(e),e=>this.tn(t,e).next(e=>e||br())).next(Uu)}}function Vu(e){return Wo(e,"collectionParents")}function Pu(e){return Wo(e,"indexEntries")}function qu(e){return Wo(e,"indexConfiguration")}function Bu(e){return Wo(e,"indexState")}function Uu(e){Er(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let s=1;s<e.length;s++){var r=e[s].indexState.offset;Zr(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new Jr(t.readTime,t.documentKey,n)}const Gu={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Ku{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Ku(e,Ku.DEFAULT_COLLECTION_PERCENTILE,Ku.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function ju(e,t,n){const r=e.store("mutations"),s=e.store("documentMutations"),i=[],a=IDBKeyRange.only(n.batchId);let o=0;const u=r.Z({range:a},(e,t,n)=>(o++,n.delete()));i.push(u.next(()=>{Er(1===o)}));const c=[];for(const e of n.mutations){const r=xo(t,e.key.path,n.batchId);i.push(s.delete(r)),c.push(e.key)}return rs.waitFor(i).next(()=>c)}function $u(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw br();t=e.noDocument}return JSON.stringify(t).length}Ku.DEFAULT_COLLECTION_PERCENTILE=10,Ku.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Ku.DEFAULT=new Ku(41943040,Ku.DEFAULT_COLLECTION_PERCENTILE,Ku.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Ku.DISABLED=new Ku(-1,0,0);class Qu{constructor(e,t,n,r){this.userId=e,this.yt=t,this.indexManager=n,this.referenceDelegate=r,this.In={}}static re(e,t,n,r){Er(""!==e.uid);var s=e.isAuthenticated()?e.uid:"";return new Qu(s,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Wu(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=Hu(h),m=Wu(h);return m.add({}).next(e=>{Er("number"==typeof e);const t=new Ho(e,l,d,f),n=(s=this.yt,i=this.userId,a=t,o=a.baseMutations.map(e=>ho(s.ie,e)),u=a.mutations.map(e=>ho(s.ie,e)),{userId:i,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var s,i,a,o,u;let c=new wi((e,t)=>Fr(e.canonicalString(),t.canonicalString()));for(const h of f){const l=xo(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,Do))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.In[e]=t.keys()}),rs.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return Wu(e).get(t).next(e=>e?(Er(e.userId===this.userId),su(this.yt,e)):null)}Tn(e,n){return this.In[n]?rs.resolve(this.In[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.In[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let s=null;return Wu(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Er(t.batchId>=r),s=su(this.yt,t)),n.done()}).next(()=>s)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return Wu(e).Z({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Wu(e).W("userMutationsIndex",t).next(e=>e.map(e=>su(this.yt,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=So(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return Hu(a).Z({range:t},(e,t,n)=>{var[r,s,i]=e,s=To(s);if(r===this.userId&&o.path.isEqual(s))return Wu(a).get(i).next(e=>{if(!e)throw br();Er(e.userId===this.userId),u.push(su(this.yt,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new wi(Fr);const n=[];return e.forEach(a=>{var e=So(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=Hu(t).Z({range:e},(e,t,n)=>{var[r,s,i]=e,s=To(s);r===this.userId&&a.path.isEqual(s)?o=o.add(i):n.done()});n.push(e)}),rs.waitFor(n).next(()=>this.En(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=So(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new wi(Fr);return Hu(e).Z({range:r},(e,t,n)=>{var[r,s,i]=e,s=To(s);r===this.userId&&a.isPrefixOf(s)?s.length===o&&(u=u.add(i)):n.done()}).next(()=>this.En(e,u))}En(t,e){const n=[],r=[];return e.forEach(e=>{r.push(Wu(t).get(e).next(e=>{if(null===e)throw br();Er(e.userId===this.userId),n.push(su(this.yt,e))}))}),rs.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return ju(t.se,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.An(n.batchId)}),rs.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}An(e){delete this.In[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return rs.resolve();var t=IDBKeyRange.lowerBound([this.userId]);const r=[];return Hu(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=To(e[1]);r.push(t)}else n.done()}).next(()=>{Er(0===r.length)})})}containsKey(e,t){return zu(e,this.userId,t)}Rn(e){return Yu(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function zu(e,i,t){const n=So(i,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return Hu(e).Z({range:r,X:!0},(e,t,n)=>{var[r,s]=e;r===i&&s===a&&(o=!0),n.done()}).next(()=>o)}function Wu(e){return Wo(e,"mutations")}function Hu(e){return Wo(e,"documentMutations")}function Yu(e){return Wo(e,"mutationQueues")}class Xu{constructor(e){this.bn=e}next(){return this.bn+=2,this.bn}static Pn(){return new Xu(0)}static vn(){return new Xu(-1)}}class Ju{constructor(e,t){this.referenceDelegate=e,this.yt=t}allocateTargetId(n){return this.Vn(n).next(e=>{const t=new Xu(e.highestTargetId);return e.highestTargetId=t.next(),this.Sn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Vn(e).next(e=>qr.fromTimestamp(new Pr(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Vn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Vn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.Sn(t,e)))}addTargetData(t,n){return this.Dn(t,n).next(()=>this.Vn(t).next(e=>(e.targetCount+=1,this.Cn(n,e),this.Sn(t,e))))}updateTargetData(e,t){return this.Dn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Zu(t).delete(e.targetId)).next(()=>this.Vn(t)).next(e=>(Er(0<e.targetCount),--e.targetCount,this.Sn(t,e)))}removeTargets(r,s,i){let a=0;const o=[];return Zu(r).Z((e,t)=>{var n=iu(t);n.sequenceNumber<=s&&null===i.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>rs.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Zu(e).Z((e,t)=>{var n=iu(t);r(n)})}Vn(e){return ec(e).get("targetGlobalKey").next(e=>(Er(null!==e),e))}Sn(e,t){return ec(e).put("targetGlobalKey",t)}Dn(e,t){return Zu(e).put(au(this.yt,t))}Cn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Vn(e).next(e=>e.targetCount)}getTargetData(e,s){var t=Di(s),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let i=null;return Zu(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=iu(t);Ai(s,r.target)&&(i=r,n.done())}).next(()=>i)}addMatchingKeys(n,e,r){const s=[],i=tc(n);return e.forEach(e=>{var t=bo(e.path);s.push(i.put({targetId:r,path:t})),s.push(this.referenceDelegate.addReference(n,r,e))}),rs.waitFor(s)}removeMatchingKeys(n,e,r){const s=tc(n);return rs.forEach(e,e=>{var t=bo(e.path);return rs.waitFor([s.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=tc(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=tc(e);let s=Oa();return r.Z({range:n,X:!0},(e,t,n)=>{var r=To(e[1]),r=new jr(r);s=s.add(r)}).next(()=>s)}containsKey(e,t){var n=bo(t.path),n=IDBKeyRange.bound([n],[Vr(n)],!1,!0);let r=0;return tc(e).Z({index:"documentTargetsIndex",X:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}ne(e,t){return Zu(e).get(t).next(e=>e?iu(e):null)}}function Zu(e){return Wo(e,"targets")}function ec(e){return Wo(e,"targetGlobal")}function tc(e){return Wo(e,"targetDocuments")}function nc([e,t],[n,r]){var s=Fr(e,n);return 0===s?Fr(t,r):s}class rc{constructor(e){this.xn=e,this.buffer=new wi(nc),this.Nn=0}kn(){return++this.Nn}On(e){var t=[e,this.kn()];if(this.buffer.size<this.xn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();nc(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class sc{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Mn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Fn(6e4)}stop(){this.Mn&&(this.Mn.cancel(),this.Mn=null)}get started(){return null!==this.Mn}Fn(e){yr("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Mn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Mn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){us(e)?yr("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await ns(e)}await this.Fn(3e5)})}}class ic{constructor(e,t){this.$n=e,this.params=t}calculateTargetCount(e,t){return this.$n.Bn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return rs.resolve(ms.at);const n=new rc(t);return this.$n.forEachTarget(e,e=>n.On(e.sequenceNumber)).next(()=>this.$n.Ln(e,e=>n.On(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.$n.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.$n.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(yr("LruGarbageCollector","Garbage collection skipped; disabled"),rs.resolve(Gu)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(yr("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Gu):this.qn(t,n))}getCacheSize(e){return this.$n.getCacheSize(e)}qn(t,n){let r,s,i,a,o,u,c;const h=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(s=e>this.params.maximumSequenceNumbersToCollect?(yr("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,s))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(i=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),pr()<=l.DEBUG&&yr("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-h}ms\n\tDetermined least recently used ${s} in `+(o-a)+"ms\n"+`\tRemoved ${i} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),rs.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:e})))}}class ac{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new ic(e,t))}Bn(e){const n=this.Un(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Un(e){let t=0;return this.Ln(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Ln(e,n){return this.Kn(e,(e,t)=>n(t))}addReference(e,t,n){return oc(e,n)}removeReference(e,t,n){return oc(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return oc(e,t)}Gn(t,n){let r=!1;return Yu(t).tt(e=>zu(t,e,n).next(e=>(e&&(r=!0),rs.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),i=[];let a=0;return this.Kn(n,(t,e)=>{if(e<=r){const r=this.Gn(n,t).next(e=>{if(!e)return a++,s.getEntry(n,t).next(()=>(s.removeEntry(t,qr.min()),tc(n).delete([0,bo(t.path)])))});i.push(r)}}).next(()=>rs.waitFor(i)).next(()=>s.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return oc(e,t)}Kn(e,r){const t=tc(e);let s,i=ms.at;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(i!==ms.at&&r(new jr(To(s)),i),i=n,s=t):i=ms.at}).next(()=>{i!==ms.at&&r(new jr(To(s)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function oc(e,t){return tc(e).put((e=e.currentSequenceNumber,{targetId:0,path:bo(t.path),sequenceNumber:e}))}class uc{constructor(){this.changes=new Aa(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,_i.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?rs.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class cc{constructor(e){this.yt=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return fc(e).put(n)}removeEntry(e,n,t){return fc(e).delete(function(e){const t=n.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],tu(e),t[t.length-1]]}(t))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Qn(t,e)))}getEntry(e,n){let r=_i.newInvalidDocument(n);return fc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(gc(n))},(e,t)=>{r=this.jn(n,t)}).next(()=>r)}Wn(e,n){let r={size:0,document:_i.newInvalidDocument(n)};return fc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(gc(n))},(e,t)=>{r={document:this.jn(n,t),size:$u(t)}}).next(()=>r)}getEntries(e,t){let r=Ca;return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n)}).next(()=>r)}Hn(e,t){let r=Ca,s=new pi(jr.comparator);return this.zn(e,t,(e,t)=>{var n=this.jn(e,t);r=r.insert(e,n),s=s.insert(e,$u(t))}).next(()=>({documents:r,Jn:s}))}zn(e,t,s){if(t.isEmpty())return rs.resolve();let n=new wi(pc);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(gc(n.first()),gc(n.last())),i=n.getIterator();let a=i.getNext();return fc(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=jr.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&pc(a,r)<0;)s(a,null),a=i.getNext();a&&a.isEqual(r)&&(s(a,t),a=i.hasNext()?i.getNext():null),a?n.j(gc(a)):n.done()}).next(()=>{for(;a;)s(a,null),a=i.hasNext()?i.getNext():null})}getAllFromCollection(e,t,n){var r=[t.popLast().toArray(),t.lastSegment(),tu(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],s=[t.popLast().toArray(),t.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return fc(e).W(IDBKeyRange.bound(r,s,!0)).next(e=>{let t=Ca;for(const n of e){const e=this.jn(jr.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);t=t.insert(e.key,e)}return t})}getAllFromCollectionGroup(e,t,n,s){let i=Ca;var r=mc(t,n),a=mc(t,Jr.max());return fc(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.jn(jr.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(r.key,r),i.size===s&&n.done()}).next(()=>i)}newChangeBuffer(e){return new lc(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return dc(e).get("remoteDocumentGlobalKey").next(e=>(Er(!!e),e))}Qn(e,t){return dc(e).put("remoteDocumentGlobalKey",t)}jn(e,t){if(t){const e=function(e,t){let n;if(t.document)n=co(e.ie,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=jr.fromSegments(t.noDocument.path),s=ru(t.noDocument.readTime);n=_i.newNoDocument(e,s),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return br();{const e=jr.fromSegments(t.unknownDocument.path),i=ru(t.unknownDocument.version);n=_i.newUnknownDocument(e,i)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new Pr(t[0],t[1]),qr.fromTimestamp(r))),n;var r}(this.yt,t);if(!e.isNoDocument()||!e.version.isEqual(qr.min()))return e}return _i.newInvalidDocument(e)}}function hc(e){return new cc(e)}class lc extends uc{constructor(e,t){super(),this.Yn=e,this.trackRemovals=t,this.Xn=new Aa(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(i){const a=[];let o=0,u=new wi((e,t)=>Fr(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.Xn.get(e);if(a.push(this.Yn.removeEntry(i,e,n.readTime)),t.isValidDocument()){var r=eu(this.Yn.yt,t);u=u.add(e.path.popLast());var s=$u(r);o+=s-n.size,a.push(this.Yn.addEntry(i,e,r))}else if(o-=n.size,this.trackRemovals){const o=eu(this.Yn.yt,t.convertToNoDocument(qr.min()));a.push(this.Yn.addEntry(i,e,o))}}),u.forEach(e=>{a.push(this.Yn.indexManager.addToCollectionParentIndex(i,e))}),a.push(this.Yn.updateMetadata(i,o)),rs.waitFor(a)}getFromCache(e,t){return this.Yn.Wn(e,t).next(e=>(this.Xn.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Yn.Hn(e,t).next(({documents:n,Jn:e})=>(e.forEach((e,t)=>{this.Xn.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function dc(e){return Wo(e,"remoteDocumentGlobal")}function fc(e){return Wo(e,"remoteDocumentsV14")}function gc(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function mc(e,t){const n=t.documentKey.path.toArray();return[e,tu(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function pc(e,t){var n=e.path.toArray(),r=t.path.toArray();let s=0;for(let i=0;i<n.length-2&&i<r.length-2;++i)if(s=Fr(n[i],r[i]),s)return s;return s=Fr(n.length,r.length),s||(s=Fr(n[n.length-2],r[r.length-2]),s||Fr(n[n.length-1],r[r.length-1]))}class yc{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class vc{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&pa(r.mutation,e,Ei.empty(),Pr.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,Oa()).next(()=>e))}getLocalViewOfDocuments(e,t,n=Oa()){const r=La();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=ka();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=La();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Oa()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,s){let i=Ca;const a=La(),o=La();return t.forEach((e,t)=>{const n=r.get(t.key);s.has(t.key)&&(void 0===n||n.mutation instanceof wa)?i=i.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),pa(n.mutation,t,n.mutation.getFieldMask(),Pr.now())):a.set(t.key,Ei.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new yc(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(i,a){const o=La();let u=new pi((e,t)=>e-t),c=Oa();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(i,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||Ei.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(u.get(r.batchId)||Oa()).add(e),u=u.insert(r.batchId,t))})}).next(()=>{const e=[],t=u.getReverseIterator();for(;t.hasNext();){const u=t.getNext(),n=u.key,r=u.value,s=La();r.forEach(e=>{var t;c.has(e)||(null!==(t=ga(a.get(e),o.get(e)))&&s.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(i,n,s))}return rs.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,jr.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):qi(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n);var r}getNextDocuments(i,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(i,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(i,t,a.largestBatchId,o-n.size):rs.resolve(La());let r=-1,s=n;return e.next(e=>rs.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?rs.resolve():this.remoteDocumentCache.getEntry(i,t).next(e=>{s=s.insert(t,e)}))).next(()=>this.populateOverlays(i,e,n)).next(()=>this.computeViews(i,s,e,Oa())).next(e=>({batchId:r,changes:Ra(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new jr(t)).next(e=>{let t=ka();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,s,i){const a=s.collectionGroup;let o=ka();return this.indexManager.getCollectionParents(r,a).next(e=>rs.forEach(e,e=>{var t,n=(t=s,e=e.child(a),new Li(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,i).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}getDocumentsMatchingCollectionQuery(t,i,n){let a;return this.remoteDocumentCache.getAllFromCollection(t,i.path,n).next(e=>(a=e,this.documentOverlayCache.getOverlaysForCollection(t,i.path,n.largestBatchId))).next(r=>{r.forEach((e,t)=>{var n=t.getKey();null===a.get(n)&&(a=a.insert(n,_i.newInvalidDocument(n)))});let s=ka();return a.forEach((e,t)=>{var n=r.get(e);void 0!==n&&pa(n.mutation,t,Ei.empty(),Pr.now()),zi(i,t)&&(s=s.insert(e,t))}),s})}}class wc{constructor(e){this.yt=e,this.Zn=new Map,this.ts=new Map}getBundleMetadata(e,t){return rs.resolve(this.Zn.get(t))}saveBundleMetadata(e,t){return this.Zn.set(t.id,{id:t.id,version:t.version,createTime:Za(t.createTime)}),rs.resolve()}getNamedQuery(e,t){return rs.resolve(this.ts.get(t))}saveNamedQuery(e,t){return this.ts.set(t.name,{name:(t=t).name,query:ou(t.bundledQuery),readTime:Za(t.readTime)}),rs.resolve()}}class Ic{constructor(){this.overlays=new pi(jr.comparator),this.es=new Map}getOverlay(e,t){return rs.resolve(this.overlays.get(t))}getOverlays(e,t){const n=La();return rs.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.oe(n,r,t)}),rs.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.es.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.es.delete(n)),rs.resolve()}getOverlaysForCollection(e,t,n){const r=La(),s=t.length+1,i=new jr(t.child("")),a=this.overlays.getIteratorFrom(i);for(;a.hasNext();){const e=a.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return rs.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let s=new pi((e,t)=>e-t);const i=this.overlays.getIterator();for(;i.hasNext();){const t=i.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=s.get(t.largestBatchId);null===e&&(e=La(),s=s.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=La(),o=s.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return rs.resolve(a)}oe(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.es.get(r.largestBatchId).delete(n.key);this.es.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new Xo(t,n));let s=this.es.get(t);void 0===s&&(s=Oa(),this.es.set(t,s)),this.es.set(t,s.add(n.key))}}class bc{constructor(){this.ns=new wi(Ec.ss),this.rs=new wi(Ec.os)}isEmpty(){return this.ns.isEmpty()}addReference(e,t){var n=new Ec(e,t);this.ns=this.ns.add(n),this.rs=this.rs.add(n)}us(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.cs(new Ec(e,t))}hs(e,t){e.forEach(e=>this.removeReference(e,t))}ls(e){const t=new jr(new Ur([])),n=new Ec(t,e),r=new Ec(t,e+1),s=[];return this.rs.forEachInRange([n,r],e=>{this.cs(e),s.push(e.key)}),s}fs(){this.ns.forEach(e=>this.cs(e))}cs(e){this.ns=this.ns.delete(e),this.rs=this.rs.delete(e)}ds(e){var t=new jr(new Ur([])),n=new Ec(t,e),t=new Ec(t,e+1);let r=Oa();return this.rs.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Ec(e,0),t=this.ns.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Ec{constructor(e,t){this.key=e,this._s=t}static ss(e,t){return jr.comparator(e.key,t.key)||Fr(e._s,t._s)}static os(e,t){return Fr(e._s,t._s)||jr.comparator(e.key,t.key)}}class Tc{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.ws=1,this.gs=new wi(Ec.ss)}checkEmpty(e){return rs.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var s=this.ws;this.ws++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var i=new Ho(s,t,n,r);this.mutationQueue.push(i);for(const t of r)this.gs=this.gs.add(new Ec(t.key,s)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return rs.resolve(i)}lookupMutationBatch(e,t){return rs.resolve(this.ys(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.ps(t+1),n=n<0?0:n;return rs.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return rs.resolve(0===this.mutationQueue.length?-1:this.ws-1)}getAllMutationBatches(e){return rs.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Ec(t,0),r=new Ec(t,Number.POSITIVE_INFINITY),s=[];return this.gs.forEachInRange([n,r],e=>{var t=this.ys(e._s);s.push(t)}),rs.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new wi(Fr);return t.forEach(e=>{var t=new Ec(e,0),n=new Ec(e,Number.POSITIVE_INFINITY);this.gs.forEachInRange([t,n],e=>{r=r.add(e._s)})}),rs.resolve(this.Is(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;jr.isDocumentKey(s)||(s=s.child(""));var i=new Ec(new jr(s),0);let a=new wi(Fr);return this.gs.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e._s)),!0)},i),rs.resolve(this.Is(a))}Is(e){const n=[];return e.forEach(e=>{var t=this.ys(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Er(0===this.Ts(r.batchId,"removed")),this.mutationQueue.shift();let s=this.gs;return rs.forEach(r.mutations,e=>{var t=new Ec(e.key,r.batchId);return s=s.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.gs=s})}An(e){}containsKey(e,t){var n=new Ec(t,0),n=this.gs.firstAfterOrEqual(n);return rs.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,rs.resolve()}Ts(e,t){return this.ps(e)}ps(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}ys(e){var t=this.ps(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class _c{constructor(e){this.Es=e,this.docs=new pi(jr.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),s=r?r.size:0,i=this.Es(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return rs.resolve(n?n.document.mutableCopy():_i.newInvalidDocument(t))}getEntries(e,t){let n=Ca;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():_i.newInvalidDocument(e))}),rs.resolve(n)}getAllFromCollection(e,t,n){let r=Ca;const s=new jr(t.child("")),i=this.docs.getIteratorFrom(s);for(;i.hasNext();){const{key:e,value:{document:s}}=i.getNext();if(!t.isPrefixOf(e.path))break;e.path.length>t.length+1||Zr(Xr(s),n)<=0||(r=r.insert(s.key,s.mutableCopy()))}return rs.resolve(r)}getAllFromCollectionGroup(e,t,n,r){br()}As(e,t){return rs.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Sc(this)}getSize(e){return rs.resolve(this.size)}}class Sc extends uc{constructor(e){super(),this.Yn=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Yn.addEntry(n,t)):this.Yn.removeEntry(e)}),rs.waitFor(r)}getFromCache(e,t){return this.Yn.getEntry(e,t)}getAllFromCache(e,t){return this.Yn.getEntries(e,t)}}class xc{constructor(e){this.persistence=e,this.Rs=new Aa(e=>Di(e),Ai),this.lastRemoteSnapshotVersion=qr.min(),this.highestTargetId=0,this.bs=0,this.Ps=new bc,this.targetCount=0,this.vs=Xu.Pn()}forEachTarget(e,n){return this.Rs.forEach((e,t)=>n(t)),rs.resolve()}getLastRemoteSnapshotVersion(e){return rs.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return rs.resolve(this.bs)}allocateTargetId(e){return this.highestTargetId=this.vs.next(),rs.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),rs.resolve()}Dn(e){this.Rs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.vs=new Xu(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}addTargetData(e,t){return this.Dn(t),this.targetCount+=1,rs.resolve()}updateTargetData(e,t){return this.Dn(t),rs.resolve()}removeTargetData(e,t){return this.Rs.delete(t.target),this.Ps.ls(t.targetId),--this.targetCount,rs.resolve()}removeTargets(n,r,s){let i=0;const a=[];return this.Rs.forEach((e,t)=>{t.sequenceNumber<=r&&null===s.get(t.targetId)&&(this.Rs.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),i++)}),rs.waitFor(a).next(()=>i)}getTargetCount(e){return rs.resolve(this.targetCount)}getTargetData(e,t){var n=this.Rs.get(t)||null;return rs.resolve(n)}addMatchingKeys(e,t,n){return this.Ps.us(t,n),rs.resolve()}removeMatchingKeys(t,e,n){this.Ps.hs(e,n);const r=this.persistence.referenceDelegate,s=[];return r&&e.forEach(e=>{s.push(r.markPotentiallyOrphaned(t,e))}),rs.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.Ps.ls(t),rs.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Ps.ds(t);return rs.resolve(n)}containsKey(e,t){return rs.resolve(this.Ps.containsKey(t))}}class Dc{constructor(e,t){this.Vs={},this.overlays={},this.Ss=new ms(0),this.Ds=!1,this.Ds=!0,this.referenceDelegate=e(this),this.Cs=new xc(this),this.indexManager=new Lu,this.remoteDocumentCache=(e=e=>this.referenceDelegate.xs(e),new _c(e)),this.yt=new Zo(t),this.Ns=new wc(this.yt)}start(){return Promise.resolve()}shutdown(){return this.Ds=!1,Promise.resolve()}get started(){return this.Ds}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new Ic,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Vs[e.toKey()];return n||(n=new Tc(t,this.referenceDelegate),this.Vs[e.toKey()]=n),n}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ns}runTransaction(e,t,n){yr("MemoryPersistence","Starting transaction:",e);const r=new Ac(this.Ss.next());return this.referenceDelegate.ks(),n(r).next(e=>this.referenceDelegate.Os(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ms(t,n){return rs.or(Object.values(this.Vs).map(e=>()=>e.containsKey(t,n)))}}class Ac extends ts{constructor(e){super(),this.currentSequenceNumber=e}}class Cc{constructor(e){this.persistence=e,this.Fs=new bc,this.$s=null}static Bs(e){return new Cc(e)}get Ls(){if(this.$s)return this.$s;throw br()}addReference(e,t,n){return this.Fs.addReference(n,t),this.Ls.delete(n.toString()),rs.resolve()}removeReference(e,t,n){return this.Fs.removeReference(n,t),this.Ls.add(n.toString()),rs.resolve()}markPotentiallyOrphaned(e,t){return this.Ls.add(t.toString()),rs.resolve()}removeTarget(e,t){this.Fs.ls(t.targetId).forEach(e=>this.Ls.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Ls.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}ks(){this.$s=new Set}Os(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return rs.forEach(this.Ls,e=>{const t=jr.fromPath(e);return this.qs(n,t).next(e=>{e||r.removeEntry(t,qr.min())})}).next(()=>(this.$s=null,r.apply(n)))}updateLimboDocument(e,t){return this.qs(e,t).next(e=>{e?this.Ls.delete(t.toString()):this.Ls.add(t.toString())})}xs(e){return 0}qs(e,t){return rs.or([()=>rs.resolve(this.Fs.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ms(e,t)])}}class Nc{constructor(e){this.yt=e}$(t,e,n,r){const s=new ss("createOrUpgrade",e);var i;n<1&&1<=r&&(t.createObjectStore("owner"),(i=t).createObjectStore("mutationQueues",{keyPath:"userId"}),i.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",_o,{unique:!0}),i.createObjectStore("documentMutations"),kc(t),t.createObjectStore("remoteDocuments"));let a=rs.resolve();return n<3&&3<=r&&(0!==n&&((i=t).deleteObjectStore("targetDocuments"),i.deleteObjectStore("targets"),i.deleteObjectStore("targetGlobal"),kc(t)),a=a.next(()=>function(){const e=s.store("targetGlobal"),t={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:qr.min().toTimestamp(),targetCount:0};return e.put("targetGlobalKey",t)}())),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,s){return s.store("mutations").W().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",_o,{unique:!0});const t=s.store("mutations"),n=e.map(e=>t.put(e));return rs.waitFor(n)})}(t,s))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Us(s))),n<6&&6<=r&&(a=a.next(()=>(t.createObjectStore("remoteDocumentGlobal"),this.Ks(s)))),n<7&&7<=r&&(a=a.next(()=>this.Gs(s))),n<8&&8<=r&&(a=a.next(()=>this.Qs(t,s))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.js(s))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(){const e=t.createObjectStore("documentOverlays",{keyPath:qo});e.createIndex("collectionPathOverlayIndex",Bo,{unique:!1}),e.createIndex("collectionGroupOverlayIndex",Uo,{unique:!1})}()})),n<13&&13<=r&&(a=a.next(()=>function(){const e=t.createObjectStore("remoteDocumentsV14",{keyPath:Ao});e.createIndex("documentKeyIndex",Co),e.createIndex("collectionGroupIndex",No)}()).next(()=>this.Ws(t,s)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.zs(t,s))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Fo}).createIndex("sequenceNumberIndex",Oo,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Vo}).createIndex("documentKeyIndex",Po,{unique:!1})}(t))),a}Ks(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=$u(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Us(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.W().next(e=>rs.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.W("userMutationsIndex",e).next(e=>rs.forEach(e,e=>{Er(e.userId===n.userId);var t=su(this.yt,e);return ju(r,n.userId,t).next(()=>{})}))}))}Gs(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(s=>{const i=[];return t.Z((e,t)=>{const n=new Ur(e),r=[0,bo(n)];i.push(a.get(r).next(e=>e?rs.resolve():(e=>a.put({targetId:0,path:bo(e),sequenceNumber:s.highestListenSequenceNumber}))(n)))}).next(()=>rs.waitFor(i))})}Qs(e,t){e.createObjectStore("collectionParents",{keyPath:Mo});const n=t.store("collectionParents"),r=new Mu,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:bo(r)})}};return t.store("remoteDocuments").Z({X:!0},(e,t)=>{const n=new Ur(e);return s(n.popLast())}).next(()=>t.store("documentMutations").Z({X:!0},([,e],t)=>{const n=To(e);return s(n.popLast())}))}js(e){const r=e.store("targets");return r.Z((e,t)=>{var n=iu(t),n=au(this.yt,n);return r.put(n)})}Ws(e,i){const t=i.store("remoteDocuments"),a=[];return t.Z((e,t)=>{const n=i.store("remoteDocumentsV14"),r=((s=t).document?new jr(Ur.fromString(s.document.name).popFirst(5)):s.noDocument?jr.fromSegments(s.noDocument.path):s.unknownDocument?jr.fromSegments(s.unknownDocument.path):br()).path.toArray();var s={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};a.push(n.put(s))}).next(()=>rs.waitFor(a))}zs(e,i){const t=i.store("mutations"),a=hc(this.yt),o=new Dc(Cc.Bs,this.yt.ie);return t.W().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:Oa();su(this.yt,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),rs.forEach(r,(e,t)=>{var n=new fr(t),r=gu.re(this.yt,n),s=o.getIndexManager(n),n=Qu.re(n,this.yt,s,o.referenceDelegate);return new vc(a,n,r,s).recalculateAndSaveOverlaysForDocumentKeys(new zo(i,ms.at),e).next()})})}}function kc(e){e.createObjectStore("targetDocuments",{keyPath:Ro}).createIndex("documentTargetsIndex",Lo,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",ko,{unique:!0}),e.createObjectStore("targetGlobal")}const Rc="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class Lc{constructor(e,t,n,r,s,i,a,o,u,c,h=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Hs=s,this.window=i,this.document=a,this.Js=u,this.Ys=c,this.Xs=h,this.Ss=null,this.Ds=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Zs=null,this.inForeground=!1,this.ti=null,this.ei=null,this.ni=Number.NEGATIVE_INFINITY,this.si=e=>Promise.resolve(),!Lc.C())throw new _r(Tr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new ac(this,r),this.ii=t+"main",this.yt=new Zo(o),this.ri=new is(this.ii,this.Xs,new Nc(this.yt)),this.Cs=new Ju(this.referenceDelegate,this.yt),this.remoteDocumentCache=hc(this.yt),this.Ns=new lu,this.window&&this.window.localStorage?this.oi=this.window.localStorage:(this.oi=null,!1===c&&vr("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.ui().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new _r(Tr.FAILED_PRECONDITION,Rc);return this.ci(),this.ai(),this.hi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Cs.getHighestSequenceNumber(e))}).then(e=>{this.Ss=new ms(e,this.Js)}).then(()=>{this.Ds=!0}).catch(e=>(this.ri&&this.ri.close(),Promise.reject(e)))}li(t){return this.si=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.ri.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Hs.enqueueAndForget(async()=>{this.started&&await this.ui()}))}ui(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>Fc(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.fi(t).next(e=>{e||(this.isPrimary=!1,this.Hs.enqueueRetryable(()=>this.si(!1)))})}).next(()=>this.di(t)).next(e=>this.isPrimary&&!e?this._i(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(us(e))return yr("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return yr("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Hs.enqueueRetryable(()=>this.si(e)),this.isPrimary=e})}fi(e){return Mc(e).get("owner").next(e=>rs.resolve(this.mi(e)))}gi(e){return Fc(e).delete(this.clientId)}async yi(){if(this.isPrimary&&!this.pi(this.ni,18e5)){this.ni=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=Wo(e,"clientMetadata");return r.W().next(e=>{const t=this.Ii(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return rs.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.oi)for(const t of e)this.oi.removeItem(this.Ti(t.clientId))}}hi(){this.ei=this.Hs.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.ui().then(()=>this.yi()).then(()=>this.hi()))}mi(e){return!!e&&e.ownerId===this.clientId}di(t){return this.Ys?rs.resolve(!0):Mc(t).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)){if(this.mi(e)&&this.networkEnabled)return!0;if(!this.mi(e)){if(!e.allowTabSynchronization)throw new _r(Tr.FAILED_PRECONDITION,Rc);return!1}}return!(!this.networkEnabled||!this.inForeground)||Fc(t).W().next(e=>void 0===this.Ii(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&yr("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Ds=!1,this.Ai(),this.ei&&(this.ei.cancel(),this.ei=null),this.Ri(),this.bi(),await this.ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new zo(e,ms.at);return this._i(t).next(()=>this.gi(t))}),this.ri.close(),this.Pi()}Ii(e,t){return e.filter(e=>this.pi(e.updateTimeMs,t)&&!this.Ei(e.clientId))}vi(){return this.runTransaction("getActiveClients","readonly",e=>Fc(e).W().next(e=>this.Ii(e,18e5).map(e=>e.clientId)))}get started(){return this.Ds}getMutationQueue(e,t){return Qu.re(e,this.yt,t,this.referenceDelegate)}getTargetCache(){return this.Cs}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Ou(e,this.yt.ie.databaseId)}getDocumentOverlayCache(e){return gu.re(this.yt,e)}getBundleCache(){return this.Ns}runTransaction(t,n,r){yr("IndexedDbPersistence","Starting transaction:",t);var e,s="readonly"===n?"readonly":"readwrite",e=15===(e=this.Xs)?Qo:14===e?$o:13===e?jo:12===e?Ko:11===e?Go:void br();let i;return this.ri.runTransaction(t,s,e,e=>(i=new zo(e,this.Ss?this.Ss.next():ms.at),"readwrite-primary"===n?this.fi(i).next(e=>!!e||this.di(i)).next(e=>{if(!e)throw vr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Hs.enqueueRetryable(()=>this.si(!1)),new _r(Tr.FAILED_PRECONDITION,es);return r(i)}).next(e=>this.wi(i).next(()=>e)):this.Vi(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Vi(e){return Mc(e).get("owner").next(e=>{if(null!==e&&this.pi(e.leaseTimestampMs,5e3)&&!this.Ei(e.ownerId)&&!this.mi(e)&&!(this.Ys||this.allowTabSynchronization&&e.allowTabSynchronization))throw new _r(Tr.FAILED_PRECONDITION,Rc)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Mc(e).put("owner",t)}static C(){return is.C()}_i(e){const t=Mc(e);return t.get("owner").next(e=>this.mi(e)?(yr("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):rs.resolve())}pi(e,t){var n=Date.now();return!(e<n-t||n<e&&(vr(`Detected an update time that is in the future: ${e} > ${n}`),1))}ci(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ti=()=>{this.Hs.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.ui()))},this.document.addEventListener("visibilitychange",this.ti),this.inForeground="visible"===this.document.visibilityState)}Ri(){this.ti&&(this.document.removeEventListener("visibilitychange",this.ti),this.ti=null)}ai(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Zs=()=>{this.Ai(),c()&&navigator.appVersion.match(/Version\/1[45]/)&&this.Hs.enterRestrictedMode(!0),this.Hs.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Zs))}bi(){this.Zs&&(this.window.removeEventListener("pagehide",this.Zs),this.Zs=null)}Ei(e){var t;try{var n=null!==(null===(t=this.oi)||void 0===t?void 0:t.getItem(this.Ti(e)));return yr("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return vr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Ai(){if(this.oi)try{this.oi.setItem(this.Ti(this.clientId),String(Date.now()))}catch(e){vr("Failed to set zombie client id.",e)}}Pi(){if(this.oi)try{this.oi.removeItem(this.Ti(this.clientId))}catch(e){}}Ti(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function Mc(e){return Wo(e,"owner")}function Fc(e){return Wo(e,"clientMetadata")}function Oc(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Vc{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Si=n,this.Di=r}static Ci(e,t){let n=Oa(),r=Oa();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new Vc(e,t.fromCache,n,r)}}class Pc{constructor(){this.xi=!1}initialize(e,t){this.Ni=e,this.indexManager=t,this.xi=!0}getDocumentsMatchingQuery(t,n,r,s){return this.ki(t,n).next(e=>e||this.Oi(t,n,s,r)).next(e=>e||this.Mi(t,n))}ki(s,i){if(Oi(i))return rs.resolve(null);let t=Ui(i);return this.indexManager.getIndexType(s,t).next(e=>0===e?null:(null!==i.limit&&1===e&&(i=Ki(i,null,"F"),t=Ui(i)),this.indexManager.getDocumentsMatchingTarget(s,t).next(e=>{const r=Oa(...e);return this.Ni.getDocuments(s,r).next(n=>this.indexManager.getMinOffset(s,t).next(e=>{var t=this.Fi(i,n);return this.$i(i,t,r,e.readTime)?this.ki(s,Ki(i,null,"F")):this.Bi(s,t,i,e)}))})))}Oi(n,r,s,i){return Oi(r)||i.isEqual(qr.min())?this.Mi(n,r):this.Ni.getDocuments(n,s).next(e=>{var t=this.Fi(r,e);return this.$i(r,t,s,i)?this.Mi(n,r):(pr()<=l.DEBUG&&yr("QueryEngine","Re-using previous result from %s to execute query: %s",i.toString(),Qi(r)),this.Bi(n,t,r,Yr(i,-1)))})}Fi(n,e){let r=new wi(Hi(n));return e.forEach((e,t)=>{zi(n,t)&&(r=r.add(t))}),r}$i(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||0<s.version.compareTo(r))}Mi(e,t){return pr()<=l.DEBUG&&yr("QueryEngine","Using full collection scan to execute query:",Qi(t)),this.Ni.getDocumentsMatchingQuery(e,t,Jr.min())}Bi(e,n,t,r){return this.Ni.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class qc{constructor(e,t,n,r){this.persistence=e,this.Li=t,this.yt=r,this.qi=new pi(Fr),this.Ui=new Aa(e=>Di(e),Ai),this.Ki=new Map,this.Gi=e.getRemoteDocumentCache(),this.Cs=e.getTargetCache(),this.Ns=e.getBundleCache(),this.Qi(n)}Qi(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new vc(this.Gi,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Gi.setIndexManager(this.indexManager),this.Li.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.qi))}}function Bc(e,t,n,r){return new qc(e,t,n,r)}async function Uc(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",s=>{let i;return a.mutationQueue.getAllMutationBatches(s).next(e=>(i=e,a.Qi(t),a.mutationQueue.getAllMutationBatches(s))).next(e=>{const t=[],n=[];let r=Oa();for(const s of i){t.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}for(const s of e){n.push(s.batchId);for(const e of s.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(s,r).next(e=>({ji:e,removedBatchIds:t,addedBatchIds:n}))})})}function Gc(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Cs.getLastRemoteSnapshotVersion(e))}function Kc(e,c){const h=e,l=c.snapshotVersion;let d=h.qi;return h.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=h.Gi.newChangeBuffer({trackRemovals:!0});d=h.qi;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Cs.removeMatchingKeys(o,t.removedDocuments,n).next(()=>h.Cs.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var s,i,a;c.targetMismatches.has(n)?e=e.withResumeToken(_s.EMPTY_BYTE_STRING,qr.min()).withLastLimboFreeSnapshotVersion(qr.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),s=r,i=e,a=t,0!==s.resumeToken.approximateByteSize()&&!(3e8<=i.snapshotVersion.toMicroseconds()-s.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||u.push(h.Cs.updateTargetData(o,e))}});let t=Ca,n=Oa();if(c.documentUpdates.forEach(e=>{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(jc(o,e,c.documentUpdates).next(e=>{t=e.Wi,n=e.zi})),!l.isEqual(qr.min())){const c=h.Cs.getLastRemoteSnapshotVersion(o).next(e=>h.Cs.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(c)}return rs.waitFor(u).next(()=>e.apply(o)).next(()=>h.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(h.qi=d,e))}function jc(e,i,t){let n=Oa(),a=Oa();return t.forEach(e=>n=n.add(e)),i.getEntries(e,n).next(r=>{let s=Ca;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(qr.min())?(i.removeEntry(e,t.readTime),s=s.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(i.addEntry(t),s=s.insert(e,t)):yr("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{Wi:s,zi:a}})}function $c(e,r){const s=e;return s.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return s.Cs.getTargetData(t,r).next(e=>e?(n=e,rs.resolve(n)):s.Cs.allocateTargetId(t).next(e=>(n=new Jo(r,e,0,t.currentSequenceNumber),s.Cs.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=s.qi.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(s.qi=s.qi.insert(e.targetId,e),s.Ui.set(r,e.targetId)),e})}async function Qc(e,t,n){const r=e,s=r.qi.get(t),i=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",i,e=>r.persistence.referenceDelegate.removeTarget(e,s))}catch(e){if(!us(e))throw e;yr("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.qi=r.qi.remove(t),r.Ui.delete(s.target)}function zc(e,n,r){const s=e;let i=qr.min(),a=Oa();return s.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,s=r.Ui.get(n);return void 0!==s?rs.resolve(r.qi.get(s)):r.Cs.getTargetData(t,n)}(s,t,Ui(n)).next(e=>{if(e)return i=e.lastLimboFreeSnapshotVersion,s.Cs.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>s.Li.getDocumentsMatchingQuery(t,n,r?i:qr.min(),r?a:Oa())).next(e=>(Yc(s,Wi(n),e),{documents:e,Hi:a})))}function Wc(e,t){const n=e,r=n.Cs,s=n.qi.get(t);return s?Promise.resolve(s.target):n.persistence.runTransaction("Get target data","readonly",e=>r.ne(e,t).next(e=>e?e.target:null))}function Hc(e,t){const n=e,r=n.Ki.get(t)||qr.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.Gi.getAllFromCollectionGroup(e,t,Yr(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(Yc(n,t,e),e))}function Yc(e,t,n){let r=e.Ki.get(t)||qr.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.Ki.set(t,r)}function Xc(e,t){return`firestore_clients_${e}_${t}`}function Jc(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Zc(e,t){return`firestore_targets_${e}_${t}`}class eh{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Zi(e,t,n){var r=JSON.parse(n);let s,i="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code,i&&(s=new _r(r.error.code,r.error.message))),i?new eh(e,t,r.state,s):(vr("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class th{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Zi(e,t){var n=JSON.parse(t);let r,s="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code,s&&(r=new _r(n.error.code,n.error.message))),s?new th(e,n.state,r):(vr("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}tr(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class nh{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Zi(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,s=Va;for(let i=0;r&&i<n.activeTargetIds.length;++i)r=Ts(n.activeTargetIds[i]),s=s.add(n.activeTargetIds[i]);return r?new nh(e,s):(vr("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class rh{constructor(e,t){this.clientId=e,this.onlineState=t}static Zi(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new rh(t.clientId,t.onlineState):(vr("SharedClientState",`Failed to parse online state: ${e}`),null)}}class sh{constructor(){this.activeTargetIds=Va}er(e){this.activeTargetIds=this.activeTargetIds.add(e)}nr(e){this.activeTargetIds=this.activeTargetIds.delete(e)}tr(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class ih{constructor(e,t,n,r,s){this.window=e,this.Hs=t,this.persistenceKey=n,this.sr=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ir=this.rr.bind(this),this.ur=new pi(Fr),this.started=!1,this.cr=[];var i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=s,this.ar=Xc(this.persistenceKey,this.sr),this.hr=`firestore_sequence_number_${this.persistenceKey}`,this.ur=this.ur.insert(this.sr,new sh),this.lr=new RegExp(`^firestore_clients_${i}_([^_]*)$`),this.dr=new RegExp(`^firestore_mutations_${i}_(\\d+)(?:_(.*))?$`),this._r=new RegExp(`^firestore_targets_${i}_(\\d+)$`),this.wr=`firestore_online_state_${this.persistenceKey}`,this.mr=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.ir)}static C(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.vi();for(const n of e)if(n!==this.sr){const e=this.getItem(Xc(this.persistenceKey,n));var t;!e||(t=nh.Zi(n,e))&&(this.ur=this.ur.insert(t.clientId,t))}this.gr();const n=this.storage.getItem(this.wr);if(n){const e=this.yr(n);e&&this.pr(e)}for(const e of this.cr)this.rr(e);this.cr=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.hr,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Ir(this.ur)}isActiveQueryTarget(n){let r=!1;return this.ur.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Tr(e,"pending")}updateMutationState(e,t,n){this.Tr(e,t,n),this.Er(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Zc(this.persistenceKey,e)))||(n=th.Zi(e,n))&&(t=n.state)),this.Ar.er(e),this.gr(),t}removeLocalQueryTarget(e){this.Ar.nr(e),this.gr()}isLocalQueryTarget(e){return this.Ar.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Zc(this.persistenceKey,e))}updateQueryState(e,t,n){this.Rr(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Er(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.br(e)}notifyBundleLoaded(e){this.Pr(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ir),this.removeItem(this.ar),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return yr("SharedClientState","READ",e,t),t}setItem(e,t){yr("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){yr("SharedClientState","REMOVE",e),this.storage.removeItem(e)}rr(e){const s=e;s.storageArea===this.storage&&(yr("SharedClientState","EVENT",s.key,s.newValue),s.key!==this.ar?this.Hs.enqueueRetryable(async()=>{if(this.started){if(null!==s.key)if(this.lr.test(s.key)){if(null==s.newValue){var e=this.vr(s.key);return this.Vr(e,null)}e=this.Sr(s.key,s.newValue);if(e)return this.Vr(e.clientId,e)}else if(this.dr.test(s.key)){if(null!==s.newValue){var t=this.Dr(s.key,s.newValue);if(t)return this.Cr(t)}}else if(this._r.test(s.key)){if(null!==s.newValue){t=this.Nr(s.key,s.newValue);if(t)return this.kr(t)}}else if(s.key===this.wr){if(null!==s.newValue){var n=this.yr(s.newValue);if(n)return this.pr(n)}}else if(s.key===this.hr){n=function(e){let t=ms.at;if(null!=e)try{var n=JSON.parse(e);Er("number"==typeof n),t=n}catch(e){vr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(s.newValue);n!==ms.at&&this.sequenceNumberHandler(n)}else if(s.key===this.mr){const r=this.Or(s.newValue);await Promise.all(r.map(e=>this.syncEngine.Mr(e)))}}else this.cr.push(s)}):vr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Ar(){return this.ur.get(this.sr)}gr(){this.setItem(this.ar,this.Ar.tr())}Tr(e,t,n){const r=new eh(this.currentUser,e,t,n),s=Jc(this.persistenceKey,this.currentUser,e);this.setItem(s,r.tr())}Er(e){var t=Jc(this.persistenceKey,this.currentUser,e);this.removeItem(t)}br(e){var t={clientId:this.sr,onlineState:e};this.storage.setItem(this.wr,JSON.stringify(t))}Rr(e,t,n){const r=Zc(this.persistenceKey,e),s=new th(e,t,n);this.setItem(r,s.tr())}Pr(e){var t=JSON.stringify(Array.from(e));this.setItem(this.mr,t)}vr(e){var t=this.lr.exec(e);return t?t[1]:null}Sr(e,t){var n=this.vr(e);return nh.Zi(n,t)}Dr(e,t){var n=this.dr.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return eh.Zi(new fr(n),r,t)}Nr(e,t){var n=this._r.exec(e),n=Number(n[1]);return th.Zi(n,t)}yr(e){return rh.Zi(e)}Or(e){return JSON.parse(e)}async Cr(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Fr(e.batchId,e.state,e.error);yr("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}kr(e){return this.syncEngine.$r(e.targetId,e.state,e.error)}Vr(e,t){const n=t?this.ur.insert(e,t):this.ur.remove(e),r=this.Ir(this.ur),s=this.Ir(n),i=[],a=[];return s.forEach(e=>{r.has(e)||i.push(e)}),r.forEach(e=>{s.has(e)||a.push(e)}),this.syncEngine.Br(i,a).then(()=>{this.ur=n})}pr(e){this.ur.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Ir(e){let n=Va;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class ah{constructor(){this.Lr=new sh,this.qr={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Lr.er(e),this.qr[e]||"not-current"}updateQueryState(e,t,n){this.qr[e]=t}removeLocalQueryTarget(e){this.Lr.nr(e)}isLocalQueryTarget(e){return this.Lr.activeTargetIds.has(e)}clearQueryState(e){delete this.qr[e]}getAllActiveQueryTargets(){return this.Lr.activeTargetIds}isActiveQueryTarget(e){return this.Lr.activeTargetIds.has(e)}start(){return this.Lr=new sh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class oh{Ur(e){}shutdown(){}}class uh{constructor(){this.Kr=()=>this.Gr(),this.Qr=()=>this.jr(),this.Wr=[],this.zr()}Ur(e){this.Wr.push(e)}shutdown(){window.removeEventListener("online",this.Kr),window.removeEventListener("offline",this.Qr)}zr(){window.addEventListener("online",this.Kr),window.addEventListener("offline",this.Qr)}Gr(){yr("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Wr)e(0)}jr(){yr("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Wr)e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const ch={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class hh{constructor(e){this.Hr=e.Hr,this.Jr=e.Jr}Yr(e){this.Xr=e}Zr(e){this.eo=e}onMessage(e){this.no=e}close(){this.Jr()}send(e){this.Hr(e)}so(){this.Xr()}io(e){this.eo(e)}ro(e){this.no(e)}}class lh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.oo=t+"://"+e.host,this.uo="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}get co(){return!1}ao(t,e,n,r,s){const i=this.ho(t,e);yr("RestConnection","Sending: ",i,n);var a={};return this.lo(a,r,s),this.fo(t,i,a,n).then(e=>(yr("RestConnection","Received: ",e),e),e=>{throw wr("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e})}_o(e,t,n,r,s,i){return this.ao(e,t,n,r,s)}lo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+gr,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}ho(e,t){var n=ch[e];return`${this.oo}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}fo(o,t,n,r){return new Promise((s,i)=>{const a=new lr;a.setWithCredentials(!0),a.listenOnce(ir.COMPLETE,()=>{try{switch(a.getLastErrorCode()){case sr.NO_ERROR:var e=a.getResponseJson();yr("Connection","XHR received:",JSON.stringify(e)),s(e);break;case sr.TIMEOUT:yr("Connection",'RPC "'+o+'" timed out'),i(new _r(Tr.DEADLINE_EXCEEDED,"Request time out"));break;case sr.HTTP_ERROR:var t=a.getStatus();if(yr("Connection",'RPC "'+o+'" failed with status:',t,"response text:",a.getResponseText()),0<t){let e=a.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const o=(r=n.status.toLowerCase().replace(/_/g,"-"),0<=Object.values(Tr).indexOf(r)?r:Tr.UNKNOWN);i(new _r(o,n.message))}else i(new _r(Tr.UNKNOWN,"Server responded with status "+a.getStatus()))}else i(new _r(Tr.UNAVAILABLE,"Connection failed."));break;default:br()}}finally{yr("Connection",'RPC "'+o+'" completed.')}var r});var e=JSON.stringify(r);a.send(t,"POST",e,n,15)})}wo(e,t,n){const r=[this.oo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=new Xn,i=rr(),a={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(a.xmlHttpFactory=new cr({})),this.lo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;var o=r.join("");yr("Connection","Creating WebChannel: "+o,a);const u=s.createWebChannel(o,a);let c=!1,h=!1;const l=new hh({Hr:e=>{h?yr("Connection","Not sending because WebChannel is closed:",e):(c||(yr("Connection","Opening WebChannel transport."),u.open(),c=!0),yr("Connection","WebChannel sending:",e),u.send(e))},Jr:()=>u.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(u,hr.EventType.OPEN,()=>{h||yr("Connection","WebChannel transport opened.")}),d(u,hr.EventType.CLOSE,()=>{h||(h=!0,yr("Connection","WebChannel transport closed"),l.io())}),d(u,hr.EventType.ERROR,e=>{h||(h=!0,wr("Connection","WebChannel transport errored:",e),l.io(new _r(Tr.UNAVAILABLE,"The operation could not be completed")))}),d(u,hr.EventType.MESSAGE,n=>{if(!h){var e=n.data[0];Er(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){yr("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=nr[e];if(void 0!==t)return Da(t)}(n),t=r.message;void 0===e&&(e=Tr.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),h=!0,l.io(new _r(e,t)),u.close()}else yr("Connection","WebChannel received:",e),l.ro(e)}}),d(i,ar.STAT_EVENT,e=>{e.stat===or?yr("Connection","Detected buffering proxy"):e.stat===ur&&yr("Connection","Detected no buffering proxy")}),setTimeout(()=>{l.so()},0),l}}function dh(){return"undefined"!=typeof window?window:null}function fh(){return"undefined"!=typeof document?document:null}function gh(e){return new Ya(e,!0)}class mh{constructor(e,t,n=1e3,r=1.5,s=6e4){this.Hs=e,this.timerId=t,this.mo=n,this.yo=r,this.po=s,this.Io=0,this.To=null,this.Eo=Date.now(),this.reset()}reset(){this.Io=0}Ao(){this.Io=this.po}Ro(e){this.cancel();var t=Math.floor(this.Io+this.bo()),n=Math.max(0,Date.now()-this.Eo),r=Math.max(0,t-n);0<r&&yr("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Io} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.To=this.Hs.enqueueAfterDelay(this.timerId,r,()=>(this.Eo=Date.now(),e())),this.Io*=this.yo,this.Io<this.mo&&(this.Io=this.mo),this.Io>this.po&&(this.Io=this.po)}Po(){null!==this.To&&(this.To.skipDelay(),this.To=null)}cancel(){null!==this.To&&(this.To.cancel(),this.To=null)}bo(){return(Math.random()-.5)*this.Io}}class ph{constructor(e,t,n,r,s,i,a,o){this.Hs=e,this.vo=n,this.Vo=r,this.connection=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.So=0,this.Do=null,this.Co=null,this.stream=null,this.xo=new mh(e,t)}No(){return 1===this.state||5===this.state||this.ko()}ko(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Oo()}async stop(){this.No()&&await this.close(0)}Mo(){this.state=0,this.xo.reset()}Fo(){this.ko()&&null===this.Do&&(this.Do=this.Hs.enqueueAfterDelay(this.vo,6e4,()=>this.$o()))}Bo(e){this.Lo(),this.stream.send(e)}async $o(){if(this.ko())return this.close(0)}Lo(){this.Do&&(this.Do.cancel(),this.Do=null)}qo(){this.Co&&(this.Co.cancel(),this.Co=null)}async close(e,t){this.Lo(),this.qo(),this.xo.cancel(),this.So++,4!==e?this.xo.reset():t&&t.code===Tr.RESOURCE_EXHAUSTED?(vr(t.toString()),vr("Using maximum backoff delay to prevent overloading the backend."),this.xo.Ao()):t&&t.code===Tr.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Uo(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Zr(t)}Uo(){}auth(){this.state=1;const e=this.Ko(this.So),n=this.So;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.So===n&&this.Go(e,t)},t=>{e(()=>{var e=new _r(Tr.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Qo(e)})})}Go(e,t){const n=this.Ko(this.So);this.stream=this.jo(e,t),this.stream.Yr(()=>{n(()=>(this.state=2,this.Co=this.Hs.enqueueAfterDelay(this.Vo,1e4,()=>(this.ko()&&(this.state=3),Promise.resolve())),this.listener.Yr()))}),this.stream.Zr(e=>{n(()=>this.Qo(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Oo(){this.state=5,this.xo.Ro(async()=>{this.state=0,this.start()})}Qo(e){return yr("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Ko(t){return e=>{this.Hs.enqueueAndForget(()=>this.So===t?e():(yr("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class yh extends ph{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.yt=s}jo(e,t){return this.connection.wo("Listen",e,t)}onMessage(e){this.xo.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:br(),s=t.targetChange.targetIds||[],i=(f=t.targetChange.resumeToken,e.wt?(Er(void 0===f||"string"==typeof f),_s.fromBase64String(f||"")):(Er(void 0===f||f instanceof Uint8Array),_s.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?Tr.UNKNOWN:Da(f.code),new _r(o,f.message||""));n=new Ga(r,s,i,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var i=ro(e,u.document.name),o=Za(u.document.updateTime),c=u.document.createTime?Za(u.document.createTime):qr.min(),h=new Ti({mapValue:{fields:u.document.fields}}),c=_i.newFoundDocument(i,o,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new Ba(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=ro(e,h.document),c=h.readTime?Za(h.readTime):qr.min(),c=_i.newNoDocument(u,c),h=h.removedTargetIds||[];n=new Ba([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=ro(e,l.document),l=l.removedTargetIds||[];n=new Ba([],l,d,null)}else{if(!("filter"in t))return br();{t.filter;const e=t.filter;e.targetId;l=e.count||0,d=new Sa(l),l=e.targetId;n=new Ua(l,d)}}var o,f;return n}(this.yt,e),n=function(e){if(!("targetChange"in e))return qr.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?Za(t.readTime):qr.min()}(e);return this.listener.Wo(t,n)}zo(e){const t={};t.database=ao(this.yt),t.addTarget=function(e,t){let n;var r=t.target;return n=Ci(r)?{documents:fo(e,r)}:{query:go(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=Ja(e,t.resumeToken):0<t.snapshotVersion.compareTo(qr.min())&&(n.readTime=Xa(e,t.snapshotVersion.toTimestamp())),n}(this.yt,e);var n,r,r=(this.yt,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return br()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.Bo(t)}Ho(e){const t={};t.database=ao(this.yt),t.removeTarget=e,this.Bo(t)}}class vh extends ph{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.yt=s,this.Jo=!1}get Yo(){return this.Jo}start(){this.Jo=!1,this.lastStreamToken=void 0,super.start()}Uo(){this.Jo&&this.Xo([])}jo(e,t){return this.connection.wo("Write",e,t)}onMessage(e){if(Er(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Jo){this.xo.reset();var t=(r=e.writeResults,s=e.commitTime,r&&0<r.length?(Er(void 0!==s),r.map(e=>function(e,t){let n=e.updateTime?Za(e.updateTime):Za(t);return n.isEqual(qr.min())&&(n=Za(t)),new ha(n,e.transformResults||[])}(e,s))):[]),n=Za(e.commitTime);return this.listener.Zo(n,t)}var r,s;return Er(!e.writeResults||0===e.writeResults.length),this.Jo=!0,this.listener.tu()}eu(){const e={};e.database=ao(this.yt),this.Bo(e)}Xo(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>ho(this.yt,e))};this.Bo(t)}}class wh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.yt=r,this.nu=!1}su(){if(this.nu)throw new _r(Tr.FAILED_PRECONDITION,"The client has already been terminated.")}ao(n,r,s){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.ao(n,r,s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Tr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new _r(Tr.UNKNOWN,e.toString())})}_o(n,r,s,i){return this.su(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection._o(n,r,s,e,t,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Tr.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new _r(Tr.UNKNOWN,e.toString())})}terminate(){this.nu=!0}}class Ih{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.iu=0,this.ru=null,this.ou=!0}uu(){0===this.iu&&(this.cu("Unknown"),this.ru=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.ru=null,this.au("Backend didn't respond within 10 seconds."),this.cu("Offline"),Promise.resolve())))}hu(e){"Online"===this.state?this.cu("Unknown"):(this.iu++,1<=this.iu&&(this.lu(),this.au(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.cu("Offline")))}set(e){this.lu(),this.iu=0,"Online"===e&&(this.ou=!1),this.cu(e)}cu(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}au(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.ou?(vr(t),this.ou=!1):yr("OnlineStateTracker",t)}lu(){null!==this.ru&&(this.ru.cancel(),this.ru=null)}}class bh{constructor(e,t,n,r,s){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.fu=[],this.du=new Map,this._u=new Set,this.wu=[],this.mu=s,this.mu.Ur(e=>{n.enqueueAndForget(async()=>{Nh(this)&&(yr("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t._u.add(4),await Th(t),t.gu.set("Unknown"),t._u.delete(4),await Eh(t)}(this))})}),this.gu=new Ih(n,r)}}async function Eh(e){if(Nh(e))for(const t of e.wu)await t(!0)}async function Th(e){for(const t of e.wu)await t(!1)}function _h(e,t){const n=e;n.du.has(t.targetId)||(n.du.set(t.targetId,t),Ch(n)?Ah(n):qh(n).ko()&&xh(n,t))}function Sh(e,t){const n=e,r=qh(n);n.du.delete(t),r.ko()&&Dh(n,t),0===n.du.size&&(r.ko()?r.Fo():Nh(n)&&n.gu.set("Unknown"))}function xh(e,t){e.yu.Ot(t.targetId),qh(e).zo(t)}function Dh(e,t){e.yu.Ot(t),qh(e).Ho(t)}function Ah(t){t.yu=new ja({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),ne:e=>t.du.get(e)||null}),qh(t).start(),t.gu.uu()}function Ch(e){return Nh(e)&&!qh(e).No()&&0<e.du.size}function Nh(e){return 0===e._u.size}function kh(e){e.yu=void 0}async function Rh(e,t,n){if(!us(t))throw t;e._u.add(1),await Th(e),e.gu.set("Offline"),n=n||(()=>Gc(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{yr("RemoteStore","Retrying IndexedDB access"),await n(),e._u.delete(1),await Eh(e)})}function Lh(t,n){return n().catch(e=>Rh(t,e,n))}async function Mh(e){const t=e,n=Bh(t);let r=0<t.fu.length?t.fu[t.fu.length-1].batchId:-1;for(;Nh(s=t)&&s.fu.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.fu.length&&n.Fo();break}r=e.batchId,function(e,t){e.fu.push(t);const n=Bh(e);n.ko()&&n.Yo&&n.Xo(t.mutations)}(t,e)}catch(e){await Rh(t,e)}var s;Fh(t)&&Oh(t)}function Fh(e){return Nh(e)&&!Bh(e).No()&&0<e.fu.length}function Oh(e){Bh(e).start()}async function Vh(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),yr("RemoteStore","RemoteStore received new credentials");var r=Nh(n);n._u.add(3),await Th(n),r&&n.gu.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n._u.delete(3),await Eh(n)}async function Ph(e,t){const n=e;t?(n._u.delete(2),await Eh(n)):(n._u.add(2),await Th(n),n.gu.set("Unknown"))}function qh(t){return t.pu||(t.pu=function(e,t,n){const r=e;return r.su(),new yh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.yt,n)}(t.datastore,t.asyncQueue,{Yr:(async function(n){n.du.forEach((e,t)=>{xh(n,e)})}).bind(null,t),Zr:(async function(e,t){kh(e),Ch(e)?(e.gu.hu(t),Ah(e)):e.gu.set("Unknown")}).bind(null,t),Wo:(async function(e,r,t){if(e.gu.set("Online"),r instanceof Ga&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.du.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.du.delete(n),e.yu.removeTarget(n))}(e)}catch(t){yr("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await Rh(e,t)}else if(r instanceof Ba?e.yu.Kt(r):r instanceof Ua?e.yu.Jt(r):e.yu.jt(r),!t.isEqual(qr.min()))try{const r=await Gc(e.localStore);0<=t.compareTo(r)&&await function(r,s){const e=r.yu.Zt(s);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.du.get(t);n&&r.du.set(t,n.withResumeToken(e.resumeToken,s))}}),e.targetMismatches.forEach(e=>{const t=r.du.get(e);var n;t&&(r.du.set(e,t.withResumeToken(_s.EMPTY_BYTE_STRING,t.snapshotVersion)),Dh(r,e),n=new Jo(t.target,e,1,t.sequenceNumber),xh(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){yr("RemoteStore","Failed to raise snapshot:",r),await Rh(e,r)}}).bind(null,t)}),t.wu.push(async e=>{e?(t.pu.Mo(),Ch(t)?Ah(t):t.gu.set("Unknown")):(await t.pu.stop(),kh(t))})),t.pu}function Bh(t){return t.Iu||(t.Iu=function(e,t,n){const r=e;return r.su(),new vh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.yt,n)}(t.datastore,t.asyncQueue,{Yr:(async function(e){Bh(e).eu()}).bind(null,t),Zr:(async function(e,t){t&&Bh(e).Yo&&await async function(e,t){if(xa(n=t.code)&&n!==Tr.ABORTED){const n=e.fu.shift();Bh(e).Mo(),await Lh(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await Mh(e)}var n}(e,t),Fh(e)&&Oh(e)}).bind(null,t),tu:(async function(e){const t=Bh(e);for(const n of e.fu)t.Xo(n.mutations)}).bind(null,t),Zo:(async function(e,t,n){const r=e.fu.shift(),s=Yo.from(r,t,n);await Lh(e,()=>e.remoteSyncer.applySuccessfulWrite(s)),await Mh(e)}).bind(null,t)}),t.wu.push(async e=>{e?(t.Iu.Mo(),await Mh(t)):(await t.Iu.stop(),0<t.fu.length&&(yr("RemoteStore",`Stopping write stream with ${t.fu.length} pending writes`),t.fu=[]))})),t.Iu}class Uh{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,this.deferred=new Sr,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,s){const i=Date.now()+n,a=new Uh(e,t,i,r,s);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new _r(Tr.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function Gh(e,t){if(vr("AsyncQueue",`${t}: ${e}`),us(e))return new _r(Tr.UNAVAILABLE,`${t}: ${e}`);throw e}class Kh{constructor(n){this.comparator=n?(e,t)=>n(e,t)||jr.comparator(e.key,t.key):(e,t)=>jr.comparator(e.key,t.key),this.keyedMap=ka(),this.sortedSet=new pi(this.comparator)}static emptySet(e){return new Kh(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof Kh))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new Kh;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class jh{constructor(){this.Tu=new pi(jr.comparator)}track(e){var t=e.doc.key,n=this.Tu.get(t);!n||0!==e.type&&3===n.type?this.Tu=this.Tu.insert(t,e):3===e.type&&1!==n.type?this.Tu=this.Tu.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Tu=this.Tu.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Tu=this.Tu.remove(t):1===e.type&&2===n.type?this.Tu=this.Tu.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Tu=this.Tu.insert(t,{type:2,doc:e.doc}):br()}Eu(){const n=[];return this.Tu.inorderTraversal((e,t)=>{n.push(t)}),n}}class $h{constructor(e,t,n,r,s,i,a,o,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,s){const i=[];return t.forEach(e=>{i.push({type:0,doc:e})}),new $h(e,t,Kh.emptySet(t),i,n,r,!0,!1,s)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&ji(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class Qh{constructor(){this.Au=void 0,this.listeners=[]}}class zh{constructor(){this.queries=new Aa(e=>$i(e),ji),this.onlineState="Unknown",this.Ru=new Set}}async function Wh(e,t){const n=e,r=t.query;let s=!1,i=n.queries.get(r);if(i||(s=!0,i=new Qh),s)try{i.Au=await n.onListen(r)}catch(e){const n=Gh(e,`Initialization of query '${Qi(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,i),i.listeners.push(t),t.bu(n.onlineState),!i.Au||t.Pu(i.Au)&&Yh(n)}async function Hh(e,t){const n=e,r=t.query;let s=!1;const i=n.queries.get(r);if(i){const e=i.listeners.indexOf(t);0<=e&&(i.listeners.splice(e,1),s=0===i.listeners.length)}if(s)return n.queries.delete(r),n.onUnlisten(r)}function Yh(e){e.Ru.forEach(e=>{e.next()})}class Xh{constructor(e,t,n){this.query=e,this.vu=t,this.Vu=!1,this.Su=null,this.onlineState="Unknown",this.options=n||{}}Pu(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new $h(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Vu?this.Du(e)&&(this.vu.next(e),t=!0):this.Cu(e,this.onlineState)&&(this.xu(e),t=!0),this.Su=e,t}onError(e){this.vu.error(e)}bu(e){this.onlineState=e;let t=!1;return this.Su&&!this.Vu&&this.Cu(this.Su,e)&&(this.xu(this.Su),t=!0),t}Cu(e,t){return!e.fromCache||(!this.options.Nu||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Du(e){if(0<e.docChanges.length)return!0;var t=this.Su&&this.Su.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}xu(e){e=$h.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Vu=!0,this.vu.next(e)}}class Jh{constructor(e,t){this.ku=e,this.byteLength=t}Ou(){return"metadata"in this.ku}}class Zh{constructor(e){this.yt=e}Ji(e){return ro(this.yt,e)}Yi(e){return e.metadata.exists?co(this.yt,e.document,!1):_i.newNoDocument(this.Ji(e.metadata.name),this.Xi(e.metadata.readTime))}Xi(e){return Za(e)}}class el{constructor(e,t,n){this.Mu=e,this.localStore=t,this.yt=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=tl(e)}Fu(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.ku.namedQuery)this.queries.push(e.ku.namedQuery);else if(e.ku.documentMetadata){this.documents.push({metadata:e.ku.documentMetadata}),e.ku.documentMetadata.exists||++t;const n=Ur.fromString(e.ku.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ku.document&&(this.documents[this.documents.length-1].document=e.ku.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}$u(e){const t=new Map,n=new Zh(this.yt);for(const s of e)if(s.metadata.queries){const e=n.Ji(s.metadata.name);for(const n of s.metadata.queries){var r=(t.get(n)||Oa()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const s=e;let i=Oa(),a=Ca;for(const e of n){const n=t.Ji(e.metadata.name);e.document&&(i=i.add(n));const c=t.Yi(e);c.setReadTime(t.Xi(e.metadata.readTime)),a=a.insert(n,c)}const o=s.Gi.newChangeBuffer({trackRemovals:!0}),u=await $c(s,(r=r,Ui(Fi(Ur.fromString(`__bundle__/docs/${r}`)))));return s.persistence.runTransaction("Apply bundle documents","readwrite",t=>jc(t,o,a).next(e=>(o.apply(t),e)).next(e=>s.Cs.removeMatchingKeysForTargetId(t,u.targetId).next(()=>s.Cs.addMatchingKeys(t,i,u.targetId)).next(()=>s.localDocuments.getLocalViewOfDocuments(t,e.Wi,e.zi)).next(()=>e.Wi)))}(this.localStore,new Zh(this.yt),this.documents,this.Mu.id),t=this.$u(this.documents);for(const e of this.queries)await async function(e,n,r=Oa()){const s=await $c(e,Ui(ou(n.bundledQuery))),i=e;return i.persistence.runTransaction("Save named query","readwrite",e=>{var t=Za(n.readTime);if(0<=s.snapshotVersion.compareTo(t))return i.Ns.saveNamedQuery(e,n);t=s.withResumeToken(_s.EMPTY_BYTE_STRING,t);return i.qi=i.qi.insert(t.targetId,t),i.Cs.updateTargetData(e,t).next(()=>i.Cs.removeMatchingKeysForTargetId(e,s.targetId)).next(()=>i.Cs.addMatchingKeys(e,r,s.targetId)).next(()=>i.Ns.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Bu:this.collectionGroups,Lu:e}}}function tl(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class nl{constructor(e){this.key=e}}class rl{constructor(e){this.key=e}}class sl{constructor(e,t){this.query=e,this.qu=t,this.Uu=null,this.hasCachedResults=!1,this.current=!1,this.Ku=Oa(),this.mutatedKeys=Oa(),this.Gu=Hi(e),this.Qu=new Kh(this.Gu)}get ju(){return this.qu}Wu(e,t){const o=t?t.zu:new jh,u=(t||this).Qu;let c=(t||this).mutatedKeys,h=u,l=!1;const d="F"===this.query.limitType&&u.size===this.query.limit?u.last():null,f="L"===this.query.limitType&&u.size===this.query.limit?u.first():null;if(e.inorderTraversal((e,t)=>{const n=u.get(e),r=zi(this.query,t)?t:null,s=!!n&&this.mutatedKeys.has(n.key),i=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?s!==i&&(o.track({type:3,doc:r}),a=!0):this.Hu(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Gu(r,d)||f&&this.Gu(r,f)<0)&&(l=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||f)&&(l=!0)),a&&(c=r?(h=h.add(r),i?c.add(e):c.delete(e)):(h=h.delete(e),c.delete(e)))}),null!==this.query.limit)for(;h.size>this.query.limit;){const e="F"===this.query.limitType?h.last():h.first();h=h.delete(e.key),c=c.delete(e.key),o.track({type:1,doc:e})}return{Qu:h,zu:o,$i:l,mutatedKeys:c}}Hu(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Qu;this.Qu=e.Qu,this.mutatedKeys=e.mutatedKeys;const s=e.zu.Eu();s.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return br()}};return n(e)-n(t)}(e.type,t.type)||this.Gu(e.doc,t.doc)),this.Ju(n);var i=t?this.Yu():[],a=0===this.Ku.size&&this.current?1:0,o=a!==this.Uu;return this.Uu=a,0!==s.length||o?{snapshot:new $h(this.query,e.Qu,r,s,e.mutatedKeys,0==a,o,!1,!!n&&0<n.resumeToken.approximateByteSize()),Xu:i}:{Xu:i}}bu(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Qu:this.Qu,zu:new jh,mutatedKeys:this.mutatedKeys,$i:!1},!1)):{Xu:[]}}Zu(e){return!this.qu.has(e)&&!!this.Qu.has(e)&&!this.Qu.get(e).hasLocalMutations}Ju(e){e&&(e.addedDocuments.forEach(e=>this.qu=this.qu.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.qu=this.qu.delete(e)),this.current=e.current)}Yu(){if(!this.current)return[];const t=this.Ku;this.Ku=Oa(),this.Qu.forEach(e=>{this.Zu(e.key)&&(this.Ku=this.Ku.add(e.key))});const n=[];return t.forEach(e=>{this.Ku.has(e)||n.push(new rl(e))}),this.Ku.forEach(e=>{t.has(e)||n.push(new nl(e))}),n}tc(e){this.qu=e.Hi,this.Ku=Oa();var t=this.Wu(e.documents);return this.applyChanges(t,!0)}ec(){return $h.fromInitialDocuments(this.query,this.Qu,this.mutatedKeys,0===this.Uu,this.hasCachedResults)}}class il{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class al{constructor(e){this.key=e,this.nc=!1}}class ol{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.sc={},this.ic=new Aa(e=>$i(e),ji),this.rc=new Map,this.oc=new Set,this.uc=new pi(jr.comparator),this.cc=new Map,this.ac=new bc,this.hc={},this.lc=new Map,this.fc=Xu.vn(),this.onlineState="Unknown",this.dc=void 0}get isPrimaryClient(){return!0===this.dc}}async function ul(n,e,t,r,s){n._c=(e,i,t)=>async function(e,t,n){let r=t.view.Wu(i);r.$i&&(r=await zc(e.localStore,t.query,!1).then(({documents:e})=>t.view.Wu(e,r)));var s=n&&n.targetChanges.get(t.targetId),s=t.view.applyChanges(r,e.isPrimaryClient,s);return yl(e,t.targetId,s.Xu),s.snapshot}(n,e,t);const i=await zc(n.localStore,e,!0),a=new sl(e,i.Hi),o=a.Wu(i.documents),u=qa.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState,s),c=a.applyChanges(o,n.isPrimaryClient,u);yl(n,t,c.Xu);var h=new il(e,t,a);return n.ic.set(e,h),n.rc.has(t)?n.rc.get(t).push(e):n.rc.set(t,[e]),c.snapshot}async function cl(e,t,n){const r=_l(e);try{const e=await function(e,s){const i=e,a=Pr.now(),o=s.reduce((e,t)=>e.add(t.key),Oa());let u,c;return i.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=Ca,r=Oa();return i.Gi.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>i.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of s){const s=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),s=ea(r.transform,e||null);null!=s&&(null===n&&(n=Ti.empty()),n.set(r.field,s))}return n||null}(n,u.get(n.key).overlayedDocument);null!=s&&t.push(new wa(n.key,s,function r(e){const s=[];return ws(e.fields,(e,t)=>{const n=new Kr([e]);if(js(t)){const e=r(t.mapValue).fields;if(0===e.length)s.push(n);else for(const t of e)s.push(n.child(t))}else s.push(n)}),new Ei(s)}(s.value.mapValue),la.exists(!0)))}return i.mutationQueue.addMutationBatch(n,a,t,s)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return i.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:Ra(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.hc[e.currentUser.toKey()];r=r||new pi(Fr),r=r.insert(t,n),e.hc[e.currentUser.toKey()]=r}(r,e.batchId,n),await wl(r,e.changes),await Mh(r.remoteStore)}catch(e){const t=Gh(e,"Failed to persist write");n.reject(t)}}async function hl(e,t){const r=e;try{const e=await Kc(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.cc.get(t);n&&(Er(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.nc=!0:0<e.modifiedDocuments.size?Er(n.nc):0<e.removedDocuments.size&&(Er(n.nc),n.nc=!1))}),await wl(r,e,t)}catch(e){await ns(e)}}function ll(r,s,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ic.forEach((e,t)=>{var n=t.view.bu(s);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.bu(n)&&(r=!0)}),r&&Yh(t)}(t.eventManager,s),r.length&&t.sc.Wo(r),t.onlineState=s,t.isPrimaryClient&&t.sharedClientState.setOnlineState(s)}}async function dl(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=s.Gi.newChangeBuffer({trackRemovals:!0});return function(e,t,r,s){const i=r.batch,n=i.keys();let a=rs.resolve();return n.forEach(n=>{a=a.next(()=>s.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Er(null!==t),e.version.compareTo(t)<0&&(i.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),s.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))}(s,e,r,n).next(()=>n.apply(e)).next(()=>s.mutationQueue.performConsistencyCheck(e)).next(()=>s.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Oa();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>s.localDocuments.getDocuments(e,t))})}(n.localStore,t);gl(n,r,null),fl(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await wl(n,e)}catch(e){await ns(e)}}function fl(e,t){(e.lc.get(t)||[]).forEach(e=>{e.resolve()}),e.lc.delete(t)}function gl(e,t,n){const r=e;let s=r.hc[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.hc[r.currentUser.toKey()]=s}}function ml(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.rc.get(e))t.ic.delete(r),n&&t.sc.wc(r,n);t.rc.delete(e),t.isPrimaryClient&&t.ac.ls(e).forEach(e=>{t.ac.containsKey(e)||pl(t,e)})}function pl(e,t){e.oc.delete(t.path.canonicalString());var n=e.uc.get(t);null!==n&&(Sh(e.remoteStore,n),e.uc=e.uc.remove(t),e.cc.delete(n),vl(e))}function yl(e,t,n){for(const r of n)r instanceof nl?(e.ac.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.uc.get(n)||e.oc.has(r)||(yr("SyncEngine","New document in limbo: "+n),e.oc.add(r),vl(e))}(e,r)):r instanceof rl?(yr("SyncEngine","Document no longer in limbo: "+r.key),e.ac.removeReference(r.key,t),e.ac.containsKey(r.key)||pl(e,r.key)):br()}function vl(e){for(;0<e.oc.size&&e.uc.size<e.maxConcurrentLimboResolutions;){var t=e.oc.values().next().value;e.oc.delete(t);var n=new jr(Ur.fromString(t)),t=e.fc.next();e.cc.set(t,new al(n)),e.uc=e.uc.insert(n,t),_h(e.remoteStore,new Jo(Ui(Fi(n.path)),t,2,ms.at))}}async function wl(e,t,r){const s=e,i=[],a=[],o=[];s.ic.isEmpty()||(s.ic.forEach((e,n)=>{o.push(s._c(n,t,r).then(e=>{var t;(e||r)&&s.isPrimaryClient&&s.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(i.push(e),t=Vc.Ci(n.targetId,e),a.push(t))}))}),await Promise.all(o),s.sc.Wo(i),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>rs.forEach(t,t=>rs.forEach(t.Si,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>rs.forEach(t.Di,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!us(e))throw e;yr("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.qi.get(t),n=e.snapshotVersion,s=e.withLastLimboFreeSnapshotVersion(n);r.qi=r.qi.insert(t,s)}}}(s.localStore,a))}async function Il(r,e){const s=r;if(Tl(s),_l(s),!0===e&&!0!==s.dc){const r=s.sharedClientState.getAllActiveQueryTargets(),e=await bl(s,r.toArray());s.dc=!0,await Ph(s.remoteStore,!0);for(const r of e)_h(s.remoteStore,r)}else if(!1===e&&!1!==s.dc){const r=[];let n=Promise.resolve();s.rc.forEach((e,t)=>{s.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(ml(s,t),Qc(s.localStore,t,!0))),Sh(s.remoteStore,t)}),await n,await bl(s,r),function(){const n=s;n.cc.forEach((e,t)=>{Sh(n.remoteStore,t)}),n.ac.fs(),n.cc=new Map,n.uc=new pi(jr.comparator)}(),s.dc=!1,await Ph(s.remoteStore,!1)}}async function bl(t,n){const r=t,s=[],i=[];for(const t of n){let e;const h=r.rc.get(t);if(h&&0!==h.length){e=await $c(r.localStore,Ui(h[0]));for(const t of h){const n=r.ic.get(t),h=(a=r,o=n,c=u=void 0,c=await zc((u=a).localStore,o.query,!0),c=o.view.tc(c),u.isPrimaryClient&&yl(u,o.targetId,c.Xu),await c);h.snapshot&&i.push(h.snapshot)}}else{const h=await Wc(r.localStore,t);e=await $c(r.localStore,h),await ul(r,El(h),t,!1,e.resumeToken)}s.push(e)}var a,o,u,c;return r.sc.Wo(i),s}function El(e){return Mi(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Tl(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=hl.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.cc.get(t);if(r&&r.nc)return Oa().add(r.key);{let e=Oa();const r=n.rc.get(t);if(!r)return e;for(const t of r){const r=n.ic.get(t);e=e.unionWith(r.view.ju)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const s=r.cc.get(t),i=s&&s.key;if(i){let e=new pi(jr.comparator);e=e.insert(i,_i.newNoDocument(i,qr.min()));const n=Oa().add(i),s=new Pa(qr.min(),new Map,new wi(Fr),e,n);await hl(r,s),r.uc=r.uc.remove(i),r.cc.delete(t),vl(r)}else await Qc(r.localStore,t,!1).then(()=>ml(r,t,n)).catch(ns)}).bind(null,t),t.sc.Wo=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,s=n.queries.get(t);if(s){for(const t of s.listeners)t.Pu(e)&&(r=!0);s.Au=e}}r&&Yh(n)}).bind(null,t.eventManager),t.sc.wc=(function(e,t,n){const r=e,s=r.queries.get(t);if(s)for(const e of s.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function _l(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=dl.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const s=e;return s.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return s.mutationQueue.lookupMutationBatch(t,r).next(e=>(Er(null!==e),n=e.keys(),s.mutationQueue.removeMutationBatch(t,e))).next(()=>s.mutationQueue.performConsistencyCheck(t)).next(()=>s.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>s.localDocuments.getDocuments(t,n))})}(r.localStore,t);gl(r,t,n),fl(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await wl(r,e)}catch(n){await ns(n)}}).bind(null,t),t}class Sl{constructor(){this.synchronizeTabs=!1}async initialize(e){this.yt=gh(e.databaseInfo.databaseId),this.sharedClientState=this.gc(e),this.persistence=this.yc(e),await this.persistence.start(),this.localStore=this.Ic(e),this.gcScheduler=this.Tc(e,this.localStore),this.indexBackfillerScheduler=this.Ec(e,this.localStore)}Tc(e,t){return null}Ec(e,t){return null}Ic(e){return Bc(this.persistence,new Pc,e.initialUser,this.yt)}yc(e){return new Dc(Cc.Bs,this.yt)}gc(e){return new ah}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class xl extends Sl{constructor(e,t,n){super(),this.Ac=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ac.initialize(this,e),await _l(this.Ac.syncEngine),await Mh(this.Ac.remoteStore),await this.persistence.li(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Ic(e){return Bc(this.persistence,new Pc,e.initialUser,this.yt)}Tc(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new sc(n,e.asyncQueue,t)}Ec(e,t){var n=new gs(t,this.persistence);return new fs(e.asyncQueue,n)}yc(e){var t=Oc(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Ku.withCacheSize(this.cacheSizeBytes):Ku.DEFAULT;return new Lc(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,dh(),fh(),this.yt,this.sharedClientState,!!this.forceOwnership)}gc(e){return new ah}}class Dl extends xl{constructor(e,t){super(e,t,!1),this.Ac=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ac.syncEngine;this.sharedClientState instanceof ih&&(this.sharedClientState.syncEngine={Fr:(async function(e,t,n,r){var s=e,i=await function(e,n){const r=e,s=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>s.Tn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):rs.resolve(null)))}(s.localStore,t);null!==i?("pending"===n?await Mh(s.remoteStore):"acknowledged"===n||"rejected"===n?(gl(s,t,r||null),fl(s,t),s.localStore.mutationQueue.An(t)):br(),await wl(s,i)):yr("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),$r:(async function(e,t,n,r){const s=e;if(s.dc)yr("SyncEngine","Ignoring unexpected query state notification.");else{var i=s.rc.get(t);if(i&&0<i.length)switch(n){case"current":case"not-current":{const e=await Hc(s.localStore,Wi(i[0])),r=Pa.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,_s.EMPTY_BYTE_STRING);await wl(s,e,r);break}case"rejected":await Qc(s.localStore,t,!0),ml(s,t,r);break;default:br()}}}).bind(null,t),Br:(async function(e,t,n){const r=Tl(e);if(r.dc){for(const e of t)if(r.rc.has(e))yr("SyncEngine","Adding an already active target "+e);else{const t=await Wc(r.localStore,e),n=await $c(r.localStore,t);await ul(r,El(t),n.targetId,!1,n.resumeToken),_h(r.remoteStore,n)}for(const e of n)r.rc.has(e)&&await Qc(r.localStore,e,!1).then(()=>{Sh(r.remoteStore,e),ml(r,e)}).catch(ns)}}).bind(null,t),vi:(function(e){return e.localStore.persistence.vi()}).bind(null,t),Mr:(async function(e,t){const n=e;return Hc(n.localStore,t).then(e=>wl(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.li(async e=>{await Il(this.Ac.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}gc(e){var t=dh();if(!ih.C(t))throw new _r(Tr.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=Oc(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new ih(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class Al{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>ll(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){yr("SyncEngine","User change. New user:",t.toKey());const r=await Uc(n.localStore,t);n.currentUser=t,(e=n).lc.forEach(e=>{e.forEach(e=>{e.reject(new _r(Tr.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.lc.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await wl(n,r.ji)}}).bind(null,this.syncEngine),await Ph(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new zh}createDatastore(e){var t,n,r,s,i=gh(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new lh(t));return n=e.authCredentials,r=e.appCheckCredentials,s=t,e=i,new wh(n,r,s,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,s=e=>ll(this.syncEngine,e,0),i=new(uh.C()?uh:oh),new bh(t,n,r,s,i);var t,n,r,s,i}createSyncEngine(e,t){return function(e,t,n,r,s,i,a){const o=new ol(e,t,n,r,s,i);return a&&(o.dc=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;yr("RemoteStore","RemoteStore shutting down."),t._u.add(5),await Th(t),t.mu.shutdown(),t.gu.set("Unknown")}(this.remoteStore)}}function Cl(e,t,n){if(!n)throw new _r(Tr.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Nl(e,t,n,r){if(!0===t&&!0===r)throw new _r(Tr.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function kl(e){if(!jr.isDocumentKey(e))throw new _r(Tr.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Rl(e){if(jr.isDocumentKey(e))throw new _r(Tr.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ll(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":br();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function Ml(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new _r(Tr.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Ll(e);throw new _r(Tr.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Fl(e,t){if(t<=0)throw new _r(Tr.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}const Ol=new Map;class Vl{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new _r(Tr.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new _r(Tr.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,Nl("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Pl{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Vl({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new _r(Tr.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new _r(Tr.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Vl(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Dr;switch(e.type){case"gapi":var t=e.client;return new kr(t,e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new _r(Tr.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Ol.get(e);t&&(yr("ComponentProvider","Removing Datastore"),Ol.delete(e),t.terminate())}(this),Promise.resolve()}}function ql(n,e,t,r={}){var s;const i=(n=Ml(n,Pl))._getSettings();if("firestore.googleapis.com"!==i.host&&i.host!==e&&wr("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},i),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=fr.MOCK_USER;else{e=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,s=e.sub||e.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},e),[a(JSON.stringify({alg:"none",type:"JWT"})),a(JSON.stringify(s)),""].join(".")}(r.mockUserToken,null===(s=n._app)||void 0===s?void 0:s.options.projectId);const i=r.mockUserToken.sub||r.mockUserToken.user_id;if(!i)throw new _r(Tr.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new fr(i)}n._authCredentials=new Ar(new xr(e,t))}}class Bl{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Gl(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Bl(this.firestore,e,this._key)}}class Ul{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Ul(this.firestore,e,this._query)}}class Gl extends Ul{constructor(e,t,n){super(e,t,Fi(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Bl(this.firestore,null,new jr(e))}withConverter(e){return new Gl(this.firestore,e,this._path)}}function Kl(e,t,...n){if(e=m(e),Cl("collection","path",t),e instanceof Pl){var r=Ur.fromString(t,...n);return Rl(r),new Gl(e,null,r)}if(!(e instanceof Bl||e instanceof Gl))throw new _r(Tr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Ur.fromString(t,...n));return Rl(r),new Gl(e.firestore,null,r)}function jl(e,t,...n){if(e=m(e),Cl("doc","path",t=1===arguments.length?Mr.R():t),e instanceof Pl){var r=Ur.fromString(t,...n);return kl(r),new Bl(e,null,new jr(r))}if(!(e instanceof Bl||e instanceof Gl))throw new _r(Tr.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Ur.fromString(t,...n));return kl(r),new Bl(e.firestore,e instanceof Gl?e.converter:null,new jr(r))}function $l(e,t){return e=m(e),t=m(t),(e instanceof Bl||e instanceof Gl)&&(t instanceof Bl||t instanceof Gl)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function Ql(e,t){return e=m(e),t=m(t),e instanceof Ul&&t instanceof Ul&&e.firestore===t.firestore&&ji(e._query,t._query)&&e.converter===t.converter}function zl(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class Wl{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Rc(this.observer.next,e)}error(e){this.observer.error?this.Rc(this.observer.error,e):vr("Uncaught Error in snapshot listener:",e.toString())}bc(){this.muted=!0}Rc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class Hl{constructor(e,t){this.Pc=e,this.yt=t,this.metadata=new Sr,this.buffer=new Uint8Array,this.vc=new TextDecoder("utf-8"),this.Vc().then(e=>{e&&e.Ou()?this.metadata.resolve(e.ku.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ku)}`))},e=>this.metadata.reject(e))}close(){return this.Pc.cancel()}async getMetadata(){return this.metadata.promise}async mc(){return await this.getMetadata(),this.Vc()}async Vc(){var e=await this.Sc();if(null===e)return null;var t=this.vc.decode(e),n=Number(t);isNaN(n)&&this.Dc(`length string (${t}) is not valid number`);t=await this.Cc(n);return new Jh(JSON.parse(t),e.length+n)}xc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Sc(){for(;this.xc()<0&&!await this.Nc(););if(0===this.buffer.length)return null;var e=this.xc();e<0&&this.Dc("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Cc(e){for(;this.buffer.length<e;)await this.Nc()&&this.Dc("Reached the end of bundle when more is expected.");var t=this.vc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}Dc(e){throw this.Pc.cancel(),new Error(`Invalid bundle format: ${e}`)}async Nc(){var e=await this.Pc.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class Yl{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new _r(Tr.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=ao(r.yt)+"/documents",s={documents:t.map(e=>no(r.yt,e))},i=await r._o("BatchGetDocuments",n,s,t.length),a=new Map;i.forEach(e=>{const t=(n=r.yt,"found"in(e=e)?function(e,t){Er(!!t.found),t.found.name,t.found.updateTime;var n=ro(e,t.found.name),r=Za(t.found.updateTime),s=t.found.createTime?Za(t.found.createTime):qr.min(),i=new Ti({mapValue:{fields:t.found.fields}});return _i.newFoundDocument(n,r,s,i)}(n,e):"missing"in e?function(e,t){Er(!!t.missing),Er(!!t.readTime);var n=ro(e,t.missing),r=Za(t.readTime);return _i.newNoDocument(n,r)}(n,e):br());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Er(!!t),o.push(t)}),o}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new Ta(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=jr.fromPath(t);this.mutations.push(new _a(n,this.precondition(n)))}),await async function(e,t){const n=e,r=ao(n.yt)+"/documents",s={writes:t.map(e=>ho(n.yt,e))};await n.ao("Commit",r,s)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw br();t=qr.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new _r(Tr.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(qr.min())?la.exists(!1):la.updateTime(t):la.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return la.exists(!0);if(t.isEqual(qr.min()))throw new _r(Tr.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return la.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class Xl{constructor(e,t,n,r,s){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=s,this.kc=n.maxAttempts,this.xo=new mh(this.asyncQueue,"transaction_retry")}run(){--this.kc,this.Oc()}Oc(){this.xo.Ro(async()=>{const t=new Yl(this.datastore),e=this.Mc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Fc(e)}))}).catch(e=>{this.Fc(e)})})}Mc(e){try{var t=this.updateFunction(e);return!bs(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Fc(e){0<this.kc&&this.$c(e)?(--this.kc,this.asyncQueue.enqueueAndForget(()=>(this.Oc(),Promise.resolve()))):this.deferred.reject(e)}$c(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!xa(t)}}class Jl{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=fr.UNAUTHENTICATED,this.clientId=Mr.R(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{yr("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(yr("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new _r(Tr.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Sr;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=Gh(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function Zl(e,t){e.asyncQueue.verifyOperationInProgress(),yr("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await Uc(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function ed(e,n){e.asyncQueue.verifyOperationInProgress();var t=await td(e);yr("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>Vh(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>Vh(n.remoteStore,t)),e.onlineComponents=n}async function td(e){return e.offlineComponents||(yr("FirestoreClient","Using default OfflineComponentProvider"),await Zl(e,new Sl)),e.offlineComponents}async function nd(e){return e.onlineComponents||(yr("FirestoreClient","Using default OnlineComponentProvider"),await ed(e,new Al)),e.onlineComponents}function rd(e){return td(e).then(e=>e.persistence)}function sd(e){return td(e).then(e=>e.localStore)}function id(e){return nd(e).then(e=>e.remoteStore)}function ad(e){return nd(e).then(e=>e.syncEngine)}async function od(e){const t=await nd(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=Tl(e);let r,s;const i=n.ic.get(t);if(i)r=i.targetId,n.sharedClientState.addLocalQueryTarget(r),s=i.view.ec();else{const e=await $c(n.localStore,Ui(t));n.isPrimaryClient&&_h(n.remoteStore,e);const i=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,s=await ul(n,t,r,"current"===i,e.resumeToken)}return s}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ic.get(t),s=n.rc.get(r.targetId);if(1<s.length)return n.rc.set(r.targetId,s.filter(e=>!ji(e,t))),void n.ic.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await Qc(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),Sh(n.remoteStore,r.targetId),ml(n,r.targetId)}).catch(ns)):(ml(n,r.targetId),await Qc(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function ud(e,t,n={}){const r=new Sr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,s,i,a){const e=new Wl({next:e=>{r.enqueueAndForget(()=>Hh(n,o));var t=e.docs.has(s);!t&&e.fromCache?a.reject(new _r(Tr.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&i&&"server"===i.source?a.reject(new _r(Tr.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.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new Xh(Fi(s.path),e,{includeMetadataChanges:!0,Nu:!0});return Wh(n,o)}(await od(e),e.asyncQueue,t,n,r)),r.promise}function cd(e,t,n={}){const r=new Sr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,s){const i=new Wl({next:e=>{n.enqueueAndForget(()=>Hh(t,a)),e.fromCache&&"server"===r.source?s.reject(new _r(Tr.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.)')):s.resolve(e)},error:e=>s.reject(e)}),a=new Xh(e,i,{includeMetadataChanges:!0,Nu:!0});return Wh(t,a)}(await od(e),e.asyncQueue,t,n,r)),r.promise}function hd(e,t,n,r){const s=(n=n,t=gh(t),i="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return zl(e,void 0);if(e instanceof ArrayBuffer)return zl(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(i),t=t,new Hl(n,t));var i;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var s=await n.getMetadata();if(await function(e,t){const n=e,r=Za(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ns.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,s))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:s.totalDocuments,bytesLoaded:s.totalBytes,totalDocuments:s.totalDocuments,totalBytes:s.totalBytes}),Promise.resolve(new Set);r._updateProgress(tl(s));const a=new el(s,t.localStore,n.yt);let e=await n.mc();for(;e;){const t=await a.Fu(e);t&&r._updateProgress(t),e=await n.mc()}var i=await a.complete();return await wl(t,i.Lu,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ns.saveBundleMetadata(e,t))}(t.localStore,s),r._completeWith(i.progress),Promise.resolve(i.Bu)}catch(t){return wr("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await ad(e),s,r)})}class ld{constructor(){this.Bc=Promise.resolve(),this.Lc=[],this.qc=!1,this.Uc=[],this.Kc=null,this.Gc=!1,this.Qc=!1,this.jc=[],this.xo=new mh(this,"async_queue_retry"),this.Wc=()=>{var e=fh();e&&yr("AsyncQueue","Visibility state changed to "+e.visibilityState),this.xo.Po()};const e=fh();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Wc)}get isShuttingDown(){return this.qc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.zc(),this.Hc(e)}enterRestrictedMode(e){if(!this.qc){this.qc=!0,this.Qc=e||!1;const t=fh();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Wc)}}enqueue(e){if(this.zc(),this.qc)return new Promise(()=>{});const t=new Sr;return this.Hc(()=>this.qc&&this.Qc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Lc.push(e),this.Jc()))}async Jc(){if(0!==this.Lc.length){try{await this.Lc[0](),this.Lc.shift(),this.xo.reset()}catch(e){if(!us(e))throw e;yr("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Lc.length&&this.xo.Ro(()=>this.Jc())}}Hc(e){var t=this.Bc.then(()=>(this.Gc=!0,e().catch(e=>{throw this.Kc=e,this.Gc=!1,vr("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Gc=!1,e))));return this.Bc=t}enqueueAfterDelay(e,t,n){this.zc(),-1<this.jc.indexOf(e)&&(t=0);var r=Uh.createAndSchedule(this,e,t,n,e=>this.Yc(e));return this.Uc.push(r),r}zc(){this.Kc&&br()}verifyOperationInProgress(){}async Xc(){for(var e;await(e=this.Bc),e!==this.Bc;);}Zc(e){for(const t of this.Uc)if(t.timerId===e)return!0;return!1}ta(t){return this.Xc().then(()=>{this.Uc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Uc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Xc()})}ea(e){this.jc.push(e)}Yc(e){var t=this.Uc.indexOf(e);this.Uc.splice(t,1)}}function dd(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class fd{constructor(){this._progressObserver={},this._taskCompletionResolver=new Sr,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var gd,md,pd;class yd extends Pl{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new ld,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||wd(this),this._firestoreClient.terminate()}}function vd(e){return e._firestoreClient||wd(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function wd(e){var t,n,r,s,i,a=e._freezeSettings(),a=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",s=e._persistenceKey,i=a,new ps(n,r,s,i.host,i.ssl,i.experimentalForceLongPolling,i.experimentalAutoDetectLongPolling,i.useFetchStreams));e._firestoreClient=new Jl(e._authCredentials,e._appCheckCredentials,e._queue,a)}function Id(e,n,r){const s=new Sr;return e.asyncQueue.enqueue(async()=>{try{await Zl(e,r),await ed(e,n),s.resolve()}catch(e){const n=e;if(!("FirebaseError"===(t=n).name?t.code===Tr.FAILED_PRECONDITION||t.code===Tr.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw n;wr("Error enabling offline persistence. Falling back to persistence disabled: "+n),s.reject(n)}var t}).then(()=>s.promise)}function bd(e){return function(e){const t=new Sr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;Nh(n.remoteStore)||yr("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.lc.get(e)||[];r.push(t),n.lc.set(e,r)}catch(e){const n=Gh(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await ad(e),t)),t.promise}(vd(e=Ml(e,yd)))}function Ed(e){return(n=vd(e=Ml(e,yd))).asyncQueue.enqueue(async()=>{const e=await rd(n),t=await id(n);return e.setNetworkEnabled(!0),function(){const e=t;return e._u.delete(0),Eh(e)}()});var n}function Td(e){return(n=vd(e=Ml(e,yd))).asyncQueue.enqueue(async()=>{const e=await rd(n),t=await id(n);return e.setNetworkEnabled(!1),async function(){const e=t;e._u.add(0),await Th(e),e.gu.set("Offline")}()});var n}function _d(t,e){return n=vd(t=Ml(t,yd)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ns.getNamedQuery(e,t))}(await sd(n),r)).then(e=>e?new Ul(t,null,e.query):null);var n,r}function Sd(e){if(e._initialized||e._terminated)throw new _r(Tr.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class xd{constructor(e){this._byteString=e}static fromBase64String(e){try{return new xd(_s.fromBase64String(e))}catch(e){throw new _r(Tr.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new xd(_s.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class Dd{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new _r(Tr.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Kr(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class Ad{constructor(e){this._methodName=e}}class Cd{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new _r(Tr.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new _r(Tr.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Fr(this._lat,e._lat)||Fr(this._long,e._long)}}const Nd=/^__.*__$/;class kd{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new wa(e,this.data,this.fieldMask,t,this.fieldTransforms):new va(e,this.data,t,this.fieldTransforms)}}class Rd{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new wa(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function Ld(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw br()}}class Md{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.yt=n,this.ignoreUndefinedProperties=r,void 0===s&&this.na(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get sa(){return this.settings.sa}ia(e){return new Md(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.yt,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}ra(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.ua(e),r}ca(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.ia({path:n,oa:!1});return r.na(),r}aa(e){return this.ia({path:void 0,oa:!0})}ha(e){return ef(e,this.settings.methodName,this.settings.la||!1,this.path,this.settings.fa)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}na(){if(this.path)for(let e=0;e<this.path.length;e++)this.ua(this.path.get(e))}ua(e){if(0===e.length)throw this.ha("Document fields must not be empty");if(Ld(this.sa)&&Nd.test(e))throw this.ha('Document fields cannot begin and end with "__"')}}class Fd{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.yt=n||gh(e)}da(e,t,n,r=!1){return new Md({sa:e,methodName:t,fa:n,path:Kr.emptyPath(),oa:!1,la:r},this.databaseId,this.yt,this.ignoreUndefinedProperties)}}function Od(e){var t=e._freezeSettings(),n=gh(e._databaseId);return new Fd(e._databaseId,!!t.ignoreUndefinedProperties,n)}function Vd(e,t,n,r,s,i={}){const a=e.da(i.merge||i.mergeFields?2:0,t,n,s);Yd("Data must be an object, but it was:",a,r);var o=Wd(r,a);let u,c;if(i.merge)u=new Ei(a.fieldMask),c=a.fieldTransforms;else if(i.mergeFields){const e=[];for(const r of i.mergeFields){const s=Xd(t,r,n);if(!a.contains(s))throw new _r(Tr.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);tf(e,s)||e.push(s)}u=new Ei(e),c=a.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,c=a.fieldTransforms;return new kd(new Ti(o),u,c)}class Pd extends Ad{_toFieldTransform(e){if(2!==e.sa)throw 1===e.sa?e.ha(`${this._methodName}() can only appear at the top level of your update data`):e.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof Pd}}function qd(e,t,n){return new Md({sa:3,fa:t.settings.fa,methodName:e._methodName,oa:n},t.databaseId,t.yt,t.ignoreUndefinedProperties)}class Bd extends Ad{_toFieldTransform(e){return new ca(e.path,new ta)}isEqual(e){return e instanceof Bd}}class Ud extends Ad{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=qd(this,e,!0),n=this._a.map(e=>zd(e,t)),r=new na(n);return new ca(e.path,r)}isEqual(e){return this===e}}class Gd extends Ad{constructor(e,t){super(e),this._a=t}_toFieldTransform(e){const t=qd(this,e,!0),n=this._a.map(e=>zd(e,t)),r=new sa(n);return new ca(e.path,r)}isEqual(e){return this===e}}class Kd extends Ad{constructor(e,t){super(e),this.wa=t}_toFieldTransform(e){var t=new aa(e.yt,Ji(e.yt,this.wa));return new ca(e.path,t)}isEqual(e){return this===e}}function jd(e,s,i,t){const a=e.da(1,s,i);Yd("Data must be an object, but it was:",a,t);const o=[],u=Ti.empty();ws(t,(e,t)=>{var n=Zd(s,e,i);t=m(t);var r=a.ca(n);if(t instanceof Pd)o.push(n);else{const e=zd(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new Ei(o);return new Rd(u,n,a.fieldTransforms)}function $d(e,t,n,r,s,i){const a=e.da(1,t,n),o=[Xd(t,r,n)],u=[s];if(i.length%2!=0)throw new _r(Tr.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<i.length;f+=2)o.push(Xd(t,i[f])),u.push(i[f+1]);const c=[],h=Ti.empty();for(let g=o.length-1;0<=g;--g)if(!tf(c,o[g])){const t=o[g];var l=m(l=u[g]);const r=a.ca(t);if(l instanceof Pd)c.push(t);else{const e=zd(l,r);null!=e&&(c.push(t),h.set(t,e))}}var d=new Ei(c);return new Rd(h,d,a.fieldTransforms)}function Qd(e,t,n,r=!1){return zd(n,e.da(r?4:3,t))}function zd(i,e){if(Hd(i=m(i)))return Yd("Unsupported field value:",e,i),Wd(i,e);if(i instanceof Ad)return function(e,t){if(!Ld(t.sa))throw t.ha(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.ha(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(i,e),null;if(void 0===i&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),i instanceof Array){if(e.settings.oa&&4!==e.sa)throw e.ha("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const s of i){let e=zd(s,t.aa(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=m(i)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Ji(t.yt,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=Pr.fromDate(e);return{timestampValue:Xa(t.yt,n)}}if(e instanceof Pr){n=new Pr(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Xa(t.yt,n)}}if(e instanceof Cd)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof xd)return{bytesValue:Ja(t.yt,e._byteString)};if(e instanceof Bl){const r=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(r))throw t.ha(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:eo(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.ha(`Unsupported field value: ${Ll(e)}`)}(0,e)}function Wd(e,r){const s={};return Is(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):ws(e,(e,t)=>{var n=zd(t,r.ra(e));null!=n&&(s[e]=n)}),{mapValue:{fields:s}}}function Hd(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Pr||e instanceof Cd||e instanceof xd||e instanceof Bl||e instanceof Ad)}function Yd(e,t,n){if(!Hd(n)||("object"!=typeof(s=n)||null===s||Object.getPrototypeOf(s)!==Object.prototype&&null!==Object.getPrototypeOf(s))){var r=Ll(n);throw"an object"===r?t.ha(e+" a custom object"):t.ha(e+" "+r)}var s}function Xd(e,t,n){if((t=m(t))instanceof Dd)return t._internalPath;if("string"==typeof t)return Zd(e,t);throw ef("Field path arguments must be of type string or ",e,!1,void 0,n)}const Jd=new RegExp("[~\\*/\\[\\]]");function Zd(t,n,r){if(0<=n.search(Jd))throw ef(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new Dd(...n.split("."))._internalPath}catch(e){throw ef(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function ef(e,t,n,r,s){var i=r&&!r.isEmpty(),a=void 0!==s;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(i||a)&&(u+=" (found",i&&(u+=` in field ${r}`),a&&(u+=` in document ${s}`),u+=")"),new _r(Tr.INVALID_ARGUMENT,o+e+u)}function tf(e,t){return e.some(e=>e.isEqual(t))}class nf{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new Bl(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new rf(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(sf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class rf extends nf{data(){return super.data()}}function sf(e,t){return"string"==typeof t?Zd(e,t):(t instanceof Dd?t:t._delegate)._internalPath}function af(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new _r(Tr.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class of{}class uf extends of{}function cf(e,t,...n){let r=[];t instanceof of&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof lf).length,n=e.filter(e=>e instanceof hf).length;if(1<t||0<t&&0<n)throw new _r(Tr.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const t of r)e=t._apply(e);return e}class hf extends uf{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new hf(e,t,n)}_apply(e){var t=this._parse(e);return wf(e._query,t),new Ul(e.firestore,e.converter,Gi(e._query,t))}_parse(e){var t=Od(e.firestore);return function(e,t,n,r,s,i,a){let o;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new _r(Tr.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){vf(a,i);const t=[];for(const n of a)t.push(yf(r,e,n));o={arrayValue:{values:t}}}else o=yf(r,e,a)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||vf(a,i),o=Qd(n,t,a,"in"===i||"not-in"===i);return Zs.create(s,i,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class lf extends of{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new lf(e,t)}_parse(t){var e=this._queryConstraints.map(e=>e._parse(t)).filter(e=>0<e.getFilters().length);return 1===e.length?e[0]:ei.create(e,this._getOperator())}_apply(e){const n=this._parse(e);return 0===n.getFilters().length?e:(function(e){let t=e;for(const e of n.getFlattenedFilters())wf(t,e),t=Gi(t,e)}(e._query),new Ul(e.firestore,e.converter,Gi(e._query,n)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class df extends uf{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new df(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new _r(Tr.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new _r(Tr.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,s=new mi(t,n);return n=s,null!==Vi(e=e)||null!==(r=Pi(e))&&If(0,r,n.field),s}(e._query,this._field,this._direction);return new Ul(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Li(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class ff extends uf{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new ff(e,t,n)}_apply(e){return new Ul(e.firestore,e.converter,Ki(e._query,this._limit,this._limitType))}}class gf extends uf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new gf(e,t,n)}_apply(e){var t,n=pf(e,this.type,this._docOrFields,this._inclusive);return new Ul(e.firestore,e.converter,(t=e._query,e=n,new Li(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class mf extends uf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new mf(e,t,n)}_apply(e){var t,n=pf(e,this.type,this._docOrFields,this._inclusive);return new Ul(e.firestore,e.converter,(t=e._query,e=n,new Li(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function pf(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof nf)return function(e,t,n,r,s){if(!r)throw new _r(Tr.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const n of Bi(e))if(n.field.isKeyField())i.push(qs(t,r.key));else{const e=r.data.field(n.field);if(Cs(e))throw new _r(Tr.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}i.push(e)}return new Hs(i,s)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var s=Od(e.firestore);return function(e,t,n,r,s,i){const a=e.explicitOrderBy;if(s.length>a.length)throw new _r(Tr.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let u=0;u<s.length;u++){const c=s[u];if(a[u].field.isKeyField()){if("string"!=typeof c)throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!qi(e)&&-1!==c.indexOf("/"))throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(Ur.fromString(c));if(!jr.isDocumentKey(n))throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const s=new jr(n);o.push(qs(t,s))}else{const e=Qd(n,r,c);o.push(e)}}return new Hs(o,i)}(e._query,e.firestore._databaseId,s,t,n,r)}function yf(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new _r(Tr.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!qi(t)&&-1!==n.indexOf("/"))throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(Ur.fromString(n));if(!jr.isDocumentKey(r))throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return qs(e,new jr(r))}if(n instanceof Bl)return qs(e,n._key);throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Ll(n)}.`)}function vf(e,t){if(!Array.isArray(e)||0===e.length)throw new _r(Tr.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new _r(Tr.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function wf(e,t){if(t.isInequality()){const r=Pi(e),s=t.field;if(null!==r&&!r.isEqual(s))throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${s.toString()}'`);var n=Vi(e);null!==n&&If(0,s,n)}const r=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(0<=t.indexOf(e.op))return e.op;return null}(e.filters,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new _r(Tr.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new _r(Tr.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function If(e,t,n){if(!n.isEqual(t))throw new _r(Tr.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class bf{convertValue(e,t="none"){switch(Ls(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Ds(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(As(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw br()}}convertObject(e,n){const r={};return ws(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new Cd(Ds(e.latitude),Ds(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return Cs(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ns(e));default:return null}}convertTimestamp(e){var t=xs(e);return new Pr(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Ur.fromString(e);Er(Io(n));const r=new ys(n.get(1),n.get(3)),s=new jr(n.popFirst(5));return r.isEqual(t)||vr(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),s}}function Ef(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class Tf extends bf{constructor(e){super(),this.firestore=e}convertBytes(e){return new xd(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bl(this.firestore,null,t)}}class _f{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Sf extends nf{constructor(e,t,n,r,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new xf(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(sf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class xf extends Sf{data(e={}){return super.data(e)}}class Df{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new _f(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new xf(this._firestore,this._userDataWriter,e.key,e,new _f(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new _r(Tr.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(i,t){if(i._snapshot.oldDocs.isEmpty()){let n=0;return i._snapshot.docChanges.map(e=>{var t=new xf(i._firestore,i._userDataWriter,e.doc.key,e.doc,new _f(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let s=i._snapshot.oldDocs;return i._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new xf(i._firestore,i._userDataWriter,e.doc.key,e.doc,new _f(i._snapshot.mutatedKeys.has(e.doc.key),i._snapshot.fromCache),i.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=s.indexOf(e.doc.key),s=s.delete(e.doc.key)),1!==e.type&&(s=s.add(e.doc),r=s.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return br()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function Af(e,t){return e instanceof Sf&&t instanceof Sf?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof Df&&t instanceof Df&&e._firestore===t._firestore&&Ql(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class Cf extends bf{constructor(e){super(),this.firestore=e}convertBytes(e){return new xd(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bl(this.firestore,null,t)}}function Nf(t){t=Ml(t,Bl);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return function(e,t){const n=new Sr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(t);s.isFoundDocument()?n.resolve(s):s.isNoDocument()?n.resolve(null):n.reject(new _r(Tr.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.)"))}catch(e){var r=Gh(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await sd(e),t,n)),n.promise}(e,t._key).then(e=>new Sf(n,r,t._key,e,new _f(null!==e&&e.hasLocalMutations,!0),t.converter))}function kf(t){t=Ml(t,Ul);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return function(e,t){const n=new Sr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const s=await zc(e,t,!0),i=new sl(t,s.Hi),a=i.Wu(s.documents),o=i.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=Gh(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await sd(e),t,n)),n.promise}(e,t._query).then(e=>new Df(n,r,t,e))}function Rf(e,t,n){e=Ml(e,Bl);var r=Ml(e.firestore,yd),s=Ef(e.converter,t,n);return Of(r,[Vd(Od(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,la.none())])}function Lf(e,t,n,...r){e=Ml(e,Bl);var s=Ml(e.firestore,yd),i=Od(s);let a;return a="string"==typeof(t=m(t))||t instanceof Dd?$d(i,"updateDoc",e._key,t,n,r):jd(i,"updateDoc",e._key,t),Of(s,[a.toMutation(e._key,la.exists(!0))])}function Mf(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},s=0;"object"!=typeof n[s]||dd(n[s])||(r=n[s],s++);var i={includeMetadataChanges:r.includeMetadataChanges};if(dd(n[s])){const t=n[s];n[s]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[s+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[s+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Bl)o=Ml(t.firestore,yd),u=Fi(t._key.path),a={next:e=>{n[s]&&n[s](Vf(o,t,e))},error:n[s+1],complete:n[s+2]};else{const c=Ml(t,Ul);o=Ml(c.firestore,yd),u=c._query;const h=new Cf(o);a={next:e=>{n[s]&&n[s](new Df(o,h,c,e))},error:n[s+1],complete:n[s+2]},af(t._query)}return function(e,t,n,r){const s=new Wl(r),i=new Xh(t,s,n);return e.asyncQueue.enqueueAndForget(async()=>Wh(await od(e),i)),()=>{s.bc(),e.asyncQueue.enqueueAndForget(async()=>Hh(await od(e),i))}}(vd(o),u,i,a)}function Ff(e,t){return function(e,t){const n=new Wl(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Ru.add(t),t.next()}(await od(e),n)),()=>{n.bc(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Ru.delete(t)}(await od(e),n))}}(vd(e=Ml(e,yd)),dd(t)?t:{next:t})}function Of(e,t){return function(e,t){const n=new Sr;return e.asyncQueue.enqueueAndForget(async()=>cl(await ad(e),t,n)),n.promise}(vd(e),t)}function Vf(e,t,n){var r=n.docs.get(t._key),s=new Cf(e);return new Sf(e,s,t._key,r,new _f(n.hasPendingWrites,n.fromCache),t.converter)}const Pf={maxAttempts:5};class qf{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=Od(e)}set(e,t,n){this._verifyNotCommitted();const r=Bf(e,this._firestore),s=Ef(r.converter,t,n),i=Vd(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,la.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var s=Bf(e,this._firestore);let i;return i="string"==typeof(t=m(t))||t instanceof Dd?$d(this._dataReader,"WriteBatch.update",s._key,t,n,r):jd(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,la.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=Bf(e,this._firestore);return this._mutations=this._mutations.concat(new Ta(t._key,la.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new _r(Tr.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function Bf(e,t){if((e=m(e)).firestore!==t)throw new _r(Tr.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class Uf extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=Od(e)}get(e){const n=Bf(e,this._firestore),r=new Tf(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return br();const t=e[0];if(t.isFoundDocument())return new nf(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new nf(this._firestore,r,n._key,null,n.converter);throw br()})}set(e,t,n){var r=Bf(e,this._firestore),s=Ef(r.converter,t,n),s=Vd(this._dataReader,"Transaction.set",r._key,s,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){var s=Bf(e,this._firestore),i="string"==typeof(t=m(t))||t instanceof Dd?$d(this._dataReader,"Transaction.update",s._key,t,n,r):jd(this._dataReader,"Transaction.update",s._key,t);return this._transaction.update(s._key,i),this}delete(e){var t=Bf(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=Bf(e,this._firestore),n=new Cf(this._firestore);return super.get(e).then(e=>new Sf(this._firestore,n,t._key,e._document,new _f(!1,!1),t.converter))}}function Gf(t,n,e){t=Ml(t,yd);var r=Object.assign(Object.assign({},Pf),e);return function(){if(r.maxAttempts<1)throw new _r(Tr.INVALID_ARGUMENT,"Max attempts must be at least 1")}(),function(t,n,r){const s=new Sr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await nd(t).then(e=>e.datastore);new Xl(t.asyncQueue,e,r,n,s).run()}),s.promise}(vd(t),e=>n(new Uf(t,e)),r)}gd=mg.SDK_VERSION,gr=gd,mg._registerComponent(new g("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),s=new yd(new Cr(e.getProvider("auth-internal")),new Lr(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new _r(Tr.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new ys(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:!0},n),s._setSettings(n),s},"PUBLIC").setMultipleInstances(!0)),mg.registerVersion(dr,"3.8.1",void 0),mg.registerVersion(dr,"3.8.1","esm2017");function Kf(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new _r("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function jf(){if("undefined"==typeof Uint8Array)throw new _r("unimplemented","Uint8Arrays are not available in this environment.")}function $f(){if("undefined"==typeof atob)throw new _r("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Qf{constructor(e){this._delegate=e}static fromBase64String(e){return $f(),new Qf(xd.fromBase64String(e))}static fromUint8Array(e){return jf(),new Qf(xd.fromUint8Array(e))}toBase64(){return $f(),this._delegate.toBase64()}toUint8Array(){return jf(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function zf(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class Wf{enableIndexedDbPersistence(e,t){return function(e,t){Sd(e=Ml(e,yd));var n=vd(e),r=e._freezeSettings(),s=new Al;return Id(n,s,new xl(s,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){Sd(e=Ml(e,yd));var t=vd(e),n=e._freezeSettings(),r=new Al;return Id(t,r,new Dl(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new _r(Tr.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Sr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!is.C())return Promise.resolve();var t=e+"main";await is.delete(t)}(Oc(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Hf{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof ys||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||wr("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){ql(this._delegate,e,t,n)}enableNetwork(){return Ed(this._delegate)}disableNetwork(){return Td(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Nl("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return bd(this._delegate)}onSnapshotsInSync(e){return Ff(this._delegate,e)}get app(){if(!this._appCompat)throw new _r("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new cg(this,Kl(this._delegate,e))}catch(e){throw tg(e,"collection()","Firestore.collection()")}}doc(e){try{return new eg(this,jl(this._delegate,e))}catch(e){throw tg(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new ag(this,function(e,t){if(e=Ml(e,Pl),Cl("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new _r(Tr.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ul(e,null,(t=t,new Li(Ur.emptyPath(),t)))}(this._delegate,e))}catch(e){throw tg(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Gf(this._delegate,e=>t(new Xf(this,e)))}batch(){return vd(this._delegate),new Jf(new qf(this._delegate,e=>Of(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=vd(t=Ml(t,yd)),r=new fd,hd(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return _d(this._delegate,e).then(e=>e?new ag(this,e):null)}}class Yf extends bf{constructor(e){super(),this.firestore=e}convertBytes(e){return new Qf(new xd(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return eg.forKey(t,this.firestore,null)}}class Xf{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Yf(e)}get(e){const t=hg(e);return this._delegate.get(t).then(e=>new sg(this._firestore,new Sf(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=hg(e);return n?(Kf("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=hg(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=hg(e);return this._delegate.delete(t),this}}class Jf{constructor(e){this._delegate=e}set(e,t,n){var r=hg(e);return n?(Kf("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var s=hg(e);return 2===arguments.length?this._delegate.update(s,t):this._delegate.update(s,t,n,...r),this}delete(e){var t=hg(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Zf{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new xf(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new ig(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=Zf.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let s=r.get(t);return s||(s=new Zf(e,new Yf(e),t),r.set(t,s)),s}}Zf.INSTANCES=new WeakMap;class eg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Yf(e)}static forPath(e,t,n){if(e.length%2!=0)throw new _r("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new eg(t,new Bl(t._delegate,n,new jr(e)))}static forKey(e,t,n){return new eg(t,new Bl(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new cg(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new cg(this.firestore,Kl(this._delegate,e))}catch(e){throw tg(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Bl&&$l(this._delegate,e)}set(e,t){t=Kf("DocumentReference.set",t);try{return t?Rf(this._delegate,e,t):Rf(this._delegate,e)}catch(e){throw tg(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?Lf(this._delegate,e):Lf(this._delegate,e,t,...n)}catch(e){throw tg(e,"updateDoc()","DocumentReference.update()")}}delete(){return Of(Ml((e=this._delegate).firestore,yd),[new Ta(e._key,la.none())]);var e}onSnapshot(...e){var t=ng(e),n=rg(e,e=>new sg(this.firestore,new Sf(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return Mf(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?Nf:"server"===(null==e?void 0:e.source)?function(t){t=Ml(t,Bl);const n=Ml(t.firestore,yd);return ud(vd(n),t._key,{source:"server"}).then(e=>Vf(n,t,e))}:function(t){t=Ml(t,Bl);const n=Ml(t.firestore,yd);return ud(vd(n),t._key).then(e=>Vf(n,t,e))})(this._delegate),t.then(e=>new sg(this.firestore,new Sf(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new eg(this.firestore,e?this._delegate.withConverter(Zf.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function tg(e,t,n){return e.message=e.message.replace(t,n),e}function ng(e){for(const t of e)if("object"==typeof t&&!zf(t))return t;return{}}function rg(e,t){var n;let r;return r=zf(e[0])?e[0]:zf(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class sg{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new eg(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return Af(this._delegate,e._delegate)}}class ig extends sg{data(e){var t=this._delegate.data(e);return void 0!==t||br(),t}}class ag{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Yf(e)}where(e,t,n){try{return new ag(this.firestore,cf(this._delegate,(r=n,s=t,i=sf("where",e),hf._create(i,s,r))))}catch(e){throw tg(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,s,i}orderBy(e,t){try{return new ag(this.firestore,cf(this._delegate,([n,r="asc"]=[e,t],s=r,i=sf("orderBy",n),df._create(i,s))))}catch(e){throw tg(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,s,i}limit(e){try{return new ag(this.firestore,cf(this._delegate,(Fl("limit",t=e),ff._create("limit",t,"F"))))}catch(e){throw tg(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new ag(this.firestore,cf(this._delegate,(Fl("limitToLast",t=e),ff._create("limitToLast",t,"L"))))}catch(e){throw tg(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return gf._create("startAt",e,!0)}(...e)))}catch(e){throw tg(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return gf._create("startAfter",e,!1)}(...e)))}catch(e){throw tg(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return mf._create("endBefore",e,!1)}(...e)))}catch(e){throw tg(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new ag(this.firestore,cf(this._delegate,function(...e){return mf._create("endAt",e,!0)}(...e)))}catch(e){throw tg(e,"endAt()","Query.endAt()")}}isEqual(e){return Ql(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?kf:"server"===(null==e?void 0:e.source)?function(t){t=Ml(t,Ul);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return cd(e,t._query,{source:"server"}).then(e=>new Df(n,r,t,e))}:function(t){t=Ml(t,Ul);const n=Ml(t.firestore,yd),e=vd(n),r=new Cf(n);return af(t._query),cd(e,t._query).then(e=>new Df(n,r,t,e))})(this._delegate),t.then(e=>new ug(this.firestore,new Df(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=ng(e),n=rg(e,e=>new ug(this.firestore,new Df(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return Mf(this._delegate,t,n)}withConverter(e){return new ag(this.firestore,e?this._delegate.withConverter(Zf.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class og{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new ig(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class ug{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new ag(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new ig(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new og(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new ig(this._firestore,e))})}isEqual(e){return Af(this._delegate,e._delegate)}}class cg extends ag{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new eg(this.firestore,e):null}doc(e){try{return void 0===e?new eg(this.firestore,jl(this._delegate)):new eg(this.firestore,jl(this._delegate,e))}catch(e){throw tg(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=Ml(e.firestore,yd),r=jl(e),s=Ef(e.converter,t);return Of(n,[Vd(Od(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,la.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new eg(this.firestore,e))}isEqual(e){return $l(this._delegate,e._delegate)}withConverter(e){return new cg(this.firestore,e?this._delegate.withConverter(Zf.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function hg(e){return Ml(e,Bl)}const lg={Firestore:Hf,GeoPoint:Cd,Timestamp:Pr,Blob:Qf,Transaction:Xf,WriteBatch:Jf,DocumentReference:eg,DocumentSnapshot:sg,Query:ag,QueryDocumentSnapshot:ig,QuerySnapshot:ug,CollectionReference:cg,FieldPath:class dg{constructor(...e){this._delegate=new Dd(...e)}static documentId(){return new dg(Kr.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof Dd&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class fg{constructor(e){this._delegate=e}static serverTimestamp(){const e=new Bd("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new fg(e)}static delete(){const e=new Pd("deleteField");return e._methodName="FieldValue.delete",new fg(e)}static arrayUnion(...e){const t=function(...e){return new Ud("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new fg(t)}static arrayRemove(...e){const t=function(...e){return new Gd("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new fg(t)}static increment(e){const t=new Kd("increment",e);return t._methodName="FieldValue.increment",new fg(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,mr.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};md=t.default,pd=(e,t)=>new Hf(e,t,new Wf),md.INTERNAL.registerComponent(new g("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return pd(t,n)},"PUBLIC").setServiceProps(Object.assign({},lg))),md.registerVersion("@firebase/firestore-compat","0.3.1")}).apply(this,arguments)}catch(e){throw console.error(e),new Error("Cannot instantiate firebase-firestore-compat.js - be sure to load firebase-app.js first.")}});
  2. //# sourceMappingURL=firebase-firestore-compat.js.map