firebase 10.3.0 → 10.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/dist/esm/index.esm.js +1 -1
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/esm/index.esm.js +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/esm/index.esm.js +2 -2
- package/compat/dist/index.node.cjs +2 -2
- package/compat/dist/index.rn.cjs.js +2 -2
- package/firebase-analytics.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +5 -5
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-compat.js +4 -4
- package/firebase-compat.js.map +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +1 -1
- package/firebase-firestore-compat.js.map +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore-lite.js.map +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-firestore.js.map +1 -1
- package/firebase-functions.js +1 -1
- package/firebase-installations.js +1 -1
- package/firebase-messaging-sw.js +1 -1
- package/firebase-messaging.js +1 -1
- package/firebase-performance-standalone-compat.es2017.js +5 -5
- package/firebase-performance-standalone-compat.js +1 -1
- package/firebase-performance.js +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-storage.js +1 -1
- package/package.json +5 -5
|
@@ -1,2 +1,2 @@
|
|
|
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(Qg,Hg){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(Qg);function n(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),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 i=[];for(let h=0;h<n.length;h+=3){var s=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)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.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 i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}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 i=n[e.charAt(u++)],s=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==i||null==s||null==a||null==o)throw new c;r.push(i<<2|s>>4),64!==a&&(r.push(s<<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)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const o=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const i=()=>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__,s=()=>{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)}},a=()=>{try{return i()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||s()}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 h(){return!function(){var e=null===(e=a())||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 d extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,d.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,f.prototype.create)}}class f{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(g,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new d(i,s,n)}}const g=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class p{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}}(Qd=l=l||{})[Qd.DEBUG=0]="DEBUG",Qd[Qd.VERBOSE=1]="VERBOSE",Qd[Qd.INFO=2]="INFO",Qd[Qd.WARN=3]="WARN",Qd[Qd.ERROR=4]="ERROR",Qd[Qd.SILENT=5]="SILENT";const y={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},v=l.INFO,w={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},_=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=w[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};var b,I="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},E={},T=I||self;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 A="closure_uid_"+(1e9*Math.random()>>>0),D=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 M(e,s){function t(){}t.prototype=s.prototype,e.$=s.prototype,e.prototype=new t,(e.prototype.constructor=e).ac=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function L(){this.s=this.s,this.o=this.o}L.prototype.s=!1,L.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,A)&&e[A]||(e[A]=++D))},L.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const O=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 F(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 P(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(S(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function V(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}V.prototype.h=function(){this.defaultPrevented=!0};var U=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 q(e){return/^[\s\xa0]*$/.test(e)}function B(){var e=T.navigator;return(e=e&&e.userAgent)?e:""}function j(e){return-1!=B().indexOf(e)}function G(e){return G[" "](e),e}G[" "]=function(){};var $,z=j("Opera"),K=j("Trident")||j("MSIE"),Q=j("Edge"),H=Q||K,W=j("Gecko")&&!(-1!=B().toLowerCase().indexOf("webkit")&&!j("Edge"))&&!(j("Trident")||j("MSIE"))&&!j("Edge"),Y=-1!=B().toLowerCase().indexOf("webkit")&&!j("Edge");function X(){var e=T.document;return e?e.documentMode:void 0}e:{var J="",Z=(Z=B(),W?/rv:([^\);]+)(\)|;)/.exec(Z):Q?/Edge\/([\d\.]+)/.exec(Z):K?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Z):Y?/WebKit\/(\S+)/.exec(Z):z?/(?:Version)[ \/]?(\S+)/.exec(Z):void 0);if(Z&&(J=Z?Z[1]:""),K){Z=X();if(null!=Z&&Z>parseFloat(J)){$=String(Z);break e}}$=J}var ee=T.document&&K&&(X()||parseInt($,10))||void 0;function te(e,t){if(V.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(W){e:{try{G(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,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:ne[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&te.$.h.call(this)}}M(te,V);var ne={2:"touch",3:"pen",4:"mouse"};te.prototype.h=function(){te.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var re="closure_listenable_"+(1e6*Math.random()|0),ie=0;function se(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++ie,this.fa=this.ia=!1}function ae(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function oe(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function ue(e){const t={};for(const n in e)t[n]=e[n];return t}const ce="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function he(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<ce.length;e++)n=ce[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function le(e){this.src=e,this.g={},this.h=0}function de(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=O(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(ae(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function fe(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}le.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=fe(e,t,r,i);return-1<a?(t=e[a],n||(t.ia=!1)):((t=new se(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var ge="closure_lm_"+(1e6*Math.random()|0),me={};function pe(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=Ee(r);return t&&t[re]?t.P(n,r,x(i)?!!i.capture:!!i,s):ye(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)pe(e,t[s],n,r,i);return null}return n=Ee(n),e&&e[re]?e.O(t,n,x(r)?!!r.capture:!!r,i):ye(e,t,n,!1,r,i)}function ye(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=x(i)?!!i.capture:!!i,o=be(e);if(o||(e[ge]=o=new le(e)),(n=o.add(t,n,r,a,s)).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===(i=!U?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(we(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function ve(e){var t,n,r;"number"!=typeof e&&e&&!e.fa&&((t=e.src)&&t[re]?de(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(we(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=be(t))?(de(n,e),0==n.h&&(n.src=null,t[ge]=null)):ae(e)))}function we(e){return e in me?me[e]:me[e]="on"+e}function _e(e,t){var n,r;return e=!!e.fa||(t=new te(t,this),n=e.listener,r=e.la||e.src,e.ia&&ve(e),n.call(r,t))}function be(e){return(e=e[ge])instanceof le?e:null}var Ie="__closure_events_fn_"+(1e9*Math.random()>>>0);function Ee(t){return"function"==typeof t?t:(t[Ie]||(t[Ie]=function(e){return t.handleEvent(e)}),t[Ie])}function Te(){L.call(this),this.i=new le(this),(this.S=this).J=null}function Se(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"==typeof t?t=new V(t,e):t instanceof V?t.target=t.target||e:(a=t,he(t=new V(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=xe(s,r,!0,t)&&a;if(a=xe(s=t.g=e,r,!0,t)&&a,a=xe(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=xe(s=t.g=n[i],r,!1,t)&&a}function xe(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,u=t[s];u&&!u.fa&&u.capture==n&&(a=u.listener,o=u.la||u.src,u.ia&&de(e.i,u),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}M(Te,L),Te.prototype[re]=!0,Te.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=x(i)?!!i.capture:!!i,r=Ee(r),t&&t[re]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=fe(a=t.g[n],r,i,s))&&(ae(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&be(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?fe(n,r,i,s):t)?n[t]:null)&&ve(r))}(this,e,t,n,r)},Te.prototype.N=function(){if(Te.$.N.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++)ae(n[r]);delete t.g[e],t.h--}}this.J=null},Te.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Te.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Ae=T.JSON.stringify;var De=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 Ce,e=>e.reset());class Ce{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}}let Ne,ke=!1,Re=new class{constructor(){this.h=this.g=null}add(e,t){const n=De.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},Me=()=>{const e=T.Promise.resolve(void 0);Ne=()=>{e.then(Le)}};var Le=()=>{for(var e;e=function(){var e=Re;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=De;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}ke=!1};function Oe(e,t){Te.call(this),this.h=e||1,this.g=t||T,this.j=k(this.qb,this),this.l=Date.now()}function Fe(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function Pe(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)}M(Oe,Te),(b=Oe.prototype).ga=!1,b.T=null,b.qb=function(){var e;this.ga&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),Se(this,"tick"),this.ga&&(Fe(this),this.start())))},b.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},b.N=function(){Oe.$.N.call(this),Fe(this),delete this.g};class Ve extends L{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=Pe(()=>{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)}N(){super.N(),this.g&&(T.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Ue(e){L.call(this),this.h=e,this.g={}}M(Ue,L);var qe=[];function Be(e,t,n,r){Array.isArray(n)||(n&&(qe[0]=n.toString()),n=qe);for(var i=0;i<n.length;i++){var s=pe(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function je(e){oe(e.g,function(e,t){this.g.hasOwnProperty(t)&&ve(e)},e),e.g={}}function Ge(){this.g=!0}function $e(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 i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return Ae(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Ue.prototype.N=function(){Ue.$.N.call(this),je(this)},Ue.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},Ge.prototype.Ea=function(){this.g=!1},Ge.prototype.info=function(){};var ze={},Ke=null;function Qe(){return Ke=Ke||new Te}function He(e){V.call(this,ze.Ta,e)}function We(){var e=Qe();Se(e,new He(e))}function Ye(e,t){V.call(this,ze.STAT_EVENT,e),this.stat=t}function Xe(e){var t=Qe();Se(t,new Ye(t,e))}function Je(e,t){V.call(this,ze.Ua,e),this.size=t}function Ze(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return T.setTimeout(function(){e()},t)}ze.Ta="serverreachability",M(He,V),ze.STAT_EVENT="statevent",M(Ye,V),ze.Ua="timingevent",M(Je,V);var et={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},tt={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function nt(){}function rt(e){return e.h||(e.h=e.i())}function it(){}nt.prototype.h=null;I={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function st(){V.call(this,"d")}function at(){V.call(this,"c")}function ot(){}function ut(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new Ue(this),this.P=lt,this.V=new Oe(e=H?125:void 0),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new ct}function ct(){this.i=null,this.g="",this.h=!1}M(st,V),M(at,V),M(ot,nt),ot.prototype.g=function(){return new XMLHttpRequest},ot.prototype.i=function(){return{}};var ht=new ot,lt=45e3,dt={},ft={};function gt(e,t,n){e.L=1,e.v=Rt(At(t)),e.s=n,e.S=!0,mt(e,null)}function mt(e,t){e.G=Date.now(),vt(e),e.A=At(e.v);var a,o,u,c,h,l,n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),zt(n.i,"t",r),e.C=0,n=e.l.J,e.h=new ct,e.g=zn(e.l,n?t:null,!e.s),0<e.O&&(e.M=new Ve(k(e.Pa,e,e.g),e.O)),Be(e.U,e.g,"readystatechange",e.nb),t=e.I?ue(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),We(),a=e.j,o=e.u,u=e.A,c=e.m,h=e.W,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,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+c+") [attempt "+h+"]: "+o+"\n"+u+"\n"+e})}function pt(e){return e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function yt(e,t,n){let r=!0,i;for(;!e.J&&e.C<n.length;){if(i=(a=n,u=o=void 0,o=(s=e).C,-1==(u=a.indexOf("\n",o))?ft:(o=Number(a.substring(o,u)),isNaN(o)?dt:(u+=1)+o>a.length?ft:(a=a.slice(u,u+o),s.C=u+o,a))),i==ft){4==t&&(e.o=4,Xe(14),r=!1),$e(e.j,e.m,null,"[Incomplete Response]");break}if(i==dt){e.o=4,Xe(15),$e(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}$e(e.j,e.m,i,null),Et(e,i)}var s,a,o,u;pt(e)&&i!=ft&&i!=dt&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,Xe(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),Pn(t),t.M=!0,Xe(11))):($e(e.j,e.m,n,"[Invalid Chunked Response]"),It(e),bt(e))}function vt(e){e.Y=Date.now()+e.P,wt(e,e.P)}function wt(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=Ze(k(e.lb,e),t)}function _t(e){e.B&&(T.clearTimeout(e.B),e.B=null)}function bt(e){0==e.l.H||e.J||qn(e.l,e)}function It(e){_t(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,Fe(e.V),je(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function Et(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Xt(n.i,e)))if(!e.K&&Xt(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;Un(n),Cn(n)}Fn(n),Xe(18)}}else n.Fa=i[1],0<n.Fa-n.V&&i[2]<37500&&n.G&&0==n.A&&!n.v&&(n.v=Ze(k(n.ib,n),6e3));if(Yt(n.i)<=1&&n.oa){try{n.oa()}catch(e){}n.oa=void 0}}else jn(n,11)}else if(!e.K&&n.g!=e||Un(n),!q(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.V=s[0],s=s[1],2==n.H)if("c"==s[0]){n.K=s[1],n.pa=s[2];var a=s[3];null!=a&&(n.ra=a,n.l.info("VER="+n.ra));var o=s[4];null!=o&&(n.Ga=o,n.l.info("SVER="+n.Ga));var u,c,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.L=r,n.l.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.i).g||-1==m.indexOf("spdy")&&-1==m.indexOf("quic")&&-1==m.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(Jt(u,u.h),u.h=null))),!r.F||(c=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.Da=c,kt(r.I,r.F,c))}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var l,d,f=e;(r=n).wa=$n(r,r.J?r.pa:null,r.Y),f.K?(Zt(r.i,f),l=f,(d=r.L)&&l.setTimeout(d),l.B&&(_t(l),vt(l)),r.g=f):On(r),0<n.j.length&&kn(n)}else"stop"!=s[0]&&"close"!=s[0]||jn(n,7);else 3==n.H&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?jn(n,7):Dn(n):"noop"!=s[0]&&n.h&&n.h.Aa(s),n.A=0)}We()}catch(e){}}function Tt(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.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){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.Z&&"function"==typeof e.Z)return e.Z();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),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(b=ut.prototype).setTimeout=function(e){this.P=e},b.nb=function(e){e=e.target;const t=this.M;t&&3==In(e)?t.l():this.Pa(e)},b.Pa=function(e){try{if(e==this.g)e:{var t=In(this.g),n=this.g.Ia();this.g.da();if(!(t<3)&&(3!=t||H||this.g&&(this.h.h||this.g.ja()||En(this.g)))){this.J||4!=t||7==n||We(),_t(this);var r=this.g.da();this.ca=r;t:if(pt(this)){var i=En(this.g);e="";var s=i.length,a=4==In(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){It(this),bt(this);var o="";break t}this.h.i=new T.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:a&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ja();if(this.i=200==r,l=this.j,d=this.u,f=this.A,g=this.m,m=this.W,p=t,y=r,l.info(function(){return"XMLHTTP RESP ("+g+") [ attempt "+m+"]: "+d+"\n"+f+"\n"+p+" "+y}),this.i){if(this.aa&&!this.K){t:{if(this.g){var u,c=this.g;if((u=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!q(u)){var h=u;break t}}h=null}if(!(r=h)){this.i=!1,this.o=3,Xe(12),It(this),bt(this);break e}$e(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Et(this,r)}this.S?(yt(this,t,o),H&&this.i&&3==t&&(Be(this.U,this.V,"tick",this.mb),this.V.start())):($e(this.j,this.m,o,null),Et(this,o)),4==t&&It(this),this.i&&!this.J&&(4==t?qn(this.l,this):(this.i=!1,vt(this)))}else(function(e){const t={};e=(e.g&&2<=In(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!q(e[i])){var n=function(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}(e[i]),r=n[0];if("string"==typeof(n=n[1])){n=n.trim();const s=t[r]||[];t[r]=s,s.push(n)}}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==r&&0<o.indexOf("Unknown SID")?(this.o=3,Xe(12)):(this.o=0,Xe(13)),It(this),bt(this)}}}catch(e){}var l,d,f,g,m,p,y},b.mb=function(){var e,t;this.g&&(e=In(this.g),t=this.g.ja(),this.C<t.length&&(_t(this),yt(this,e,t),this.i&&4!=e&&vt(this)))},b.cancel=function(){this.J=!0,It(this)},b.lb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(We(),Xe(17)),It(this),this.o=2,bt(this)):wt(this,this.Y-n)};var St=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function xt(e){var t,n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof xt?(this.h=e.h,Dt(this,e.j),this.s=e.s,this.g=e.g,Ct(this,e.m),this.l=e.l,t=e.i,(n=new Bt).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Nt(this,n),this.o=e.o):e&&(t=String(e).match(St))?(this.h=!1,Dt(this,t[1]||"",!0),this.s=Mt(t[2]||""),this.g=Mt(t[3]||"",!0),Ct(this,t[4]),this.l=Mt(t[5]||"",!0),Nt(this,t[6]||"",!0),this.o=Mt(t[7]||"")):(this.h=!1,this.i=new Bt(null,this.h))}function At(e){return new xt(e)}function Dt(e,t,n){e.j=n?Mt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Ct(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 Nt(e,t,n){var r,i;t instanceof Bt?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(jt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(Gt(this,t),zt(this,n,e))},r)),r.j=i):(n||(t=Lt(t,Ut)),e.i=new Bt(t,e.h))}function kt(e,t,n){e.i.set(t,n)}function Rt(e){return kt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Mt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Lt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Ot),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Ot(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}xt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Lt(t,Ft,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Lt(t,Ft,!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(Lt(n,"/"==n.charAt(0)?Vt:Pt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Lt(n,qt)),e.join("")};var Ft=/[#\/\?@]/g,Pt=/[#\?:]/g,Vt=/[#\?]/g,Ut=/[#\?@]/g,qt=/#/g;function Bt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function jt(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,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function Gt(e,t){jt(e),t=Kt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function $t(e,t){return jt(e),t=Kt(e,t),e.g.has(t)}function zt(e,t,n){Gt(e,t),0<n.length&&(e.i=null,e.g.set(Kt(e,t),F(n)),e.h+=n.length)}function Kt(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(b=Bt.prototype).add=function(e,t){jt(this),this.i=null,e=Kt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},b.forEach=function(n,r){jt(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},b.ta=function(){jt(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},b.Z=function(t){jt(this);let n=[];if("string"==typeof t)$t(this,t)&&(n=n.concat(this.g.get(Kt(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},b.set=function(e,t){return jt(this),this.i=null,$t(this,e=Kt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},b.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},b.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],i=encodeURIComponent(String(r)),s=this.Z(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")};var Qt=class{constructor(e,t){this.g=e,this.map=t}};function Ht(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.Ka&&T.g.Ka()&&T.g.Ka().ec),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Wt(e){return e.h||e.g&&e.g.size>=e.j}function Yt(e){return e.h?1:e.g?e.g.size:0}function Xt(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Jt(e,t){e.g?e.g.add(t):e.h=t}function Zt(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function en(t){if(null!=t.h)return t.i.concat(t.h.F);if(null==t.g||0===t.g.size)return F(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.F);return e}}Ht.prototype.cancel=function(){if(this.i=en(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()}};var tn,nn=class{stringify(e){return T.JSON.stringify(e,void 0)}parse(e){return T.JSON.parse(e,void 0)}};function rn(){this.g=new nn}function sn(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function an(e){this.l=e.fc||null,this.j=e.ob||!1}function on(e,t){Te.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=un,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}M(an,nt),an.prototype.g=function(){return new on(this.l,this.j)},an.prototype.i=(tn={},function(){return tn}),M(on,Te);var un=0;function cn(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function hn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,ln(e)}function ln(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(b=on.prototype).open=function(e,t){if(this.readyState!=un)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,ln(this)},b.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.F||T).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},b.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,hn(this)),this.readyState=un},b.$a=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,ln(this)),this.g&&(this.readyState=3,ln(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.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;cn(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},b.Xa=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?hn:ln)(this),3==this.readyState&&cn(this))},b.Za=function(e){this.g&&(this.response=this.responseText=e,hn(this))},b.Ya=function(e){this.g&&(this.response=e,hn(this))},b.ka=function(){this.g&&hn(this)},b.setRequestHeader=function(e,t){this.v.append(e,t)},b.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},b.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(on.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var dn=T.JSON.parse;function fn(e){Te.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=gn,this.L=this.M=!1}M(fn,Te);var gn="",mn=/^https?$/i,pn=["POST","PUT"];function yn(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,vn(e),_n(e)}function vn(e){e.F||(e.F=!0,Se(e,"complete"),Se(e,"error"))}function wn(e){if(e.h&&void 0!==E&&(!e.C[1]||4!=In(e)||2!=e.da()))if(e.v&&4==In(e))Pe(e.La,0,e);else if(Se(e,"readystatechange"),4==In(e)){e.h=!1;try{var t,n,r,i=e.da();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break e;default:s=!1}if((t=s)||((n=0===i)&&(!(r=String(e.I).match(St)[1]||null)&&T.self&&T.self.location&&(r=T.self.location.protocol.slice(0,-1)),n=!mn.test(r?r.toLowerCase():"")),t=n),t)Se(e,"complete"),Se(e,"success");else{e.m=6;try{var a=2<In(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.da()+"]",vn(e)}}finally{_n(e)}}}function _n(e,t){if(e.g){bn(e);const n=e.g,r=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||Se(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function bn(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(T.clearTimeout(e.A),e.A=null)}function In(e){return e.g?e.g.readyState:0}function En(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case gn:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Tn(e){let n="";return oe(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Sn(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Tn(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):kt(e,t,n))}function xn(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function An(e){this.Ga=0,this.j=[],this.l=new Ge,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=xn("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=xn("baseRetryDelayMs",5e3,e),this.hb=xn("retryDelaySeedMs",1e4,e),this.eb=xn("forwardChannelMaxRetries",2,e),this.xa=xn("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.dc||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Ht(e&&e.concurrentRequestLimit),this.Ja=new rn,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function Dn(e){if(Nn(e),3==e.H){var t=e.W++,n=At(e.I);if(kt(n,"SID",e.K),kt(n,"RID",t),kt(n,"TYPE","terminate"),Mn(e,n),(t=new ut(e,e.l,t)).L=2,t.v=Rt(At(n)),n=!1,T.navigator&&T.navigator.sendBeacon)try{n=T.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&T.Image&&((new Image).src=t.v,n=!0),n||(t.g=zn(t.l,null),t.g.ha(t.v)),t.G=Date.now(),vt(t)}Gn(e)}function Cn(e){e.g&&(Pn(e),e.g.cancel(),e.g=null)}function Nn(e){Cn(e),e.u&&(T.clearTimeout(e.u),e.u=null),Un(e),e.i.cancel(),e.m&&("number"==typeof e.m&&T.clearTimeout(e.m),e.m=null)}function kn(e){var t;Wt(e.i)||e.m||(e.m=!0,t=e.Na,Ne||Me(),ke||(Ne(),ke=!0),Re.add(t,e),e.C=0)}function Rn(e,t){var n=t?t.m:e.W++,r=At(e.I);kt(r,"SID",e.K),kt(r,"RID",n),kt(r,"AID",e.V),Mn(e,r),e.o&&e.s&&Sn(r,e.o,e.s),n=new ut(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=Ln(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),Jt(e.i,n),gt(n,r,t)}function Mn(e,n){e.na&&oe(e.na,function(e,t){kt(n,t,e)}),e.h&&Tt({},function(e,t){kt(n,t,e)})}function Ln(e,t,r){r=Math.min(e.j.length,r);var i=e.h?k(e.h.Va,e.h,e):null;e:{var s=e.j;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=s[0].g,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].g,o=s[t].map;if((a-=n)<0)n=Math.max(0,s[t].g-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Tt(e,function(e,t){let n=e;x(e)&&(n=Ae(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,u,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=u.join("&");break e}}}return e=e.j.splice(0,r),t.F=e,i}function On(e){var t;e.g||e.u||(e.ba=1,t=e.Ma,Ne||Me(),ke||(Ne(),ke=!0),Re.add(t,e),e.A=0)}function Fn(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=Ze(k(e.Ma,e),Bn(e,e.A)),e.A++,1)}function Pn(e){null!=e.B&&(T.clearTimeout(e.B),e.B=null)}function Vn(e){e.g=new ut(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=At(e.wa);kt(t,"RID","rpc"),kt(t,"SID",e.K),kt(t,"AID",e.V),kt(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&kt(t,"TO",e.qa),kt(t,"TYPE","xmlhttp"),Mn(e,t),e.o&&e.s&&Sn(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=Rt(At(t)),n.s=null,n.S=!0,mt(n,e)}function Un(e){null!=e.v&&(T.clearTimeout(e.v),e.v=null)}function qn(e,t){var n,r,i,s=null;if(e.g==t){Un(e),Pn(e),e.g=null;var a=2}else{if(!Xt(e.i,t))return;s=t.F,Zt(e.i,t),a=1}if(0!=e.H)if(t.i)1==a?(s=t.s?t.s.length:0,t=Date.now()-t.G,n=e.C,Se(a=Qe(),new Je(a,s)),kn(e)):On(e);else if(3==(n=t.o)||0==n&&0<t.ca||(1!=a||(i=t,Yt((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.j=i.F.concat(r.j),0):1==r.H||2==r.H||r.C>=(r.cb?0:r.eb)||(r.m=Ze(k(r.Na,r,i),Bn(r,r.C)),r.C++,0))))&&(2!=a||!Fn(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:jn(e,5);break;case 4:jn(e,10);break;case 3:jn(e,6);break;default:jn(e,2)}}function Bn(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function jn(e,t){var n,r;e.l.info("Error code "+t),2==t?(n=null,e.h&&(n=null),r=k(e.pb,e),n||(n=new xt("//www.google.com/images/cleardot.gif"),T.location&&"http"==T.location.protocol||Dt(n,"https"),Rt(n)),function(e,t){var n=new Ge;if(T.Image){const r=new Image;r.onload=R(sn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=R(sn,n,r,"TestLoadImage: error",!1,t),r.onabort=R(sn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=R(sn,n,r,"TestLoadImage: timeout",!1,t),T.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):Xe(2),e.H=0,e.h&&e.h.za(t),Gn(e),Nn(e)}function Gn(e){var t;e.H=0,e.ma=[],e.h&&(0==(t=en(e.i)).length&&0==e.j.length||(P(e.ma,t),P(e.ma,e.j),e.i.i.length=0,F(e.j),e.j.length=0),e.h.ya())}function $n(e,t,n){var r,i,s=n instanceof xt?At(n):new xt(n);return""!=s.g?(t&&(s.g=t+"."+s.g),Ct(s,s.m)):(s=(r=T.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new xt(null),s&&Dt(i,s),t&&(i.g=t),r&&Ct(i,r),n&&(i.l=n),s=i),n=e.F,t=e.Da,n&&t&&kt(s,n,t),kt(s,"VER",e.ra),Mn(e,s),s}function zn(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new fn(new an({ob:!0})):new fn(e.va)).Oa(e.J),t}function Kn(){}function Qn(){if(K&&!(10<=Number(ee)))throw Error("Environmental error: no available transport.")}function Hn(e,t){Te.call(this),this.g=new An(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.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!q(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!q(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Xn(this)}function Wn(e){st.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);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 Yn(){at.call(this),this.status=1}function Xn(e){this.g=e}function Jn(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function Zn(e,t,n){n=n||0;var r=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;i<16;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1];var i=e.g[2],s=e.g[3],a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+((a=t+(s^n&(i^s))+r[0]+3614090360&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function er(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(b=fn.prototype).Oa=function(e){this.M=e},b.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=(this.u||ht).g(),this.C=this.u?rt(this.u):rt(ht),this.g.onreadystatechange=k(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void yn(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);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()),i=T.FormData&&e instanceof T.FormData,0<=O(pn,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{bn(this),0<this.B&&((this.L=(o=this.g,K&&"number"==typeof o.timeout&&void 0!==o.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=k(this.ua,this)):this.A=Pe(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){yn(this,e)}var o},b.ua=function(){void 0!==E&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Se(this,"timeout"),this.abort(8))},b.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Se(this,"complete"),Se(this,"abort"),_n(this))},b.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),_n(this,!0)),fn.$.N.call(this)},b.La=function(){this.s||(this.G||this.v||this.l?wn(this):this.kb())},b.kb=function(){wn(this)},b.isActive=function(){return!!this.g},b.da=function(){try{return 2<In(this)?this.g.status:-1}catch(e){return-1}},b.ja=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},b.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),dn(t)}},b.Ia=function(){return this.m},b.Sa=function(){return"string"==typeof this.j?this.j:String(this.j)},(b=An.prototype).ra=8,b.H=1,b.Na=function(t){if(this.m)if(this.m=null,1==this.H){if(!t){this.W=Math.floor(1e5*Math.random()),t=this.W++;const s=new ut(this,this.l,t);let e=this.s;if(this.U&&(e?(e=ue(e),he(e,this.U)):e=this.U),null!==this.o||this.O||(s.I=e,e=null),this.P)e:{for(var n=0,r=0;r<this.j.length;r++){var i=this.j[r];if("__data__"in i.map&&"string"==typeof(i=i.map.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.j.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Ln(this,s,n),kt(r=At(this.I),"RID",t),kt(r,"CVER",22),this.F&&kt(r,"X-HTTP-Session-Id",this.F),Mn(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(Tn(e)))+"&"+n:this.o&&Sn(r,this.o,e)),Jt(this.i,s),this.bb&&kt(r,"TYPE","init"),this.P?(kt(r,"$req",n),kt(r,"SID","null"),s.aa=!0,gt(s,r,null)):gt(s,r,n),this.H=2}}else 3==this.H&&(t?Rn(this,t):0==this.j.length||Wt(this.i)||Rn(this))},b.Ma=function(){var e;this.u=null,Vn(this),this.ca&&!(this.M||null==this.g||this.S<=0)&&(e=2*this.S,this.l.info("BP detection timer enabled: "+e),this.B=Ze(k(this.jb,this),e))},b.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,Xe(10),Cn(this),Vn(this))},b.ib=function(){null!=this.v&&(this.v=null,Cn(this),Fn(this),Xe(19))},b.pb=function(e){e?(this.l.info("Successfully pinged google.com"),Xe(2)):(this.l.info("Failed to ping google.com"),Xe(1))},b.isActive=function(){return!!this.h&&this.h.isActive(this)},(b=Kn.prototype).Ba=function(){},b.Aa=function(){},b.za=function(){},b.ya=function(){},b.isActive=function(){return!0},b.Va=function(){},Qn.prototype.g=function(e,t){return new Hn(e,t)},M(Hn,Te),Hn.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;Xe(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=$n(e,null,e.Y),kn(e)},Hn.prototype.close=function(){Dn(this.g)},Hn.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Ae(e),e=t),n.j.push(new Qt(n.fb++,e)),3==n.H&&kn(n)},Hn.prototype.N=function(){this.g.h=null,delete this.j,Dn(this.g),delete this.g,Hn.$.N.call(this)},M(Wn,st),M(Yn,at),M(Xn,Kn),Xn.prototype.Ba=function(){Se(this.g,"a")},Xn.prototype.Aa=function(e){Se(this.g,new Wn(e))},Xn.prototype.za=function(e){Se(this.g,new Yn)},Xn.prototype.ya=function(){Se(this.g,"b")},M(Jn,function(){this.blockSize=-1}),Jn.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Jn.prototype.j=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)Zn(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){Zn(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){Zn(this,r),i=0;break}}this.h=i,this.i+=t},Jn.prototype.l=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var n=8*this.i,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;t<4;++t)for(var r=0;r<32;r+=8)e[n++]=this.g[t]>>>r&255;return e};var tr={};function nr(e){return-128<=e&&e<128?(t=e,n=function(e){return new er([0|e],e<0?-1:0)},r=tr,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new er([0|e],e<0?-1:0);var t,n,r}function rr(e){if(isNaN(e)||!isFinite(e))return sr;if(e<0)return hr(rr(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=ir;return new er(t,0)}var ir=4294967296,sr=nr(0),ar=nr(1),or=nr(16777216);function ur(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function cr(e){return-1==e.h}function hr(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new er(n,~e.h).add(ar)}function lr(e,t){return e.add(hr(t))}function dr(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function fr(e,t){this.g=e,this.h=t}function gr(e,t){if(ur(t))throw Error("division by zero");if(ur(e))return new fr(sr,sr);if(cr(e))return t=gr(hr(e),t),new fr(hr(t.g),hr(t.h));if(cr(t))return t=gr(e,hr(t)),new fr(hr(t.g),t.h);if(30<e.g.length){if(cr(e)||cr(t))throw Error("slowDivide_ only works with positive integers.");for(var n=ar,r=t;r.X(e)<=0;)n=mr(n),r=mr(r);for(var i=pr(n,1),s=pr(r,1),r=pr(r,2),n=pr(n,2);!ur(r);){var a=s.add(r);a.X(e)<=0&&(i=i.add(n),s=a),r=pr(r,1),n=pr(n,1)}return t=lr(e,i.R(t)),new fr(i,t)}for(i=sr;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),a=(s=rr(n)).R(t);cr(a)||0<a.X(e);)a=(s=rr(n-=r)).R(t);ur(s)&&(s=ar),i=i.add(s),e=lr(e,a)}return new fr(i,e)}function mr(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new er(n,e.h)}function pr(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new er(i,e.h)}(b=er.prototype).ea=function(){if(cr(this))return-hr(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:ir+r)*t,t*=ir}return e},b.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(ur(this))return"0";if(cr(this))return"-"+hr(this).toString(e);for(var t=rr(Math.pow(e,6)),n=this,r="";;){var i=gr(n,t).g,s=((0<(n=lr(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(ur(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},b.D=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},b.X=function(e){return cr(e=lr(this,e))?-1:ur(e)?0:1},b.abs=function(){return cr(this)?hr(this):this},b.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),a=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new er(n,-2147483648&n[n.length-1]?-1:0)},b.R=function(e){if(ur(this)||ur(e))return sr;if(cr(this))return cr(e)?hr(this).R(hr(e)):hr(hr(this).R(e));if(cr(e))return hr(this.R(hr(e)));if(this.X(or)<0&&e.X(or)<0)return rr(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,a=65535&this.D(r),o=e.D(i)>>>16,u=65535&e.D(i);n[2*r+2*i]+=a*u,dr(n,2*r+2*i),n[2*r+2*i+1]+=s*u,dr(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,dr(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,dr(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new er(n,0)},b.gb=function(e){return gr(this,e).h},b.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new er(n,this.h&e.h)},b.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new er(n,this.h|e.h)},b.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new er(n,this.h^e.h)},Qn.prototype.createWebChannel=Qn.prototype.g,Hn.prototype.send=Hn.prototype.u,Hn.prototype.open=Hn.prototype.m,et.NO_ERROR=0,et.TIMEOUT=8,et.HTTP_ERROR=6,tt.COMPLETE="complete",(it.EventType=I).OPEN="a",I.CLOSE="b",I.ERROR="c",I.MESSAGE="d",Te.prototype.listen=Te.prototype.O,fn.prototype.listenOnce=fn.prototype.P,fn.prototype.getLastError=fn.prototype.Sa,fn.prototype.getLastErrorCode=fn.prototype.Ia,fn.prototype.getStatus=fn.prototype.da,fn.prototype.getResponseJson=fn.prototype.Wa,fn.prototype.getResponseText=fn.prototype.ja,fn.prototype.send=fn.prototype.ha,fn.prototype.setWithCredentials=fn.prototype.Oa,Jn.prototype.digest=Jn.prototype.l,Jn.prototype.update=Jn.prototype.j,er.prototype.multiply=er.prototype.R,er.prototype.modulo=er.prototype.gb,er.prototype.compare=er.prototype.X,er.prototype.toNumber=er.prototype.ea,er.prototype.getBits=er.prototype.D,er.fromNumber=rr,er.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if((n=n||10)<2||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return hr(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=rr(Math.pow(n,8)),i=sr,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n),i=a<8?(a=rr(Math.pow(n,a)),i.R(a).add(rr(o))):(i=i.R(r)).add(rr(o));return i};var yr,vr=Qe,wr=et,_r=tt,br=ze,Ir=10,Er=11,Tr=it,Sr=fn,xr=Jn,Ar=er;const Dr="@firebase/firestore";class Cr{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}}Cr.UNAUTHENTICATED=new Cr(null),Cr.GOOGLE_CREDENTIALS=new Cr("google-credentials-uid"),Cr.FIRST_PARTY=new Cr("first-party-uid"),Cr.MOCK_USER=new Cr("mock-user");let Nr="10.3.0";const kr=new class{constructor(e){this.name=e,this._logLevel=v,this._logHandler=_,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?y[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 Rr(){return kr.logLevel}function Mr(e,...t){var n;kr.logLevel<=l.DEBUG&&(n=t.map(Fr),kr.debug(`Firestore (${Nr}): ${e}`,...n))}function Lr(e,...t){var n;kr.logLevel<=l.ERROR&&(n=t.map(Fr),kr.error(`Firestore (${Nr}): ${e}`,...n))}function Or(e,...t){var n;kr.logLevel<=l.WARN&&(n=t.map(Fr),kr.warn(`Firestore (${Nr}): ${e}`,...n))}function Fr(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function Pr(e="Unexpected state"){var t=`FIRESTORE (${Nr}) INTERNAL ASSERTION FAILED: `+e;throw Lr(t),new Error(t)}function Vr(e){e||Pr()}const Ur={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 qr extends d{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class Br{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class jr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Gr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Cr.UNAUTHENTICATED))}shutdown(){}}class $r{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 zr{constructor(e){this.t=e,this.currentUser=Cr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new Br;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new Br,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{Mr("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):(Mr("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new Br))},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?(Mr("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Vr("string"==typeof e.accessToken),new jr(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 Vr(null===e||"string"==typeof e),new Cr(e)}}class Kr{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=Cr.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);var e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class Qr{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Kr(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(Cr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Hr{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 Wr{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,n){const r=e=>{null!=e.error&&Mr("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.R;return this.R=e.token,Mr("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{Mr("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):Mr("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Vr("string"==typeof e.token),this.R=e.token,new Hr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Yr{static V(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=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<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function Xr(e,t){return e<t?-1:t<e?1:0}function Jr(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function Zr(e){return e+"\0"}class ei{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new qr(Ur.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new qr(Ur.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new qr(Ur.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new qr(Ur.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return ei.fromMillis(Date.now())}static fromDate(e){return ei.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new ei(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Xr(this.nanoseconds,e.nanoseconds):Xr(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 ti{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ti(e)}static min(){return new ti(new ei(0,0))}static max(){return new ti(new ei(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 ni{constructor(e,t,n){void 0===t?t=0:t>e.length&&Pr(),void 0===n?n=e.length-t:n>e.length-t&&Pr(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===ni.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof ni?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),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class ri extends ni{construct(e,t,n){return new ri(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 qr(Ur.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new ri(t)}static emptyPath(){return new ri([])}}const ii=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class si extends ni{construct(e,t,n){return new si(e,t,n)}static isValidIdentifier(e){return ii.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!si.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new si(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new qr(Ur.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new qr(Ur.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new qr(Ur.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new qr(Ur.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new si(t)}static emptyPath(){return new si([])}}class ai{constructor(e){this.path=e}static fromPath(e){return new ai(ri.fromString(e))}static fromName(e){return new ai(ri.fromString(e).popFirst(5))}static empty(){return new ai(ri.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===ri.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return ri.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ai(new ri(e.slice()))}}class oi{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function ui(e){return e.fields.find(e=>2===e.kind)}function ci(e){return e.fields.filter(e=>2!==e.kind)}oi.UNKNOWN_ID=-1;class hi{constructor(e,t){this.fieldPath=e,this.kind=t}}class li{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new li(0,gi.min())}}function di(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=ti.fromTimestamp(1e9===r?new ei(n+1,0):new ei(n,r));return new gi(r,ai.empty(),t)}function fi(e){return new gi(e.readTime,e.key,-1)}class gi{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new gi(ti.min(),ai.empty(),-1)}static max(){return new gi(ti.max(),ai.empty(),-1)}}function mi(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ai.comparator(e.documentKey,t.documentKey),0!==n?n:Xr(e.largestBatchId,t.largestBatchId))}const pi="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class yi{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function vi(e){if(e.code!==Ur.FAILED_PRECONDITION||e.message!==pi)throw e;Mr("LocalStore","Unexpectedly lost primary lease")}class wi{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,i){return this.callbackAttached&&Pr(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new wi((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof wi?t:wi.resolve(t)}catch(e){return wi.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):wi.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):wi.reject(t)}static resolve(n){return new wi((e,t)=>{e(n)})}static reject(n){return new wi((e,t)=>{t(n)})}static waitFor(e){return new wi((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=wi.resolve(!1);for(const n of e)t=t.next(e=>e?wi.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 wi((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;u(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new wi((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class _i{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.m=new Br,this.transaction.oncomplete=()=>{this.m.resolve()},this.transaction.onabort=()=>{e.error?this.m.reject(new Ei(n,e.error)):this.m.resolve()},this.transaction.onerror=e=>{var t=Di(e.target.error);this.m.reject(new Ei(n,t))}}static open(e,t,n,r){try{return new _i(t,e.transaction(r,n))}catch(e){throw new Ei(t,e)}}get g(){return this.m.promise}abort(e){e&&this.m.reject(e),this.aborted||(Mr("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}p(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Si(t)}}class bi{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===bi.D(u())&&Lr("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 Mr("SimpleDb","Removing database:",e),xi(window.indexedDB.deleteDatabase(e)).toPromise()}static v(){if(!function(){try{return"object"==typeof indexedDB}catch(e){return}}())return!1;if(bi.C())return!0;const e=u(),t=bi.D(e),n=0<t&&t<10,r=bi.F(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static C(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.M)}static O(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 F(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async N(s){return this.db||(Mr("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new Ei(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new qr(Ur.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 qr(Ur.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 Ei(s,t))},i.onupgradeneeded=e=>{Mr("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.B(t,i.transaction,e.oldVersion,this.version).next(()=>{Mr("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.L&&(this.db.onversionchange=e=>this.L(e)),this.db}k(t){this.L=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.N(e);const t=_i.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.p(),e)).catch(e=>(t.abort(e),wi.reject(e))).toPromise();return s.catch(()=>{}),await t.g,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Mr("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 Ii{constructor(e){this.q=e,this.K=!1,this.$=null}get isDone(){return this.K}get U(){return this.$}set cursor(e){this.q=e}done(){this.K=!0}W(e){this.$=e}delete(){return xi(this.q.delete())}}class Ei extends qr{constructor(e,t){super(Ur.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Ti(e){return"IndexedDbTransactionError"===e.name}class Si{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Mr("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Mr("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),xi(n)}add(e){return Mr("SimpleDb","ADD",this.store.name,e,e),xi(this.store.add(e))}get(t){return xi(this.store.get(t)).next(e=>(Mr("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Mr("SimpleDb","DELETE",this.store.name,e),xi(this.store.delete(e))}count(){return Mr("SimpleDb","COUNT",this.store.name),xi(this.store.count())}G(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.j(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new wi((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}H(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new wi((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}J(e,t){Mr("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Y=!1;var r=this.cursor(n);return this.j(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.j(r,t)}X(i){const e=this.cursor({});return new wi((n,r)=>{e.onerror=e=>{var t=Di(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}j(e,s){const a=[];return new wi((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new Ii(t),r=s(t.primaryKey,t.value,n);if(r instanceof wi){const e=r.catch(e=>(n.done(),wi.reject(e)));a.push(e)}n.isDone?i():null===n.U?t.continue():t.continue(n.U)}else i()}}).next(()=>wi.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.Y?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function xi(e){return new wi((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Di(e.target.error);r(t)}})}let Ai=!1;function Di(e){const t=bi.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 qr("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 Ai||(Ai=!0,setTimeout(()=>{throw e},0)),e}}return e}class Ci{constructor(e,t){this.asyncQueue=e,this.ee=t,this.task=null}start(){this.te(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}te(e){Mr("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{Mr("IndexBackiller",`Documents written: ${await this.ee.ne()}`)}catch(e){Ti(e)?Mr("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await vi(e)}await this.te(6e4)})}}class Ni{constructor(e,t){this.localStore=e,this.persistence=t}async ne(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.re(e,t))}re(e,t){const n=new Set;let r=t,i=!0;return wi.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(Mr("IndexBackiller",`Processing collection: ${t}`),this.ie(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}ie(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.se(n,e)).next(e=>(Mr("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}se(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=fi(t);0<mi(n,r)&&(r=n)}),new gi(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ki{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.oe(e),this._e=e=>t.writeSequenceNumber(e))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this._e&&this._e(e),e}}function Ri(e){return null==e}function Mi(e){return 0===e&&1/e==-1/0}function Li(e){return"number"==typeof e&&Number.isInteger(e)&&!Mi(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Oi(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Fi(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Fi(t)}function Fi(e){return e+""}function Pi(t){const n=t.length;if(Vr(2<=n),2===n)return Vr(""===t.charAt(0)&&""===t.charAt(1)),ri.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=n-2,r=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>__PRIVATE_lastReasonableEscapeIndex)&&Pr(),t.charAt(n+1)){case"":var s=t.substring(a,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:Pr()}a=n+2}return new ri(r)}ki.ae=-1;const Vi=["userId","batchId"];function Ui(e,t){return[e,Oi(t)]}function qi(e,t,n){return[e,Oi(t),n]}const Bi={},ji=["prefixPath","collectionGroup","readTime","documentId"],Gi=["prefixPath","collectionGroup","documentId"],$i=["collectionGroup","readTime","prefixPath","documentId"],zi=["canonicalId","targetId"],Ki=["targetId","path"],Qi=["path","targetId"],Hi=["collectionId","parent"],Wi=["indexId","uid"],Yi=["uid","sequenceNumber"],Xi=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Ji=["indexId","uid","orderedDocumentKey"],Zi=["userId","collectionPath","documentId"],es=["userId","collectionPath","largestBatchId"],ts=["userId","collectionGroup","largestBatchId"],ns=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],rs=[...ns,"documentOverlays"],is=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ss=is,as=[...ss,"indexConfiguration","indexState","indexEntries"];class os extends yi{constructor(e,t){super(),this.ue=e,this.currentSequenceNumber=t}}function us(e,t){var n=e;return bi.O(n.ue,t)}function cs(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function hs(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function ls(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ds{constructor(e,t){this.comparator=e,this.root=t||gs.EMPTY}insert(e,t){return new ds(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,gs.BLACK,null,null))}remove(e){return new ds(this.comparator,this.root.remove(e,this.comparator).copy(null,null,gs.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 fs(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new fs(this.root,e,this.comparator,!1)}getReverseIterator(){return new fs(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new fs(this.root,e,this.comparator,!0)}}class fs{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}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 gs{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:gs.RED,this.left=null!=r?r:gs.EMPTY,this.right=null!=i?i:gs.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new gs(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i: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 i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return gs.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 gs.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,gs.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,gs.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 Pr();if(this.right.isRed())throw Pr();var e=this.left.check();if(e!==this.right.check())throw Pr();return e+(this.isRed()?0:1)}}gs.EMPTY=null,gs.RED=!0,gs.BLACK=!1,gs.EMPTY=new class{constructor(){this.size=0}get key(){throw Pr()}get value(){throw Pr()}get color(){throw Pr()}get left(){throw Pr()}get right(){throw Pr()}copy(e,t,n,r,i){return this}insert(e,t,n){return new gs(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 ms{constructor(e){this.comparator=e,this.data=new ds(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 ps(this.data.getIterator())}getIteratorFrom(e){return new ps(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 ms))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 ms(this.comparator);return t.data=e,t}}class ps{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function ys(e){return e.hasNext()?e.getNext():void 0}class vs{constructor(e){(this.fields=e).sort(si.comparator)}static empty(){return new vs([])}unionWith(e){let t=new ms(si.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new vs(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Jr(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class ws extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class _s{constructor(e){this.binaryString=e}static fromBase64String(e){var t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new ws("Invalid base64 string: "+e):e}}(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 Xr(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}_s.EMPTY_BYTE_STRING=new _s("");const bs=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Is(t){if(Vr(!!t),"string"!=typeof t)return{seconds:Es(t.seconds),nanos:Es(t.nanos)};{let e=0;var n=bs.exec(t);Vr(!!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 Es(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ts(e){return"string"==typeof e?_s.fromBase64String(e):_s.fromUint8Array(e)}function Ss(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 xs(e){var t=e.mapValue.fields.__previous_value__;return Ss(t)?xs(t):t}function As(e){var t=Is(e.mapValue.fields.__local_write_time__.timestampValue);return new ei(t.seconds,t.nanos)}class Ds{constructor(e,t,n,r,i,s,a,o,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=u}}class Cs{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Cs("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Cs&&e.projectId===this.projectId&&e.database===this.database}}const Ns={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},ks={nullValue:"NULL_VALUE"};function Rs(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?Ss(e)?4:zs(e)?9007199254740991:10:Pr()}function Ms(e,t){if(e===t)return!0;var n,r,i=Rs(e);if(i!==Rs(t))return!1;switch(i){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return As(e).isEqual(As(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;var n=Is(e.timestampValue),r=Is(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return r=t,Ts(e.bytesValue).isEqual(Ts(r.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return n=t,Es((r=e).geoPointValue.latitude)===Es(n.geoPointValue.latitude)&&Es(r.geoPointValue.longitude)===Es(n.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Es(e.integerValue)===Es(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Es(e.doubleValue),r=Es(t.doubleValue);return n===r?Mi(n)===Mi(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return Jr(e.arrayValue.values||[],t.arrayValue.values||[],Ms);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(cs(n)!==cs(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Ms(n[e],r[e])))return!1;return!0}(e,t);default:return Pr()}}function Ls(e,t){return void 0!==(e.values||[]).find(e=>Ms(e,t))}function Os(e,t){if(e===t)return 0;var n,r,i,s,a=Rs(e),o=Rs(t);if(a!==o)return Xr(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Xr(e.booleanValue,t.booleanValue);case 2:return r=t,i=Es((n=e).integerValue||n.doubleValue),s=Es(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Fs(e.timestampValue,t.timestampValue);case 4:return Fs(As(e),As(t));case 5:return Xr(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ts(e),r=Ts(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=Xr(n[i],r[i]);if(0!==t)return t}return Xr(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=Xr(Es(n.latitude),Es(r.latitude)))?s:Xr(Es(n.longitude),Es(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Os(n[i],r[i]);if(t)return t}return Xr(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Ns.mapValue&&t===Ns.mapValue)return 0;if(e===Ns.mapValue)return 1;if(t===Ns.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=Xr(r[o],s[o]);if(0!==t)return t;var a=Os(n[r[o]],i[s[o]]);if(0!==a)return a}return Xr(r.length,s.length)}(e.mapValue,t.mapValue);default:throw Pr()}}function Fs(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Xr(e,t);var n=Is(e),r=Is(t),i=Xr(n.seconds,r.seconds);return 0!==i?i:Xr(n.nanos,r.nanos)}function Ps(e){return function s(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=Is(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return Ts(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return ai.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):Pr()}(e)}function Vs(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Us(e){return!!e&&"integerValue"in e}function qs(e){return!!e&&"arrayValue"in e}function Bs(e){return e&&"nullValue"in e}function js(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Gs(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 hs(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 zs(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Ks(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 Qs(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){this.value=e}static empty(){return new Hs({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)],!Gs(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=si.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=$s(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());Gs(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)];Gs(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){hs(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Hs($s(this.value))}}class Ws{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Ws(e,0,ti.min(),ti.min(),ti.min(),Hs.empty(),0)}static newFoundDocument(e,t,n,r){return new Ws(e,1,t,ti.min(),n,r,0)}static newNoDocument(e,t){return new Ws(e,2,t,ti.min(),ti.min(),Hs.empty(),0)}static newUnknownDocument(e,t){return new Ws(e,3,t,ti.min(),ti.min(),Hs.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(ti.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=Hs.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Hs.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ti.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 Ws&&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 Ws(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 Ys{constructor(e,t){this.position=e,this.inclusive=t}}function Xs(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?ai.comparator(ai.fromName(a.referenceValue),n.key):Os(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Js(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 Zs{constructor(e,t="asc"){this.field=e,this.dir=t}}class ea{}class ta extends ea{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 ca(e,t,n):"array-contains"===t?new fa(e,n):"in"===t?new ga(e,n):"not-in"===t?new ma(e,n):"array-contains-any"===t?new pa(e,n):new ta(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?ha:la)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Os(t,this.value)):null!==t&&Rs(this.value)===Rs(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 Pr()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class na extends ea{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new na(e,t)}matches(t){return ra(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ce||(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){var e=this.le(e=>e.isInequality());return null!==e?e.field:null}le(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function ra(e){return"and"===e.op}function ia(e){return"or"===e.op}function sa(e){return aa(e)&&ra(e)}function aa(e){for(const t of e.filters)if(t instanceof na)return!1;return!0}function oa(e,t){var n=e.filters.concat(t);return na.create(n,e.op)}function ua(e){return e instanceof ta?`${(t=e).field.canonicalString()} ${t.op} ${Ps(t.value)}`:e instanceof na?(e=e).op.toString()+" {"+e.getFilters().map(ua).join(" ,")+"}":"Filter";var t}class ca extends ta{constructor(e,t,n){super(e,t,n),this.key=ai.fromName(n.referenceValue)}matches(e){var t=ai.comparator(e.key,this.key);return this.matchesComparison(t)}}class ha extends ta{constructor(e,t){super(e,"in",t),this.keys=da(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class la extends ta{constructor(e,t){super(e,"not-in",t),this.keys=da(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function da(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ai.fromName(e.referenceValue))}class fa extends ta{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return qs(t)&&Ls(t.arrayValue,this.value)}}class ga extends ta{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Ls(this.value.arrayValue,t)}}class ma extends ta{constructor(e,t){super(e,"not-in",t)}matches(e){if(Ls(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Ls(this.value.arrayValue,t)}}class pa extends ta{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!qs(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Ls(this.value.arrayValue,e))}}class ya{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.he=null}}function va(e,t=null,n=[],r=[],i=null,s=null,a=null){return new ya(e,t,n,r,i,s,a)}function wa(e){const t=e;if(null===t.he){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 ta)return e.field.canonicalString()+e.op.toString()+Ps(e.value);if(sa(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(","),Ri(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.he=e}return t.he}function _a(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(n=e.orderBy[i],r=t.orderBy[i],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 s=0;s<e.filters.length;s++)if(!function r(e,t){return e instanceof ta?(n=e,(s=t)instanceof ta&&n.op===s.op&&n.field.isEqual(s.field)&&Ms(n.value,s.value)):e instanceof na?(i=t)instanceof na&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void Pr();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Js(e.startAt,t.startAt)&&Js(e.endAt,t.endAt)}function ba(e){return ai.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Ia(e,t){return e.filters.filter(e=>e instanceof ta&&e.field.isEqual(t))}function Ea(t,n,r){let i=ks,s=!0;for(const r of Ia(t,n)){let e=ks,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?ks:"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?Vs(Cs.empty(),ai.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:Pr();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=ks}Ks({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=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];Ks({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function Ta(t,n,r){let i=Ns,s=!0;for(const r of Ia(t,n)){let e=Ns,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?Vs(Cs.empty(),ai.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Ns:Pr(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Ns}0<Qs({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=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<Qs({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class Sa{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Pe=null,this.Ie=null,this.Te=null,this.startAt,this.endAt}}function xa(e,t,n,r,i,s,a,o){return new Sa(e,t,n,r,i,s,a,o)}function Aa(e){return new Sa(e)}function Da(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 Ca(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Na(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function ka(e){return null!==e.collectionGroup}function Ra(t){const n=t;if(null===n.Pe){n.Pe=[];const t=Na(n),e=Ca(n);if(null!==t&&null===e)t.isKeyField()||n.Pe.push(new Zs(t)),n.Pe.push(new Zs(si.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.Pe.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.Pe.push(new Zs(si.keyField(),t))}}}return n.Pe}function Ma(e){const t=e;return t.Ie||(t.Ie=function(e,t){if("F"===e.limitType)return va(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new Zs(e.field,t)});var n=e.endAt?new Ys(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Ys(e.startAt.position,e.startAt.inclusive):null;return va(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,Ra(e))),t.Ie}function La(e,t){t.getFirstInequalityField(),Na(e);var n=e.filters.concat([t]);return new Sa(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Oa(e,t,n){return new Sa(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Fa(e,t){return _a(Ma(e),Ma(t))&&e.limitType===t.limitType}function Pa(e){return`${wa(Ma(e))}|lt:${e.limitType}`}function Va(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=>ua(e)).join(", ")}]`),Ri(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})`}(Ma(e))}; limitType=${e.limitType})`}function Ua(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):ai.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of Ra(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return;return 1}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return;return 1}(e,t)&&(i=t,(!(t=e).startAt||(n=t.startAt,e=Ra(t),r=Xs(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=Ra(t),r=Xs(n,t,i),n.inclusive?0<=r:0<r)));var n,r,i,s,a}function qa(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Ba(i){return(e,t)=>{let n=!1;for(const r of Ra(i)){const i=function(e,t,n){var r=e.field.isKeyField()?ai.comparator(t.key,n.key):function(e,t,n){var r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Os(r,i):Pr()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Pr()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class ja{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 i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[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){hs(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return ls(this.inner)}size(){return this.innerSize}}const Ga=new ds(ai.comparator);const $a=new ds(ai.comparator);function za(...e){let t=$a;for(const n of e)t=t.insert(n.key,n);return t}function Ka(e){let n=$a;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function Qa(){return new ja(e=>e.toString(),(e,t)=>e.isEqual(t))}const Ha=new ds(ai.comparator),Wa=new ms(ai.comparator);function Ya(...e){let t=Wa;for(const n of e)t=t.add(n);return t}const Xa=new ms(Xr);function Ja(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Mi(t)?"-0":t}}function Za(e){return{integerValue:""+e}}function eo(e,t){return Li(t)?Za(t):Ja(e,t)}class to{constructor(){this._=void 0}}function no(e,t){return e instanceof uo?Us(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class ro extends to{}class io extends to{constructor(e){super(),this.elements=e}}function so(e,t){const n=ho(t);for(const t of e.elements)n.some(e=>Ms(e,t))||n.push(t);return{arrayValue:{values:n}}}class ao extends to{constructor(e){super(),this.elements=e}}function oo(e,t){let n=ho(t);for(const t of e.elements)n=n.filter(e=>!Ms(e,t));return{arrayValue:{values:n}}}class uo extends to{constructor(e,t){super(),this.serializer=e,this.Ee=t}}function co(e){return Es(e.integerValue||e.doubleValue)}function ho(e){return qs(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class lo{constructor(e,t){this.field=e,this.transform=t}}class fo{constructor(e,t){this.version=e,this.transformResults=t}}class go{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new go}static exists(e){return new go(void 0,e)}static updateTime(e){return new go(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 mo(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class po{}function yo(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new xo(e.key,go.none()):new bo(e.key,e.data,go.none());{const i=e.data,s=Hs.empty();let t=new ms(si.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new Io(e.key,s,new vs(t.toArray()),go.none())}}function vo(e,t,n){e instanceof bo?function(e,t,n){const r=e.value.clone(),i=To(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Io?function(e,t,n){if(!mo(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=To(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Eo(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function wo(e,t,n,r){return e instanceof bo?function(e,t,n,r){if(!mo(e.precondition,t))return n;const i=e.value.clone(),s=So(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof Io?function(e,t,n,r){if(!mo(e.precondition,t))return n;const i=So(e.fieldTransforms,r,t),s=t.data;return s.setAll(Eo(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,mo(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function _o(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&&Jr(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof io&&t instanceof io||e instanceof ao&&t instanceof ao?Jr(e.elements,t.elements,Ms):e instanceof uo&&t instanceof uo?Ms(e.Ee,t.Ee):e instanceof ro&&t instanceof ro)}(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 bo extends po{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 Io extends po{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Eo(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 To(e,t,n){const r=new Map;Vr(e.length===n.length);for(let h=0;h<n.length;h++){var i=e[h],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,u=a,c=n[h],o instanceof io?so(o,u):o instanceof ao?oo(o,u):c))}var o,u,c;return r}function So(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,(i=e,s=h,a=t,u=o=void 0,i instanceof ro?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return(t=t&&Ss(t)?xs(t):t)&&(n.fields.__previous_value__=t),{mapValue:n}}(a,s):i instanceof io?so(i,s):i instanceof ao?oo(i,s):(o=no(i=i,s),u=co(o)+co(i.Ee),Us(o)&&Us(i.Ee)?Za(u):Ja(i.serializer,u))))}var i,s,a,o,u;return r}class xo extends po{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Ao extends po{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Do{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 i=this.mutations[r];i.key.isEqual(e.key)&&vo(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=wo(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=wo(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=Qa();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=yo(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(ti.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Ya())}isEqual(e){return this.batchId===e.batchId&&Jr(this.mutations,e.mutations,(e,t)=>_o(e,t))&&Jr(this.baseMutations,e.baseMutations,(e,t)=>_o(e,t))}}class Co{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Vr(e.mutations.length===n.length);let r=Ha;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new Co(e,t,n,r)}}class No{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 ko{constructor(e,t){this.count=e,this.unchangedNames=t}}function Ro(e){switch(e){default:return Pr();case Ur.CANCELLED:case Ur.UNKNOWN:case Ur.DEADLINE_EXCEEDED:case Ur.RESOURCE_EXHAUSTED:case Ur.INTERNAL:case Ur.UNAVAILABLE:case Ur.UNAUTHENTICATED:return!1;case Ur.INVALID_ARGUMENT:case Ur.NOT_FOUND:case Ur.ALREADY_EXISTS:case Ur.PERMISSION_DENIED:case Ur.FAILED_PRECONDITION:case Ur.ABORTED:case Ur.OUT_OF_RANGE:case Ur.UNIMPLEMENTED:case Ur.DATA_LOSS:return!0}}function Mo(e){if(void 0===e)return Lr("GRPC error has no .code"),Ur.UNKNOWN;switch(e){case yr.OK:return Ur.OK;case yr.CANCELLED:return Ur.CANCELLED;case yr.UNKNOWN:return Ur.UNKNOWN;case yr.DEADLINE_EXCEEDED:return Ur.DEADLINE_EXCEEDED;case yr.RESOURCE_EXHAUSTED:return Ur.RESOURCE_EXHAUSTED;case yr.INTERNAL:return Ur.INTERNAL;case yr.UNAVAILABLE:return Ur.UNAVAILABLE;case yr.UNAUTHENTICATED:return Ur.UNAUTHENTICATED;case yr.INVALID_ARGUMENT:return Ur.INVALID_ARGUMENT;case yr.NOT_FOUND:return Ur.NOT_FOUND;case yr.ALREADY_EXISTS:return Ur.ALREADY_EXISTS;case yr.PERMISSION_DENIED:return Ur.PERMISSION_DENIED;case yr.FAILED_PRECONDITION:return Ur.FAILED_PRECONDITION;case yr.ABORTED:return Ur.ABORTED;case yr.OUT_OF_RANGE:return Ur.OUT_OF_RANGE;case yr.UNIMPLEMENTED:return Ur.UNIMPLEMENTED;case yr.DATA_LOSS:return Ur.DATA_LOSS;default:return Pr()}}function Lo(){return new TextEncoder}(tt=yr=yr||{})[tt.OK=0]="OK",tt[tt.CANCELLED=1]="CANCELLED",tt[tt.UNKNOWN=2]="UNKNOWN",tt[tt.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",tt[tt.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",tt[tt.NOT_FOUND=5]="NOT_FOUND",tt[tt.ALREADY_EXISTS=6]="ALREADY_EXISTS",tt[tt.PERMISSION_DENIED=7]="PERMISSION_DENIED",tt[tt.UNAUTHENTICATED=16]="UNAUTHENTICATED",tt[tt.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",tt[tt.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",tt[tt.ABORTED=10]="ABORTED",tt[tt.OUT_OF_RANGE=11]="OUT_OF_RANGE",tt[tt.UNIMPLEMENTED=12]="UNIMPLEMENTED",tt[tt.INTERNAL=13]="INTERNAL",tt[tt.UNAVAILABLE=14]="UNAVAILABLE",tt[tt.DATA_LOSS=15]="DATA_LOSS";const Oo=new Ar([4294967295,4294967295],0);function Fo(e){const t=Lo().encode(e),n=new xr;return n.update(t),new Uint8Array(n.digest())}function Po(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new Ar([n,r],0),new Ar([i,s],0)]}class Vo{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new Uo(`Invalid padding: ${t}`);if(n<0)throw new Uo(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new Uo(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Uo(`Invalid padding when bitmap length is 0: ${t}`);this.Ae=8*e.length-t,this.Re=Ar.fromNumber(this.Ae)}Ve(e,t,n){let r=e.add(t.multiply(Ar.fromNumber(n)));return 1===r.compare(Oo)&&(r=new Ar([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Re).toNumber()}me(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ae)return!1;const t=Fo(e),[n,r]=Po(t);for(let i=0;i<this.hashCount;i++){const t=this.Ve(n,r,i);if(!this.me(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new Vo(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.Ae){const n=Fo(t),[r,i]=Po(n);for(let e=0;e<this.hashCount;e++){const n=this.Ve(r,i,e);this.fe(n)}}}fe(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class Uo extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class qo{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,Bo.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new qo(ti.min(),r,new ds(Xr),Ga,Ya())}}class Bo{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new Bo(n,t,Ya(),Ya(),Ya())}}class jo{constructor(e,t,n,r){this.ge=e,this.removedTargetIds=t,this.key=n,this.pe=r}}class Go{constructor(e,t){this.targetId=e,this.ye=t}}class $o{constructor(e,t,n=_s.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class zo{constructor(){this.we=0,this.Se=Ho(),this.be=_s.EMPTY_BYTE_STRING,this.De=!1,this.ve=!0}get current(){return this.De}get resumeToken(){return this.be}get Ce(){return 0!==this.we}get Fe(){return this.ve}Me(e){0<e.approximateByteSize()&&(this.ve=!0,this.be=e)}xe(){let n=Ya(),r=Ya(),i=Ya();return this.Se.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:Pr()}}),new Bo(this.be,this.De,n,r,i)}Oe(){this.ve=!1,this.Se=Ho()}Ne(e,t){this.ve=!0,this.Se=this.Se.insert(e,t)}Be(e){this.ve=!0,this.Se=this.Se.remove(e)}Le(){this.we+=1}ke(){--this.we}qe(){this.ve=!0,this.De=!0}}class Ko{constructor(e){this.Qe=e,this.Ke=new Map,this.$e=Ga,this.Ue=Qo(),this.We=new ds(Xr)}Ge(e){for(const t of e.ge)e.pe&&e.pe.isFoundDocument()?this.ze(t,e.pe):this.je(t,e.key,e.pe);for(const n of e.removedTargetIds)this.je(n,e.key,e.pe)}He(n){this.forEachTarget(n,e=>{const t=this.Je(e);switch(n.state){case 0:this.Ye(e)&&t.Me(n.resumeToken);break;case 1:t.ke(),t.Ce||t.Oe(),t.Me(n.resumeToken);break;case 2:t.ke(),t.Ce||this.removeTarget(e);break;case 3:this.Ye(e)&&(t.qe(),t.Me(n.resumeToken));break;case 4:this.Ye(e)&&(this.Ze(e),t.Me(n.resumeToken));break;default:Pr()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Ke.forEach((e,t)=>{this.Ye(t)&&n(t)})}Xe(e){const t=e.targetId,n=e.ye.count,r=this.et(t);if(r){var i=r.target;if(ba(i))if(0===n){const e=new ai(i.path);this.je(t,e,Ws.newNoDocument(e,ti.min()))}else Vr(1===n);else{const r=this.tt(t);if(r!==n){const n=this.nt(e),s=n?this.rt(n,e,r):1;if(0!==s){this.Ze(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.We=this.We.insert(t,e)}}}}}nt(e){var t=e.ye.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=Ts(n).toUint8Array()}catch(e){if(e instanceof ws)return Or("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new Vo(i,r,t)}catch(e){return Or(e instanceof Uo?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ae?null:s}rt(e,t,n){return t.ye.count===n-this.ot(e,t.targetId)?0:2}ot(n,r){const e=this.Qe.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Qe.st(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.je(r,e,null),i++)}),i}_t(r){const i=new Map;this.Ke.forEach((e,t)=>{var n=this.et(t);if(n){if(e.current&&ba(n.target)){const i=new ai(n.target.path);null!==this.$e.get(i)||this.ut(t,i)||this.je(t,i,Ws.newNoDocument(i,r))}e.Fe&&(i.set(t,e.xe()),e.Oe())}});let s=Ya();this.Ue.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.et(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.$e.forEach((e,t)=>t.setReadTime(r));var e=new qo(r,i,this.We,this.$e,s);return this.$e=Ga,this.Ue=Qo(),this.We=new ds(Xr),e}ze(e,t){var n;this.Ye(e)&&(n=this.ut(e,t.key)?2:0,this.Je(e).Ne(t.key,n),this.$e=this.$e.insert(t.key,t),this.Ue=this.Ue.insert(t.key,this.ct(t.key).add(e)))}je(e,t,n){if(this.Ye(e)){const r=this.Je(e);this.ut(e,t)?r.Ne(t,1):r.Be(t),this.Ue=this.Ue.insert(t,this.ct(t).delete(e)),n&&(this.$e=this.$e.insert(t,n))}}removeTarget(e){this.Ke.delete(e)}tt(e){var t=this.Je(e).xe();return this.Qe.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Le(e){this.Je(e).Le()}Je(e){let t=this.Ke.get(e);return t||(t=new zo,this.Ke.set(e,t)),t}ct(e){let t=this.Ue.get(e);return t||(t=new ms(Xr),this.Ue=this.Ue.insert(e,t)),t}Ye(e){var t=null!==this.et(e);return t||Mr("WatchChangeAggregator","Detected inactive target",e),t}et(e){var t=this.Ke.get(e);return t&&t.Ce?null:this.Qe.lt(e)}Ze(t){this.Ke.set(t,new zo),this.Qe.getRemoteKeysForTarget(t).forEach(e=>{this.je(t,e,null)})}ut(e,t){return this.Qe.getRemoteKeysForTarget(e).has(t)}}function Qo(){return new ds(ai.comparator)}function Ho(){return new ds(ai.comparator)}const Wo={asc:"ASCENDING",desc:"DESCENDING"},Yo={"<":"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"},Xo={and:"AND",or:"OR"};class Jo{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Zo(e,t){return e.useProto3Json||Ri(t)?t:{value:t}}function eu(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function tu(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function nu(e){return Vr(!!e),ti.fromTimestamp((t=Is(e),new ei(t.seconds,t.nanos)));var t}function ru(e,t){return e=e,new ri(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function iu(e){var t=ri.fromString(e);return Vr(Iu(t)),t}function su(e,t){return ru(e.databaseId,t.path)}function au(e,t){const n=iu(t);if(n.get(1)!==e.databaseId.projectId)throw new qr(Ur.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 qr(Ur.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ai(hu(n))}function ou(e,t){return ru(e.databaseId,t)}function uu(e){var t=iu(e);return 4===t.length?ri.emptyPath():hu(t)}function cu(e){return new ri(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function hu(e){return Vr(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function lu(e,t,n){return{name:su(e,t),fields:n.value.mapValue.fields}}function du(e,t,n){const r=au(e,t.name),i=nu(t.updateTime),s=t.createTime?nu(t.createTime):ti.min(),a=new Hs({mapValue:{fields:t.fields}}),o=Ws.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function fu(e,t){let n;if(t instanceof bo)n={update:lu(e,t.key,t.value)};else if(t instanceof xo)n={delete:su(e,t.key)};else if(t instanceof Io)n={update:lu(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 Ao))return Pr();n={verify:su(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof ro)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof io)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof ao)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof uo)return{fieldPath:e.field.canonicalString(),increment:t.Ee};throw Pr()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,eu(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:Pr())),n;var r}function gu(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?go.updateTime(nu(i.updateTime)):void 0!==i.exists?go.exists(i.exists):go.none():go.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Vr("REQUEST_TIME"===t.setToServerValue),n=new ro;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new io(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new ao(e)}else"increment"in t?n=new uo(e,t.increment):Pr();var r=si.fromServerFormat(t.fieldPath);return new lo(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=au(t,e.update.name),a=new Hs({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new vs(t.map(e=>si.fromServerFormat(e)))}(e.updateMask);return new Io(s,a,t,n,r)}return new bo(s,a,n,r)}if(e.delete){const r=au(t,e.delete);return new xo(r,n)}if(e.verify){const r=au(t,e.verify);return new Ao(r,n)}return Pr()}function mu(e,t){return{documents:[ou(e,t.path)]}}function pu(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=ou(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=ou(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length)return function n(e){return e instanceof ta?function(e){if("=="===e.op){if(js(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NAN"}};if(Bs(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(js(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NOT_NAN"}};if(Bs(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:_u(e.field),op:vu(e.op),value:e.value}}}(e):e instanceof na?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:wu(e.op),filters:t}}}(e):Pr()}(na.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:_u(e.field),direction:(e=e.dir,Wo[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);i=Zo(e,t.limit);return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function yu(e){let t=uu(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0<a){Vr(1===a);const f=s.from[0];f.allDescendants?o=f.collectionId:t=t.child(f.collectionId)}let u=[];s.where&&(u=function(e){const t=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=bu(e.unaryFilter.field);return ta.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=bu(e.unaryFilter.field);return ta.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=bu(e.unaryFilter.field);return ta.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=bu(e.unaryFilter.field);return ta.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Pr()}}(e):void 0!==e.fieldFilter?function(e){return ta.create(bu(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 Pr()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return na.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Pr()}}(e.compositeFilter.op))}(e):Pr()}(e);return t instanceof na&&sa(t)?t.getFilters():[t]}(s.where));let c=[];s.orderBy&&(c=s.orderBy.map(e=>function(e){return new Zs(bu(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let h=null;s.limit&&(h=(e=s.limit,Ri(n="object"==typeof e?e.value:e)?null:n));let l=null;s.startAt&&(l=(r=s.startAt,i=!!r.before,n=r.values||[],new Ys(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new Ys(s,i))),xa(t,o,c,u,h,"F",l,d)}function vu(e){return Yo[e]}function wu(e){return Xo[e]}function _u(e){return{fieldPath:e.canonicalString()}}function bu(e){return si.fromServerFormat(e.fieldPath)}function Iu(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class Eu{constructor(e,t,n,r,i=ti.min(),s=ti.min(),a=_s.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new Eu(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Eu(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Eu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Eu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Tu{constructor(e){this.ht=e}}function Su(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:xu(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:su(i=e.ht,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:eu(i,e.version.toTimestamp()),createTime:eu(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Au(t.version)};else{if(!t.isUnknownDocument())return Pr();r.unknownDocument={path:n.path.toArray(),version:Au(t.version)}}var i;return r}function xu(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Au(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Du(e){var t=new ei(e.seconds,e.nanoseconds);return ti.fromTimestamp(t)}function Cu(t,e){const n=(e.baseMutations||[]).map(e=>gu(t.ht,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>gu(t.ht,e)),i=ei.fromMillis(e.localWriteTimeMs);return new Do(e.batchId,i,n,r)}function Nu(e){var t,n=Du(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?Du(e.lastLimboFreeSnapshotVersion):ti.min(),i=void 0!==e.query.documents?(Vr(1===(t=e.query).documents.length),Ma(Aa(uu(t.documents[0])))):Ma(yu(e.query));return new Eu(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,_s.fromBase64String(e.resumeToken))}function ku(e,t){var n=Au(t.snapshotVersion),r=Au(t.lastLimboFreeSnapshotVersion),i=(ba(t.target)?mu:pu)(e.ht,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:wa(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Ru(e){var t=yu({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Oa(t,t.limit,"L"):t}function Mu(e,t){return new No(t.largestBatchId,gu(e.ht,t.overlayMutation))}function Lu(e,t){var n=t.path.lastSegment();return[e,Oi(t.path.popLast()),n]}function Ou(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:Au(r.readTime),documentKey:Oi(r.documentKey.path),largestBatchId:r.largestBatchId}}class Fu{getBundleMetadata(e,t){return Pu(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:Du(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return Pu(e).put({bundleId:(t=t).id,createTime:Au(nu(t.createTime)),version:t.version})}getNamedQuery(e,t){return Vu(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:Ru(e.bundledQuery),readTime:Du(e.readTime)}})}saveNamedQuery(e,t){return Vu(e).put({name:(t=t).name,readTime:Au(nu(t.readTime)),bundledQuery:t.bundledQuery})}}function Pu(e){return us(e,"bundles")}function Vu(e){return us(e,"namedQueries")}class Uu{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){var n=t.uid||"";return new Uu(e,n)}getOverlay(e,t){return qu(e).get(Lu(this.userId,t)).next(e=>e?Mu(this.serializer,e):null)}getOverlays(e,t){const n=Qa();return wi.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new No(i,t);s.push(this.It(r,n))}),wi.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Oi(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(qu(n).J("collectionPathOverlayIndex",t))}),wi.waitFor(i)}getOverlaysForCollection(e,t,n){const r=Qa(),i=Oi(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return qu(e).G("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=Mu(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=Qa();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return qu(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=Mu(this.serializer,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}It(e,t){return qu(e).put(function(e,t,n){var[,r,i]=Lu(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:fu(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function qu(e){return us(e,"documentOverlays")}class Bu{constructor(){}Tt(e,t){this.Et(e,t),t.dt()}Et(e,t){var n,r;"nullValue"in e?this.At(t,5):"booleanValue"in e?(this.At(t,10),t.Rt(e.booleanValue?1:0)):"integerValue"in e?(this.At(t,15),t.Rt(Es(e.integerValue))):"doubleValue"in e?(n=Es(e.doubleValue),isNaN(n)?this.At(t,13):(this.At(t,15),Mi(n)?t.Rt(0):t.Rt(n))):"timestampValue"in e?(r=e.timestampValue,this.At(t,20),"string"==typeof r?t.Vt(r):(t.Vt(`${r.seconds||""}`),t.Rt(r.nanos||0))):"stringValue"in e?(this.ft(e.stringValue,t),this.gt(t)):"bytesValue"in e?(this.At(t,30),t.yt(Ts(e.bytesValue)),this.gt(t)):"referenceValue"in e?this.wt(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.At(t,45),t.Rt(r.latitude||0),t.Rt(r.longitude||0)):"mapValue"in e?zs(e)?this.At(t,Number.MAX_SAFE_INTEGER):(this.St(e.mapValue,t),this.gt(t)):"arrayValue"in e?(this.bt(e.arrayValue,t),this.gt(t)):Pr()}ft(e,t){this.At(t,25),this.Dt(e,t)}Dt(e,t){t.Vt(e)}St(e,t){var n=e.fields||{};this.At(t,55);for(const e of Object.keys(n))this.ft(e,t),this.Et(n[e],t)}bt(e,t){var n=e.values||[];this.At(t,50);for(const e of n)this.Et(e,t)}wt(e,t){this.At(t,37),ai.fromName(e).path.forEach(e=>{this.At(t,60),this.Dt(e,t)})}At(e,t){e.Rt(t)}gt(e){e.Rt(2)}}function ju(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)}Bu.vt=new Bu;class Gu{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ct(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ft(n.value),n=t.next();this.Mt()}xt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ot(n.value),n=t.next();this.Nt()}Bt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ft(e);else if(e<2048)this.Ft(960|e>>>6),this.Ft(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ft(480|e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e);else{const e=t.codePointAt(0);this.Ft(240|e>>>18),this.Ft(128|63&e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e)}}this.Mt()}Lt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ot(e);else if(e<2048)this.Ot(960|e>>>6),this.Ot(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ot(480|e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e);else{const e=t.codePointAt(0);this.Ot(240|e>>>18),this.Ot(128|63&e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e)}}this.Nt()}kt(e){var t=this.qt(e),n=ju(t);this.Qt(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]}Kt(e){var t=this.qt(e),n=ju(t);this.Qt(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])}$t(){this.Ut(255),this.Ut(255)}Wt(){this.Gt(255),this.Gt(255)}reset(){this.position=0}seed(e){this.Qt(e.length),this.buffer.set(e,this.position),this.position+=e.length}zt(){return this.buffer.slice(0,this.position)}qt(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}Ft(e){var t=255&e;0==t?(this.Ut(0),this.Ut(255)):255==t?(this.Ut(255),this.Ut(0)):this.Ut(t)}Ot(e){var t=255&e;0==t?(this.Gt(0),this.Gt(255)):255==t?(this.Gt(255),this.Gt(0)):this.Gt(e)}Mt(){this.Ut(0),this.Ut(1)}Nt(){this.Gt(0),this.Gt(1)}Ut(e){this.Qt(1),this.buffer[this.position++]=e}Gt(e){this.Qt(1),this.buffer[this.position++]=~e}Qt(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 $u{constructor(e){this.jt=e}yt(e){this.jt.Ct(e)}Vt(e){this.jt.Bt(e)}Rt(e){this.jt.kt(e)}dt(){this.jt.$t()}}class zu{constructor(e){this.jt=e}yt(e){this.jt.xt(e)}Vt(e){this.jt.Lt(e)}Rt(e){this.jt.Kt(e)}dt(){this.jt.Wt()}}class Ku{constructor(){this.jt=new Gu,this.Ht=new $u(this.jt),this.Jt=new zu(this.jt)}seed(e){this.jt.seed(e)}Yt(e){return 0===e?this.Ht:this.Jt}zt(){return this.jt.zt()}reset(){this.jt.reset()}}class Qu{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Zt(){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 Qu(this.indexId,this.documentKey,this.arrayValue,n)}}function Hu(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Wu(e.arrayValue,t.arrayValue),0!==n?n:(n=Wu(e.directionalValue,t.directionalValue),0!==n?n:ai.comparator(e.documentKey,t.documentKey)))}function Wu(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 Yu{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Xt=e.orderBy,this.en=[];for(const t of e.filters){const e=t;e.isInequality()?this.tn=e:this.en.push(e)}}nn(e){Vr(e.collectionGroup===this.collectionId);var t=ui(e);if(void 0!==t&&!this.rn(t))return!1;const n=ci(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.rn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(void 0!==this.tn){if(!r.has(this.tn.field.canonicalString())){const e=n[i];if(!this.sn(this.tn,e)||!this.on(this.Xt[s++],e))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Xt.length||!this.on(this.Xt[s++],e))return!1}return!0}rn(e){for(const t of this.en)if(this.sn(t,e))return!0;return!1}sn(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}on(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(Vr(e instanceof ta||e instanceof na),e instanceof ta)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=na.create(n,e.op);return r=rc(r),ec(r)?r:(Vr(r instanceof na),Vr(ra(r)),Vr(1<r.filters.length),r.filters.reduce((e,t)=>tc(e,t)))}(function t(n){var e;if(Vr(n instanceof ta||n instanceof na),n instanceof ta){if(n instanceof ga){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>ta.create(n.field,"==",e)))||[];return na.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return na.create(r,n.op)}(e));return Vr(ec(t)),Ju(t)||Zu(t)?[t]:t.getFilters()}function Ju(e){return e instanceof ta}function Zu(e){return e instanceof na&&sa(e)}function ec(e){return Ju(e)||Zu(e)||function(e){if(e instanceof na&&ia(e)){for(const t of e.getFilters())if(!Ju(t)&&!Zu(t))return!1;return!0}return!1}(e)}function tc(e,t){var n,r;return Vr(e instanceof ta||e instanceof na),Vr(t instanceof ta||t instanceof na),rc(e instanceof ta?t instanceof ta?(n=e,r=t,na.create([n,r],"and")):nc(e,t):t instanceof ta?nc(t,e):function(e,t){if(Vr(0<e.filters.length&&0<t.filters.length),ra(e)&&ra(t))return oa(e,t.getFilters());const n=ia(e)?e:t,r=ia(e)?t:e,i=n.filters.map(e=>tc(e,r));return na.create(i,"or")}(e,t))}function nc(t,e){if(ra(e))return oa(e,t.getFilters());var n=e.filters.map(e=>tc(t,e));return na.create(n,"or")}function rc(t){if(Vr(t instanceof ta||t instanceof na),t instanceof ta)return t;const e=t.getFilters();if(1===e.length)return rc(e[0]);if(aa(t))return t;const n=e.map(e=>rc(e)),r=[];return n.forEach(e=>{e instanceof ta?r.push(e):e instanceof na&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:na.create(r,t.op)}class ic{constructor(){this._n=new sc}addToCollectionParentIndex(e,t){return this._n.add(t),wi.resolve()}getCollectionParents(e,t){return wi.resolve(this._n.getEntries(t))}addFieldIndex(e,t){return wi.resolve()}deleteFieldIndex(e,t){return wi.resolve()}getDocumentsMatchingTarget(e,t){return wi.resolve(null)}getIndexType(e,t){return wi.resolve(0)}getFieldIndexes(e,t){return wi.resolve([])}getNextCollectionGroupToUpdate(e){return wi.resolve(null)}getMinOffset(e,t){return wi.resolve(gi.min())}getMinOffsetFromCollectionGroup(e,t){return wi.resolve(gi.min())}updateCollectionGroup(e,t,n){return wi.resolve()}updateIndexEntries(e,t){return wi.resolve()}}class sc{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ms(ri.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}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 ms(ri.comparator)).toArray()}}const ac=new Uint8Array(0);class oc{constructor(e,t){this.user=e,this.databaseId=t,this.an=new sc,this.un=new ja(e=>wa(e),(e,t)=>_a(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.an.has(t))return wi.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.an.add(t)});r={collectionId:n,parent:Oi(r)};return uc(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[Zr(n),""],!1,!0);return uc(e).G(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Pi(t.parent))}return r})}addFieldIndex(e,t){const n=hc(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=lc(e);return i.next(e=>{n.put(Ou(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=hc(e),r=lc(e),i=cc(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,h){const l=cc(e);let d=!0;const n=new Map;return wi.forEach(this.cn(h),t=>this.ln(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let c=Ya();const d=[];return wi.forEach(n,(e,t)=>{var n;Mr("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${wa(h)}`);var r=function(e,t){var n=ui(t);if(void 0===n)return null;for(const t of Ia(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),i=function(e,t){const n=new Map;for(const r of ci(t))for(const t of Ia(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 i of ci(t)){const t=(0===i.kind?Ea:Ta)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Ys(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of ci(t)){const t=(0===i.kind?Ta:Ea)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Ys(n,r)}(t,e),o=this.hn(e,t,s),u=this.hn(e,t,a),i=this.Pn(e,t,i),i=this.In(e.indexId,r,o,s.inclusive,u,a.inclusive,i);return wi.forEach(i,e=>l.H(e,h.limit).next(e=>{e.forEach(e=>{var t=ai.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),d.push(t))})}))}).next(()=>d)}return wi.resolve(null)})}cn(t){let e=this.un.get(t);return e||(e=0===t.filters.length?[t]:Xu(na.create(t.filters,"and")).map(e=>va(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.un.set(t,e),e)}In(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),u=o/(null!=e?e.length:1),c=[];for(let h=0;h<o;++h){const o=e?this.Tn(e[h/u]):ac,l=this.En(t,o,n[h%u],r),d=this.dn(t,o,i[h%u],s),f=a.map(e=>this.En(t,o,e,!0));c.push(...this.createRange(l,d,f))}return c}En(e,t,n,r){const i=new Qu(e,ai.empty(),t,n);return r?i:i.Zt()}dn(e,t,n,r){const i=new Qu(e,ai.empty(),t,n);return r?i.Zt():i}ln(e,t){const r=new Yu(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.nn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.cn(t);return wi.forEach(r,t=>this.ln(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new ms(si.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(()=>function(e){return null!==e.limit}(t)&&1<r.length&&2===n?1:n)}An(e,t){const n=new Ku;for(const i of ci(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Yt(i.kind);Bu.vt.Tt(e,r)}return n.zt()}Tn(e){const t=new Ku;return Bu.vt.Tt(e,t.Yt(0)),t.zt()}Rn(e,t){const n=new Ku;return Bu.vt.Tt(Vs(this.databaseId,t),n.Yt(0===(r=ci(e)).length?0:r[r.length-1].kind)),n.zt();var r}Pn(e,t,n){if(null===n)return[];let r=[];r.push(new Ku);let i=0;for(const s of ci(e)){const e=n[i++];for(const n of r)if(this.Vn(t,s.fieldPath)&&qs(e))r=this.mn(r,s,e);else{const t=n.Yt(s.kind);Bu.vt.Tt(e,t)}}return this.fn(r)}hn(e,t,n){return this.Pn(e,t,n.position)}fn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].zt();return t}mn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new Ku;r.seed(n.zt()),Bu.vt.Tt(e,r.Yt(t.kind)),i.push(r)}return i}Vn(e,t){return!!e.filters.find(e=>e instanceof ta&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=hc(e),r=lc(e);return(t?n.G("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.G()).next(e=>{const s=[];return wi.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new li(e.sequenceNumber,new gi(Du(e.readTime),new ai(Pi(e.documentKey)),e.largestBatchId)):li.empty(),r=t.fields.map(([e,t])=>new hi(si.fromServerFormat(e),t)),new oi(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}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:Xr(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=hc(e),s=lc(e);return this.gn(e).next(t=>i.G("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>wi.forEach(e,e=>s.put(Ou(e.indexId,this.user,t,r)))))}updateIndexEntries(i,e){const n=new Map;return wi.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?wi.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),wi.forEach(e,n=>this.pn(i,t,n).next(e=>{var t=this.yn(r,n);return e.isEqual(t)?wi.resolve():this.wn(i,r,n,e,t)}))))})}Sn(e,t,n,r){return cc(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.Rn(n,t.key),documentKey:t.key.path.toArray()})}bn(e,t,n,r){return cc(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.Rn(n,t.key),t.key.path.toArray()])}pn(e,n,r){const t=cc(e);let i=new ms(Hu);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.Rn(r,n)])},(e,t)=>{i=i.add(new Qu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}yn(e,t){let n=new ms(Hu);var r=this.An(t,e);if(null==r)return n;const i=ui(t);if(null!=i){var s=e.data.field(i.fieldPath);if(qs(s))for(const i of s.arrayValue.values||[])n=n.add(new Qu(t.indexId,e.key,this.Tn(i),r))}else n=n.add(new Qu(t.indexId,e.key,ac,r));return n}wn(t,n,r,e,i){Mr("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,t,n,r,i){var s=e.getIterator(),a=t.getIterator();let o=ys(s),u=ys(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=ys(a)):t?(i(o),o=ys(s)):(o=ys(s),u=ys(a))}}(e,i,Hu,e=>{s.push(this.Sn(t,n,r,e))},e=>{s.push(this.bn(t,n,r,e))}),wi.waitFor(s)}gn(e){let r=1;return lc(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)=>Hu(e,t)).filter((e,t,n)=>!t||0!==Hu(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=Hu(i,e),s=Hu(i,t);if(0===n)r[0]=e.Zt();else if(0<n&&s<0)r.push(i),r.push(i.Zt());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2){if(this.Dn(r[a],r[a+1]))return[];const t=[r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,ac,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,ac,[]];i.push(IDBKeyRange.bound(t,n))}return i}Dn(e,t){return 0<Hu(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(dc)}getMinOffset(t,e){return wi.mapArray(this.cn(e),e=>this.ln(t,e).next(e=>e||Pr())).next(dc)}}function uc(e){return us(e,"collectionParents")}function cc(e){return us(e,"indexEntries")}function hc(e){return us(e,"indexConfiguration")}function lc(e){return us(e,"indexState")}function dc(e){Vr(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;mi(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new gi(t.readTime,t.documentKey,n)}const fc={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class gc{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new gc(e,gc.DEFAULT_COLLECTION_PERCENTILE,gc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function mc(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const u=r.Z({range:a},(e,t,n)=>(o++,n.delete()));s.push(u.next(()=>{Vr(1===o)}));const c=[];for(const e of n.mutations){const r=qi(t,e.key.path,n.batchId);s.push(i.delete(r)),c.push(e.key)}return wi.waitFor(s).next(()=>c)}function pc(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 Pr();t=e.noDocument}return JSON.stringify(t).length}gc.DEFAULT_COLLECTION_PERCENTILE=10,gc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,gc.DEFAULT=new gc(41943040,gc.DEFAULT_COLLECTION_PERCENTILE,gc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),gc.DISABLED=new gc(-1,0,0);class yc{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.vn={}}static Pt(e,t,n,r){Vr(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new yc(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return wc(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=_c(h),m=wc(h);return m.add({}).next(e=>{Vr("number"==typeof e);const t=new Do(e,l,d,f),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>fu(i.ht,e)),u=a.mutations.map(e=>fu(i.ht,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var i,s,a,o,u;let c=new ms((e,t)=>Xr(e.canonicalString(),t.canonicalString()));for(const h of f){const l=qi(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,Bi))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.vn[e]=t.keys()}),wi.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return wc(e).get(t).next(e=>e?(Vr(e.userId===this.userId),Cu(this.serializer,e)):null)}Cn(e,n){return this.vn[n]?wi.resolve(this.vn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.vn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return wc(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Vr(t.batchId>=r),i=Cu(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return wc(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 wc(e).G("userMutationsIndex",t).next(e=>e.map(e=>Cu(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=Ui(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return _c(a).Z({range:t},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);if(r===this.userId&&o.path.isEqual(i))return wc(a).get(s).next(e=>{if(!e)throw Pr();Vr(e.userId===this.userId),u.push(Cu(this.serializer,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new ms(Xr);const n=[];return e.forEach(a=>{var e=Ui(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=_c(t).Z({range:e},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),wi.waitFor(n).next(()=>this.Fn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=Ui(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new ms(Xr);return _c(e).Z({range:r},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(u=u.add(s)):n.done()}).next(()=>this.Fn(e,u))}Fn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(wc(t).get(e).next(e=>{if(null===e)throw Pr();Vr(e.userId===this.userId),n.push(Cu(this.serializer,e))}))}),wi.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return mc(t.ue,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.Mn(n.batchId)}),wi.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}Mn(e){delete this.vn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return wi.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return _c(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Pi(e[1]);r.push(t)}else n.done()}).next(()=>{Vr(0===r.length)})})}containsKey(e,t){return vc(e,this.userId,t)}xn(e){return bc(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function vc(e,s,t){const n=Ui(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return _c(e).Z({range:r,Y:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function wc(e){return us(e,"mutations")}function _c(e){return us(e,"documentMutations")}function bc(e){return us(e,"mutationQueues")}class Ic{constructor(e){this.On=e}next(){return this.On+=2,this.On}static Nn(){return new Ic(0)}static Bn(){return new Ic(-1)}}class Ec{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.Ln(n).next(e=>{const t=new Ic(e.highestTargetId);return e.highestTargetId=t.next(),this.kn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Ln(e).next(e=>ti.fromTimestamp(new ei(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Ln(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Ln(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.kn(t,e)))}addTargetData(t,n){return this.qn(t,n).next(()=>this.Ln(t).next(e=>(e.targetCount+=1,this.Qn(n,e),this.kn(t,e))))}updateTargetData(e,t){return this.qn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Tc(t).delete(e.targetId)).next(()=>this.Ln(t)).next(e=>(Vr(0<e.targetCount),--e.targetCount,this.kn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return Tc(r).Z((e,t)=>{var n=Nu(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>wi.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Tc(e).Z((e,t)=>{var n=Nu(t);r(n)})}Ln(e){return Sc(e).get("targetGlobalKey").next(e=>(Vr(null!==e),e))}kn(e,t){return Sc(e).put("targetGlobalKey",t)}qn(e,t){return Tc(e).put(ku(this.serializer,t))}Qn(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.Ln(e).next(e=>e.targetCount)}getTargetData(e,i){var t=wa(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return Tc(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=Nu(t);_a(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=xc(n);return e.forEach(e=>{var t=Oi(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),wi.waitFor(i)}removeMatchingKeys(n,e,r){const i=xc(n);return wi.forEach(e,e=>{var t=Oi(e.path);return wi.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=xc(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=xc(e);let i=Ya();return r.Z({range:n,Y:!0},(e,t,n)=>{var r=Pi(e[1]),r=new ai(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Oi(t.path),n=IDBKeyRange.bound([n],[Zr(n)],!1,!0);let r=0;return xc(e).Z({index:"documentTargetsIndex",Y:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}lt(e,t){return Tc(e).get(t).next(e=>e?Nu(e):null)}}function Tc(e){return us(e,"targets")}function Sc(e){return us(e,"targetGlobal")}function xc(e){return us(e,"targetDocuments")}function Ac([e,t],[n,r]){var i=Xr(e,n);return 0===i?Xr(t,r):i}class Dc{constructor(e){this.Kn=e,this.buffer=new ms(Ac),this.$n=0}Un(){return++this.$n}Wn(e){var t=[e,this.Un()];if(this.buffer.size<this.Kn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Ac(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Cc{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Gn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.zn(6e4)}stop(){this.Gn&&(this.Gn.cancel(),this.Gn=null)}get started(){return null!==this.Gn}zn(e){Mr("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Gn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Ti(e)?Mr("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await vi(e)}await this.zn(3e5)})}}class Nc{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.Hn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return wi.resolve(ki.ae);const n=new Dc(t);return this.jn.forEachTarget(e,e=>n.Wn(e.sequenceNumber)).next(()=>this.jn.Jn(e,e=>n.Wn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Mr("LruGarbageCollector","Garbage collection skipped; disabled"),wi.resolve(fc)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Mr("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),fc):this.Yn(t,n))}getCacheSize(e){return this.jn.getCacheSize(e)}Yn(t,n){let r,i,s,a,o,u,c;const h=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(Mr("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,i))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),Rr()<=l.DEBUG&&Mr("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-h}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),wi.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class kc{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Nc(e,t))}Hn(e){const n=this.Zn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Zn(e){let t=0;return this.Jn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Jn(e,n){return this.Xn(e,(e,t)=>n(t))}addReference(e,t,n){return Rc(e,n)}removeReference(e,t,n){return Rc(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Rc(e,t)}er(t,n){let r=!1;return bc(t).X(e=>vc(t,e,n).next(e=>(e&&(r=!0),wi.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.Xn(n,(t,e)=>{if(e<=r){const r=this.er(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,ti.min()),xc(n).delete(function(e){return[0,Oi(e.path)]}(t))))});s.push(r)}}).next(()=>wi.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Rc(e,t)}Xn(e,r){const t=xc(e);let i,s=ki.ae;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==ki.ae&&r(new ai(Pi(i)),s),s=n,i=t):s=ki.ae}).next(()=>{s!==ki.ae&&r(new ai(Pi(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Rc(e,t){return xc(e).put((e=e.currentSequenceNumber,{targetId:0,path:Oi(t.path),sequenceNumber:e}))}class Mc{constructor(){this.changes=new ja(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,Ws.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?wi.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 Lc{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return Vc(e).put(n)}removeEntry(e,t,n){return Vc(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],xu(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.tr(t,e)))}getEntry(e,n){let r=Ws.newInvalidDocument(n);return Vc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Uc(n))},(e,t)=>{r=this.nr(n,t)}).next(()=>r)}rr(e,n){let r={size:0,document:Ws.newInvalidDocument(n)};return Vc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Uc(n))},(e,t)=>{r={document:this.nr(n,t),size:pc(t)}}).next(()=>r)}getEntries(e,t){let r=Ga;return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n)}).next(()=>r)}sr(e,t){let r=Ga,i=new ds(ai.comparator);return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n),i=i.insert(e,pc(t))}).next(()=>({documents:r,_r:i}))}ir(e,t,i){if(t.isEmpty())return wi.resolve();let n=new ms(Bc);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(Uc(n.first()),Uc(n.last())),s=n.getIterator();let a=s.getNext();return Vc(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ai.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&Bc(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.W(Uc(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,r,t,i){const n=r.path,s=[n.popLast().toArray(),n.lastSegment(),xu(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],a=[n.popLast().toArray(),n.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Vc(e).G(IDBKeyRange.bound(s,a,!0)).next(e=>{let t=Ga;for(const n of e){const e=this.nr(ai.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);e.isFoundDocument()&&(Ua(r,e)||i.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=Ga;var r=qc(t,n),a=qc(t,gi.max());return Vc(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.nr(ai.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new Fc(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return Pc(e).get("remoteDocumentGlobalKey").next(e=>(Vr(!!e),e))}tr(e,t){return Pc(e).put("remoteDocumentGlobalKey",t)}nr(e,t){if(t){const e=function(e,t){let n;if(t.document)n=du(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ai.fromSegments(t.noDocument.path),i=Du(t.noDocument.readTime);n=Ws.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Pr();{const e=ai.fromSegments(t.unknownDocument.path),s=Du(t.unknownDocument.version);n=Ws.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new ei(t[0],t[1]),ti.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(ti.min()))return e}return Ws.newInvalidDocument(e)}}function Oc(e){return new Lc(e)}class Fc extends Mc{constructor(e,t){super(),this.ar=e,this.trackRemovals=t,this.ur=new ja(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,u=new ms((e,t)=>Xr(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.ur.get(e);if(a.push(this.ar.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=Su(this.ar.serializer,t);u=u.add(e.path.popLast());var i=pc(r);o+=i-n.size,a.push(this.ar.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=Su(this.ar.serializer,t.convertToNoDocument(ti.min()));a.push(this.ar.addEntry(s,e,o))}}),u.forEach(e=>{a.push(this.ar.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.ar.updateMetadata(s,o)),wi.waitFor(a)}getFromCache(e,t){return this.ar.rr(e,t).next(e=>(this.ur.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.ar.sr(e,t).next(({documents:n,_r:e})=>(e.forEach((e,t)=>{this.ur.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function Pc(e){return us(e,"remoteDocumentGlobal")}function Vc(e){return us(e,"remoteDocumentsV14")}function Uc(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function qc(e,t){const n=t.documentKey.path.toArray();return[e,xu(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function Bc(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=Xr(n[s],r[s]),i)return i;return i=Xr(n.length,r.length),i||(i=Xr(n[n.length-2],r[r.length-2]),i||Xr(n[n.length-1],r[r.length-1]))}class jc{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Gc{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&&wo(r.mutation,e,vs.empty(),ei.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,Ya()).next(()=>e))}getLocalViewOfDocuments(e,t,n=Ya()){const r=Qa();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=za();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=Qa();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Ya()))}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,i){let s=Ga;const a=Qa(),o=Qa();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof Io)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),wo(n.mutation,t,n.mutation.getFieldMask(),ei.now())):a.set(t.key,vs.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new jc(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=Qa();let u=new ds((e,t)=>e-t),c=Ya();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||vs.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(u.get(r.batchId)||Ya()).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,i=Qa();r.forEach(e=>{var t;c.has(e)||(null!==(t=yo(a.get(e),o.get(e)))&&i.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return wi.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,ai.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):ka(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n);var r}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):wi.resolve(Qa());let r=-1,i=n;return e.next(e=>wi.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?wi.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,Ya())).next(e=>({batchId:r,changes:Ka(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ai(t)).next(e=>{let t=za();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s){const a=i.collectionGroup;let o=za();return this.indexManager.getCollectionParents(r,a).next(e=>wi.forEach(e,e=>{var t,n=(t=i,e=e.child(a),new Sa(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}getDocumentsMatchingCollectionQuery(t,s,n){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,a))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Ws.newInvalidDocument(n)))});let i=za();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&wo(n.mutation,t,vs.empty(),ei.now()),Ua(s,t)&&(i=i.insert(e,t))}),i})}}class $c{constructor(e){this.serializer=e,this.cr=new Map,this.lr=new Map}getBundleMetadata(e,t){return wi.resolve(this.cr.get(t))}saveBundleMetadata(e,t){return this.cr.set(t.id,{id:t.id,version:t.version,createTime:nu(t.createTime)}),wi.resolve()}getNamedQuery(e,t){return wi.resolve(this.lr.get(t))}saveNamedQuery(e,t){return this.lr.set(t.name,{name:(t=t).name,query:Ru(t.bundledQuery),readTime:nu(t.readTime)}),wi.resolve()}}class zc{constructor(){this.overlays=new ds(ai.comparator),this.hr=new Map}getOverlay(e,t){return wi.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Qa();return wi.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.It(n,r,t)}),wi.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.hr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.hr.delete(n)),wi.resolve()}getOverlaysForCollection(e,t,n){const r=Qa(),i=t.length+1,s=new ai(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return wi.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new ds((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=Qa(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=Qa(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return wi.resolve(a)}It(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.hr.get(r.largestBatchId).delete(n.key);this.hr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new No(t,n));let i=this.hr.get(t);void 0===i&&(i=Ya(),this.hr.set(t,i)),this.hr.set(t,i.add(n.key))}}class Kc{constructor(){this.Pr=new ms(Qc.Ir),this.Tr=new ms(Qc.Er)}isEmpty(){return this.Pr.isEmpty()}addReference(e,t){var n=new Qc(e,t);this.Pr=this.Pr.add(n),this.Tr=this.Tr.add(n)}dr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ar(new Qc(e,t))}Rr(e,t){e.forEach(e=>this.removeReference(e,t))}Vr(e){const t=new ai(new ri([])),n=new Qc(t,e),r=new Qc(t,e+1),i=[];return this.Tr.forEachInRange([n,r],e=>{this.Ar(e),i.push(e.key)}),i}mr(){this.Pr.forEach(e=>this.Ar(e))}Ar(e){this.Pr=this.Pr.delete(e),this.Tr=this.Tr.delete(e)}gr(e){var t=new ai(new ri([])),n=new Qc(t,e),t=new Qc(t,e+1);let r=Ya();return this.Tr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Qc(e,0),t=this.Pr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Qc{constructor(e,t){this.key=e,this.pr=t}static Ir(e,t){return ai.comparator(e.key,t.key)||Xr(e.pr,t.pr)}static Er(e,t){return Xr(e.pr,t.pr)||ai.comparator(e.key,t.key)}}class Hc{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.yr=1,this.wr=new ms(Qc.Ir)}checkEmpty(e){return wi.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.yr;this.yr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new Do(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.wr=this.wr.add(new Qc(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return wi.resolve(s)}lookupMutationBatch(e,t){return wi.resolve(this.Sr(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.br(t+1),n=n<0?0:n;return wi.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return wi.resolve(0===this.mutationQueue.length?-1:this.yr-1)}getAllMutationBatches(e){return wi.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Qc(t,0),r=new Qc(t,Number.POSITIVE_INFINITY),i=[];return this.wr.forEachInRange([n,r],e=>{var t=this.Sr(e.pr);i.push(t)}),wi.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new ms(Xr);return t.forEach(e=>{var t=new Qc(e,0),n=new Qc(e,Number.POSITIVE_INFINITY);this.wr.forEachInRange([t,n],e=>{r=r.add(e.pr)})}),wi.resolve(this.Dr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ai.isDocumentKey(i)||(i=i.child(""));var s=new Qc(new ai(i),0);let a=new ms(Xr);return this.wr.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.pr)),!0)},s),wi.resolve(this.Dr(a))}Dr(e){const n=[];return e.forEach(e=>{var t=this.Sr(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Vr(0===this.vr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.wr;return wi.forEach(r.mutations,e=>{var t=new Qc(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.wr=i})}Mn(e){}containsKey(e,t){var n=new Qc(t,0),n=this.wr.firstAfterOrEqual(n);return wi.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,wi.resolve()}vr(e,t){return this.br(e)}br(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Sr(e){var t=this.br(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Wc{constructor(e){this.Cr=e,this.docs=new ds(ai.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Cr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,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 wi.resolve(n?n.document.mutableCopy():Ws.newInvalidDocument(t))}getEntries(e,t){let n=Ga;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ws.newInvalidDocument(e))}),wi.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Ga;const s=t.path,a=new ai(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||mi(fi(a),n)<=0||(r.has(a.key)||Ua(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return wi.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Pr()}Fr(e,t){return wi.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Yc(this)}getSize(e){return wi.resolve(this.size)}}class Yc extends Mc{constructor(e){super(),this.ar=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.ar.addEntry(n,t)):this.ar.removeEntry(e)}),wi.waitFor(r)}getFromCache(e,t){return this.ar.getEntry(e,t)}getAllFromCache(e,t){return this.ar.getEntries(e,t)}}class Xc{constructor(e){this.persistence=e,this.Mr=new ja(e=>wa(e),_a),this.lastRemoteSnapshotVersion=ti.min(),this.highestTargetId=0,this.Or=0,this.Nr=new Kc,this.targetCount=0,this.Br=Ic.Nn()}forEachTarget(e,n){return this.Mr.forEach((e,t)=>n(t)),wi.resolve()}getLastRemoteSnapshotVersion(e){return wi.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return wi.resolve(this.Or)}allocateTargetId(e){return this.highestTargetId=this.Br.next(),wi.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Or&&(this.Or=t),wi.resolve()}qn(e){this.Mr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Br=new Ic(t),this.highestTargetId=t),e.sequenceNumber>this.Or&&(this.Or=e.sequenceNumber)}addTargetData(e,t){return this.qn(t),this.targetCount+=1,wi.resolve()}updateTargetData(e,t){return this.qn(t),wi.resolve()}removeTargetData(e,t){return this.Mr.delete(t.target),this.Nr.Vr(t.targetId),--this.targetCount,wi.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Mr.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Mr.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),wi.waitFor(a).next(()=>s)}getTargetCount(e){return wi.resolve(this.targetCount)}getTargetData(e,t){var n=this.Mr.get(t)||null;return wi.resolve(n)}addMatchingKeys(e,t,n){return this.Nr.dr(t,n),wi.resolve()}removeMatchingKeys(t,e,n){this.Nr.Rr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),wi.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Nr.Vr(t),wi.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Nr.gr(t);return wi.resolve(n)}containsKey(e,t){return wi.resolve(this.Nr.containsKey(t))}}class Jc{constructor(e,t){this.Lr={},this.overlays={},this.kr=new ki(0),this.qr=!1,this.qr=!0,this.referenceDelegate=e(this),this.Qr=new Xc(this),this.indexManager=new ic,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Kr(e),new Wc(e)),this.serializer=new Tu(t),this.$r=new $c(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.qr=!1,Promise.resolve()}get started(){return this.qr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new zc,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Lr[e.toKey()];return n||(n=new Hc(t,this.referenceDelegate),this.Lr[e.toKey()]=n),n}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.$r}runTransaction(e,t,n){Mr("MemoryPersistence","Starting transaction:",e);const r=new Zc(this.kr.next());return this.referenceDelegate.Ur(),n(r).next(e=>this.referenceDelegate.Wr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Gr(t,n){return wi.or(Object.values(this.Lr).map(e=>()=>e.containsKey(t,n)))}}class Zc extends yi{constructor(e){super(),this.currentSequenceNumber=e}}class eh{constructor(e){this.persistence=e,this.zr=new Kc,this.jr=null}static Hr(e){return new eh(e)}get Jr(){if(this.jr)return this.jr;throw Pr()}addReference(e,t,n){return this.zr.addReference(n,t),this.Jr.delete(n.toString()),wi.resolve()}removeReference(e,t,n){return this.zr.removeReference(n,t),this.Jr.add(n.toString()),wi.resolve()}markPotentiallyOrphaned(e,t){return this.Jr.add(t.toString()),wi.resolve()}removeTarget(e,t){this.zr.Vr(t.targetId).forEach(e=>this.Jr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Jr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ur(){this.jr=new Set}Wr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return wi.forEach(this.Jr,e=>{const t=ai.fromPath(e);return this.Yr(n,t).next(e=>{e||r.removeEntry(t,ti.min())})}).next(()=>(this.jr=null,r.apply(n)))}updateLimboDocument(e,t){return this.Yr(e,t).next(e=>{e?this.Jr.delete(t.toString()):this.Jr.add(t.toString())})}Kr(e){return 0}Yr(e,t){return wi.or([()=>wi.resolve(this.zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gr(e,t)])}}class th{constructor(e){this.serializer=e}B(t,e,n,r){const i=new _i("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vi,{unique:!0}),s.createObjectStore("documentMutations"),nh(t),t.createObjectStore("remoteDocuments"));let a=wi.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),nh(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ti.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").G().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vi,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return wi.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Xr(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ei(i)))),n<7&&7<=r&&(a=a.next(()=>this.ti(i))),n<8&&8<=r&&(a=a.next(()=>this.ni(t,i))),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.ri(i))),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(e){const t=e.createObjectStore("documentOverlays",{keyPath:Zi});t.createIndex("collectionPathOverlayIndex",es,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",ts,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:ji});t.createIndex("documentKeyIndex",Gi),t.createIndex("collectionGroupIndex",$i)}(t)).next(()=>this.ii(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.si(t,i))),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:Wi}).createIndex("sequenceNumberIndex",Yi,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Xi}).createIndex("documentKeyIndex",Ji,{unique:!1})}(t))),a}ei(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=pc(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Xr(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.G().next(e=>wi.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.G("userMutationsIndex",e).next(e=>wi.forEach(e,e=>{Vr(e.userId===n.userId);var t=Cu(this.serializer,e);return mc(r,n.userId,t).next(()=>{})}))}))}ti(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Z((e,t)=>{const n=new ri(e),r=[0,Oi(n)];s.push(a.get(r).next(e=>e?wi.resolve():(e=>a.put({targetId:0,path:Oi(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>wi.waitFor(s))})}ni(e,t){e.createObjectStore("collectionParents",{keyPath:Hi});const n=t.store("collectionParents"),r=new sc,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Oi(r)})}};return t.store("remoteDocuments").Z({Y:!0},(e,t)=>{const n=new ri(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Z({Y:!0},([,e],t)=>{const n=Pi(e);return i(n.popLast())}))}ri(e){const r=e.store("targets");return r.Z((e,t)=>{var n=Nu(t),n=ku(this.serializer,n);return r.put(n)})}ii(e,a){const t=a.store("remoteDocuments"),o=[];return t.Z((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new ai(ri.fromString(s.document.name).popFirst(5)):s.noDocument?ai.fromSegments(s.noDocument.path):s.unknownDocument?ai.fromSegments(s.unknownDocument.path):Pr()).path.toArray(),i={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};var s;o.push(n.put(i))}).next(()=>wi.waitFor(o))}si(e,s){const t=s.store("mutations"),a=Oc(this.serializer),o=new Jc(eh.Hr,this.serializer.ht);return t.G().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:Ya();Cu(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),wi.forEach(r,(e,t)=>{var n=new Cr(t),r=Uu.Pt(this.serializer,n),i=o.getIndexManager(n),n=yc.Pt(n,this.serializer,i,o.referenceDelegate);return new Gc(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new os(s,ki.ae),e).next()})})}}function nh(e){e.createObjectStore("targetDocuments",{keyPath:Ki}).createIndex("documentTargetsIndex",Qi,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",zi,{unique:!0}),e.createObjectStore("targetGlobal")}const rh="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 ih{constructor(e,t,n,r,i,s,a,o,u,c,h=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.oi=i,this.window=s,this.document=a,this._i=u,this.ai=c,this.ui=h,this.kr=null,this.qr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.li=null,this.hi=null,this.Pi=Number.NEGATIVE_INFINITY,this.Ii=e=>Promise.resolve(),!ih.v())throw new qr(Ur.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new kc(this,r),this.Ti=t+"main",this.serializer=new Tu(o),this.Ei=new bi(this.Ti,this.ui,new th(this.serializer)),this.Qr=new Ec(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Oc(this.serializer),this.$r=new Fu,this.window&&this.window.localStorage?this.di=this.window.localStorage:(this.di=null,!1===c&&Lr("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.Ai().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new qr(Ur.FAILED_PRECONDITION,rh);return this.Ri(),this.Vi(),this.mi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Qr.getHighestSequenceNumber(e))}).then(e=>{this.kr=new ki(e,this._i)}).then(()=>{this.qr=!0}).catch(e=>(this.Ei&&this.Ei.close(),Promise.reject(e)))}fi(t){return this.Ii=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ei.k(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.oi.enqueueAndForget(async()=>{this.started&&await this.Ai()}))}Ai(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>ah(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.gi(t).next(e=>{e||(this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)))})}).next(()=>this.pi(t)).next(e=>this.isPrimary&&!e?this.yi(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(Ti(e))return Mr("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Mr("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.oi.enqueueRetryable(()=>this.Ii(e)),this.isPrimary=e})}gi(e){return sh(e).get("owner").next(e=>wi.resolve(this.Si(e)))}bi(e){return ah(e).delete(this.clientId)}async Di(){if(this.isPrimary&&!this.vi(this.Pi,18e5)){this.Pi=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=us(e,"clientMetadata");return r.G().next(e=>{const t=this.Ci(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return wi.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.di)for(const t of e)this.di.removeItem(this.Fi(t.clientId))}}mi(){this.hi=this.oi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ai().then(()=>this.Di()).then(()=>this.mi()))}Si(e){return!!e&&e.ownerId===this.clientId}pi(t){return this.ai?wi.resolve(!0):sh(t).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)){if(this.Si(e)&&this.networkEnabled)return!0;if(!this.Si(e)){if(!e.allowTabSynchronization)throw new qr(Ur.FAILED_PRECONDITION,rh);return!1}}return!(!this.networkEnabled||!this.inForeground)||ah(t).G().next(e=>void 0===this.Ci(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&&Mr("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.qr=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Oi(),this.Ni(),await this.Ei.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new os(e,ki.ae);return this.yi(t).next(()=>this.bi(t))}),this.Ei.close(),this.Bi()}Ci(e,t){return e.filter(e=>this.vi(e.updateTimeMs,t)&&!this.Mi(e.clientId))}Li(){return this.runTransaction("getActiveClients","readonly",e=>ah(e).G().next(e=>this.Ci(e,18e5).map(e=>e.clientId)))}get started(){return this.qr}getMutationQueue(e,t){return yc.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new oc(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return Uu.Pt(this.serializer,e)}getBundleCache(){return this.$r}runTransaction(t,n,r){Mr("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=15===(e=this.ui)?as:14===e?ss:13===e?is:12===e?rs:11===e?ns:void Pr();let a;return this.Ei.runTransaction(t,i,s,e=>(a=new os(e,this.kr?this.kr.next():ki.ae),"readwrite-primary"===n?this.gi(a).next(e=>!!e||this.pi(a)).next(e=>{if(!e)throw Lr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)),new qr(Ur.FAILED_PRECONDITION,pi);return r(a)}).next(e=>this.wi(a).next(()=>e)):this.ki(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}ki(e){return sh(e).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)&&!this.Si(e)&&!(this.ai||this.allowTabSynchronization&&e.allowTabSynchronization))throw new qr(Ur.FAILED_PRECONDITION,rh)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return sh(e).put("owner",t)}static v(){return bi.v()}yi(e){const t=sh(e);return t.get("owner").next(e=>this.Si(e)?(Mr("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):wi.resolve())}vi(e,t){var n=Date.now();return!(e<n-t||n<e&&(Lr(`Detected an update time that is in the future: ${e} > ${n}`),1))}Ri(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.li=()=>{this.oi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ai()))},this.document.addEventListener("visibilitychange",this.li),this.inForeground="visible"===this.document.visibilityState)}Oi(){this.li&&(this.document.removeEventListener("visibilitychange",this.li),this.li=null)}Vi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();var e=/(?:Version|Mobile)\/1[456]/;h()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.oi.enterRestrictedMode(!0),this.oi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ci))}Ni(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Mi(e){var t;try{var n=null!==(null===(t=this.di)||void 0===t?void 0:t.getItem(this.Fi(e)));return Mr("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Lr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this.di)try{this.di.setItem(this.Fi(this.clientId),String(Date.now()))}catch(e){Lr("Failed to set zombie client id.",e)}}Bi(){if(this.di)try{this.di.removeItem(this.Fi(this.clientId))}catch(e){}}Fi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function sh(e){return us(e,"owner")}function ah(e){return us(e,"clientMetadata")}function oh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class uh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.qi=n,this.Qi=r}static Ki(e,t){let n=Ya(),r=Ya();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 uh(e,t.fromCache,n,r)}}class ch{constructor(){this.$i=!1}initialize(e,t){this.Ui=e,this.indexManager=t,this.$i=!0}getDocumentsMatchingQuery(t,n,r,i){return this.Wi(t,n).next(e=>e||this.Gi(t,n,i,r)).next(e=>e||this.zi(t,n))}Wi(i,s){if(Da(s))return wi.resolve(null);let t=Ma(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Oa(s,null,"F"),t=Ma(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=Ya(...e);return this.Ui.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.ji(s,n);return this.Hi(s,t,r,e.readTime)?this.Wi(i,Oa(s,null,"F")):this.Ji(i,t,s,e)}))})))}Gi(n,r,i,s){return Da(r)||s.isEqual(ti.min())?this.zi(n,r):this.Ui.getDocuments(n,i).next(e=>{var t=this.ji(r,e);return this.Hi(r,t,i,s)?this.zi(n,r):(Rr()<=l.DEBUG&&Mr("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Va(r)),this.Ji(n,t,r,di(s,-1)))})}ji(n,e){let r=new ms(Ba(n));return e.forEach((e,t)=>{Ua(n,t)&&(r=r.add(t))}),r}Hi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}zi(e,t){return Rr()<=l.DEBUG&&Mr("QueryEngine","Using full collection scan to execute query:",Va(t)),this.Ui.getDocumentsMatchingQuery(e,t,gi.min())}Ji(e,n,t,r){return this.Ui.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class hh{constructor(e,t,n,r){this.persistence=e,this.Yi=t,this.serializer=r,this.Zi=new ds(Xr),this.Xi=new ja(e=>wa(e),_a),this.es=new Map,this.ts=e.getRemoteDocumentCache(),this.Qr=e.getTargetCache(),this.$r=e.getBundleCache(),this.ns(n)}ns(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Gc(this.ts,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ts.setIndexManager(this.indexManager),this.Yi.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Zi))}}function lh(e,t,n,r){return new hh(e,t,n,r)}async function dh(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a.ns(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Ya();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({rs:e,removedBatchIds:t,addedBatchIds:n}))})})}function fh(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Qr.getLastRemoteSnapshotVersion(e))}function gh(e,c){const h=e,l=c.snapshotVersion;let d=h.Zi;return h.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=h.ts.newChangeBuffer({trackRemovals:!0});d=h.Zi;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Qr.removeMatchingKeys(o,t.removedDocuments,n).next(()=>h.Qr.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==c.targetMismatches.get(n)?e=e.withResumeToken(_s.EMPTY_BYTE_STRING,ti.min()).withLastLimboFreeSnapshotVersion(ti.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||u.push(h.Qr.updateTargetData(o,e))}});let t=Ga,n=Ya();if(c.documentUpdates.forEach(e=>{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(mh(o,e,c.documentUpdates).next(e=>{t=e.ss,n=e.os})),!l.isEqual(ti.min())){const c=h.Qr.getLastRemoteSnapshotVersion(o).next(e=>h.Qr.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(c)}return wi.waitFor(u).next(()=>e.apply(o)).next(()=>h.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(h.Zi=d,e))}function mh(e,s,t){let n=Ya(),a=Ya();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=Ga;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(ti.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):Mr("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{ss:i,os:a}})}function ph(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Qr.getTargetData(t,r).next(e=>e?(n=e,wi.resolve(n)):i.Qr.allocateTargetId(t).next(e=>(n=new Eu(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Qr.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.Zi.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Zi=i.Zi.insert(e.targetId,e),i.Xi.set(r,e.targetId)),e})}async function yh(e,t,n){const r=e,i=r.Zi.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!Ti(e))throw e;Mr("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Zi=r.Zi.remove(t),r.Xi.delete(i.target)}function vh(e,n,r){const i=e;let s=ti.min(),a=Ya();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.Xi.get(n);return void 0!==i?wi.resolve(r.Zi.get(i)):r.Qr.getTargetData(t,n)}(i,t,Ma(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Qr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.Yi.getDocumentsMatchingQuery(t,n,r?s:ti.min(),r?a:Ya())).next(e=>(bh(i,qa(n),e),{documents:e,_s:a})))}function wh(e,t){const n=e,r=n.Qr,i=n.Zi.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.lt(e,t).next(e=>e?e.target:null))}function _h(e,t){const n=e,r=n.es.get(t)||ti.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.ts.getAllFromCollectionGroup(e,t,di(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(bh(n,t,e),e))}function bh(e,t,n){let r=e.es.get(t)||ti.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.es.set(t,r)}function Ih(e,t){return`firestore_clients_${e}_${t}`}function Eh(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Th(e,t){return`firestore_targets_${e}_${t}`}class Sh{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static hs(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new qr(r.error.code,r.error.message))),s?new Sh(e,t,r.state,i):(Lr("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Ps(){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 xh{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static hs(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new qr(n.error.code,n.error.message))),i?new xh(e,n.state,r):(Lr("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Ps(){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 Ah{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static hs(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=Xa;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=Li(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new Ah(e,i):(Lr("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class Dh{constructor(e,t){this.clientId=e,this.onlineState=t}static hs(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Dh(t.clientId,t.onlineState):(Lr("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Ch{constructor(){this.activeTargetIds=Xa}Is(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ts(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ps(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Nh{constructor(e,t,n,r,i){this.window=e,this.oi=t,this.persistenceKey=n,this.Es=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ds=this.As.bind(this),this.Rs=new ds(Xr),this.started=!1,this.Vs=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.fs=Ih(this.persistenceKey,this.Es),this.gs=`firestore_sequence_number_${this.persistenceKey}`,this.Rs=this.Rs.insert(this.Es,new Ch),this.ps=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.ys=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.ws=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Ss=`firestore_online_state_${this.persistenceKey}`,this.bs=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.ds)}static v(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Li();for(const n of e)if(n!==this.Es){const e=this.getItem(Ih(this.persistenceKey,n));var t;!e||(t=Ah.hs(n,e))&&(this.Rs=this.Rs.insert(t.clientId,t))}this.Ds();const n=this.storage.getItem(this.Ss);if(n){const e=this.vs(n);e&&this.Cs(e)}for(const e of this.Vs)this.As(e);this.Vs=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.gs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Fs(this.Rs)}isActiveQueryTarget(n){let r=!1;return this.Rs.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Ms(e,"pending")}updateMutationState(e,t,n){this.Ms(e,t,n),this.xs(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Th(this.persistenceKey,e)))||(n=xh.hs(e,n))&&(t=n.state)),this.Os.Is(e),this.Ds(),t}removeLocalQueryTarget(e){this.Os.Ts(e),this.Ds()}isLocalQueryTarget(e){return this.Os.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Th(this.persistenceKey,e))}updateQueryState(e,t,n){this.Ns(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.xs(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Bs(e)}notifyBundleLoaded(e){this.Ls(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ds),this.removeItem(this.fs),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Mr("SharedClientState","READ",e,t),t}setItem(e,t){Mr("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Mr("SharedClientState","REMOVE",e),this.storage.removeItem(e)}As(e){const i=e;i.storageArea===this.storage&&(Mr("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.fs?this.oi.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.ps.test(i.key)){if(null==i.newValue){var e=this.ks(i.key);return this.qs(e,null)}e=this.Qs(i.key,i.newValue);if(e)return this.qs(e.clientId,e)}else if(this.ys.test(i.key)){if(null!==i.newValue){var t=this.Ks(i.key,i.newValue);if(t)return this.$s(t)}}else if(this.ws.test(i.key)){if(null!==i.newValue){t=this.Us(i.key,i.newValue);if(t)return this.Ws(t)}}else if(i.key===this.Ss){if(null!==i.newValue){var n=this.vs(i.newValue);if(n)return this.Cs(n)}}else if(i.key===this.gs){n=function(e){let t=ki.ae;if(null!=e)try{var n=JSON.parse(e);Vr("number"==typeof n),t=n}catch(e){Lr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==ki.ae&&this.sequenceNumberHandler(n)}else if(i.key===this.bs){const r=this.Gs(i.newValue);await Promise.all(r.map(e=>this.syncEngine.zs(e)))}}else this.Vs.push(i)}):Lr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Os(){return this.Rs.get(this.Es)}Ds(){this.setItem(this.fs,this.Os.Ps())}Ms(e,t,n){const r=new Sh(this.currentUser,e,t,n),i=Eh(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Ps())}xs(e){var t=Eh(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Bs(e){var t={clientId:this.Es,onlineState:e};this.storage.setItem(this.Ss,JSON.stringify(t))}Ns(e,t,n){const r=Th(this.persistenceKey,e),i=new xh(e,t,n);this.setItem(r,i.Ps())}Ls(e){var t=JSON.stringify(Array.from(e));this.setItem(this.bs,t)}ks(e){var t=this.ps.exec(e);return t?t[1]:null}Qs(e,t){var n=this.ks(e);return Ah.hs(n,t)}Ks(e,t){var n=this.ys.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return Sh.hs(new Cr(n),r,t)}Us(e,t){var n=this.ws.exec(e),n=Number(n[1]);return xh.hs(n,t)}vs(e){return Dh.hs(e)}Gs(e){return JSON.parse(e)}async $s(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.js(e.batchId,e.state,e.error);Mr("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Ws(e){return this.syncEngine.Hs(e.targetId,e.state,e.error)}qs(e,t){const n=t?this.Rs.insert(e,t):this.Rs.remove(e),r=this.Fs(this.Rs),i=this.Fs(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Js(s,a).then(()=>{this.Rs=n})}Cs(e){this.Rs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Fs(e){let n=Xa;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class kh{constructor(){this.Ys=new Ch,this.Zs={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Ys.Is(e),this.Zs[e]||"not-current"}updateQueryState(e,t,n){this.Zs[e]=t}removeLocalQueryTarget(e){this.Ys.Ts(e)}isLocalQueryTarget(e){return this.Ys.activeTargetIds.has(e)}clearQueryState(e){delete this.Zs[e]}getAllActiveQueryTargets(){return this.Ys.activeTargetIds}isActiveQueryTarget(e){return this.Ys.activeTargetIds.has(e)}start(){return this.Ys=new Ch,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Rh{Xs(e){}shutdown(){}}class Mh{constructor(){this.eo=()=>this.no(),this.ro=()=>this.io(),this.so=[],this.oo()}Xs(e){this.so.push(e)}shutdown(){window.removeEventListener("online",this.eo),window.removeEventListener("offline",this.ro)}oo(){window.addEventListener("online",this.eo),window.addEventListener("offline",this.ro)}no(){Mr("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.so)e(0)}io(){Mr("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.so)e(1)}static v(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Lh=null;function Oh(){return null===Lh?Lh=268435456+Math.round(2147483648*Math.random()):Lh++,"0x"+Lh.toString(16)}const Fh={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class Ph{constructor(e){this._o=e._o,this.ao=e.ao}uo(e){this.co=e}lo(e){this.ho=e}onMessage(e){this.Po=e}close(){this.ao()}send(e){this._o(e)}Io(){this.co()}To(e){this.ho(e)}Eo(e){this.Po(e)}}const Vh="WebChannelConnection";class Uh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.Ao=t+"://"+e.host,this.Ro=`projects/${n}/databases/${r}`,this.Vo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get mo(){return!1}fo(t,e,n,r,i){const s=Oh(),a=this.po(t,e);Mr("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.Ro,"x-goog-request-params":this.Vo};return this.yo(o,r,i),this.wo(t,a,o,n).then(e=>(Mr("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw Or("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}So(e,t,n,r,i,s){return this.fo(e,t,n,r,i)}yo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+Nr,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)}po(e,t){var n=Fh[e];return`${this.Ao}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}wo(u,t,n,r){const c=Oh();return new Promise((s,a)=>{const o=new Sr;o.setWithCredentials(!0),o.listenOnce(_r.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case wr.NO_ERROR:var e=o.getResponseJson();Mr(Vh,`XHR for RPC '${u}' ${c} received:`,JSON.stringify(e)),s(e);break;case wr.TIMEOUT:Mr(Vh,`RPC '${u}' ${c} timed out`),a(new qr(Ur.DEADLINE_EXCEEDED,"Request time out"));break;case wr.HTTP_ERROR:var t=o.getStatus();if(Mr(Vh,`RPC '${u}' ${c} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const u=(r=n.status,i=r.toLowerCase().replace(/_/g,"-"),0<=Object.values(Ur).indexOf(i)?i:Ur.UNKNOWN);a(new qr(u,n.message))}else a(new qr(Ur.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new qr(Ur.UNAVAILABLE,"Connection failed."));break;default:Pr()}}finally{Mr(Vh,`RPC '${u}' ${c} completed.`)}var r,i});var e=JSON.stringify(r);Mr(Vh,`RPC '${u}' ${c} sending request:`,r),o.send(t,"POST",e,n,15)})}bo(i,e,t){const s=Oh(),n=[this.Ao,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=new Qn,a=vr(),o={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},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(o.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(o.useFetchStreams=!0),this.yo(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var c=n.join("");Mr(Vh,`Creating RPC '${i}' stream ${s}: ${c}`,o);const h=r.createWebChannel(c,o);let l=!1,d=!1;const f=new Ph({_o:e=>{d?Mr(Vh,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(l||(Mr(Vh,`Opening RPC '${i}' stream ${s} transport.`),h.open(),l=!0),Mr(Vh,`RPC '${i}' stream ${s} sending:`,e),h.send(e))},ao:()=>h.close()}),g=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return g(h,Tr.EventType.OPEN,()=>{d||Mr(Vh,`RPC '${i}' stream ${s} transport opened.`)}),g(h,Tr.EventType.CLOSE,()=>{d||(d=!0,Mr(Vh,`RPC '${i}' stream ${s} transport closed`),f.To())}),g(h,Tr.EventType.ERROR,e=>{d||(d=!0,Or(Vh,`RPC '${i}' stream ${s} transport errored:`,e),f.To(new qr(Ur.UNAVAILABLE,"The operation could not be completed")))}),g(h,Tr.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];Vr(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Mr(Vh,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=yr[e];if(void 0!==t)return Mo(t)}(n),t=r.message;void 0===e&&(e=Ur.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,f.To(new qr(e,t)),h.close()}else Mr(Vh,`RPC '${i}' stream ${s} received:`,e),f.Eo(e)}}),g(a,br.STAT_EVENT,e=>{e.stat===Ir?Mr(Vh,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===Er&&Mr(Vh,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{f.Io()},0),f}}function qh(){return"undefined"!=typeof window?window:null}function Bh(){return"undefined"!=typeof document?document:null}function jh(e){return new Jo(e,!0)}class Gh{constructor(e,t,n=1e3,r=1.5,i=6e4){this.oi=e,this.timerId=t,this.Do=n,this.vo=r,this.Co=i,this.Fo=0,this.Mo=null,this.xo=Date.now(),this.reset()}reset(){this.Fo=0}Oo(){this.Fo=this.Co}No(e){this.cancel();var t=Math.floor(this.Fo+this.Bo()),n=Math.max(0,Date.now()-this.xo),r=Math.max(0,t-n);0<r&&Mr("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Fo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Mo=this.oi.enqueueAfterDelay(this.timerId,r,()=>(this.xo=Date.now(),e())),this.Fo*=this.vo,this.Fo<this.Do&&(this.Fo=this.Do),this.Fo>this.Co&&(this.Fo=this.Co)}Lo(){null!==this.Mo&&(this.Mo.skipDelay(),this.Mo=null)}cancel(){null!==this.Mo&&(this.Mo.cancel(),this.Mo=null)}Bo(){return(Math.random()-.5)*this.Fo}}class $h{constructor(e,t,n,r,i,s,a,o){this.oi=e,this.ko=n,this.qo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Qo=0,this.Ko=null,this.$o=null,this.stream=null,this.Uo=new Gh(e,t)}Wo(){return 1===this.state||5===this.state||this.Go()}Go(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.zo()}async stop(){this.Wo()&&await this.close(0)}jo(){this.state=0,this.Uo.reset()}Ho(){this.Go()&&null===this.Ko&&(this.Ko=this.oi.enqueueAfterDelay(this.ko,6e4,()=>this.Jo()))}Yo(e){this.Zo(),this.stream.send(e)}async Jo(){if(this.Go())return this.close(0)}Zo(){this.Ko&&(this.Ko.cancel(),this.Ko=null)}Xo(){this.$o&&(this.$o.cancel(),this.$o=null)}async close(e,t){this.Zo(),this.Xo(),this.Uo.cancel(),this.Qo++,4!==e?this.Uo.reset():t&&t.code===Ur.RESOURCE_EXHAUSTED?(Lr(t.toString()),Lr("Using maximum backoff delay to prevent overloading the backend."),this.Uo.Oo()):t&&t.code===Ur.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.e_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.lo(t)}e_(){}auth(){this.state=1;const e=this.t_(this.Qo),n=this.Qo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Qo===n&&this.n_(e,t)},t=>{e(()=>{var e=new qr(Ur.UNKNOWN,"Fetching auth token failed: "+t.message);return this.r_(e)})})}n_(e,t){const n=this.t_(this.Qo);this.stream=this.i_(e,t),this.stream.uo(()=>{n(()=>(this.state=2,this.$o=this.oi.enqueueAfterDelay(this.qo,1e4,()=>(this.Go()&&(this.state=3),Promise.resolve())),this.listener.uo()))}),this.stream.lo(e=>{n(()=>this.r_(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}zo(){this.state=5,this.Uo.No(async()=>{this.state=0,this.start()})}r_(e){return Mr("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}t_(t){return e=>{this.oi.enqueueAndForget(()=>this.Qo===t?e():(Mr("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class zh extends $h{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}i_(e,t){return this.connection.bo("Listen",e,t)}onMessage(e){this.Uo.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:Pr(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.useProto3Json?(Vr(void 0===f||"string"==typeof f),_s.fromBase64String(f||"")):(Vr(void 0===f||f instanceof Uint8Array),_s.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?Ur.UNKNOWN:Mo(f.code),new qr(o,f.message||""));n=new $o(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var s=au(e,u.document.name),o=nu(u.document.updateTime),c=u.document.createTime?nu(u.document.createTime):ti.min(),h=new Hs({mapValue:{fields:u.document.fields}}),c=Ws.newFoundDocument(s,o,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new jo(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=au(e,h.document),c=h.readTime?nu(h.readTime):ti.min(),c=Ws.newNoDocument(u,c),h=h.removedTargetIds||[];n=new jo([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=au(e,l.document),l=l.removedTargetIds||[];n=new jo([],l,d,null)}else{if(!("filter"in t))return Pr();{t.filter;const e=t.filter;e.targetId;var{count:l=0,unchangedNames:d}=e,l=new ko(l,d),d=e.targetId;n=new Go(d,l)}}var o,f;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return ti.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?nu(t.readTime):ti.min()}(e);return this.listener.s_(t,n)}o_(e){const t={};t.database=cu(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=ba(r)?{documents:mu(e,r)}:{query:pu(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=tu(e,t.resumeToken);const r=Zo(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(ti.min())){n.readTime=eu(e,t.snapshotVersion.toTimestamp());const r=Zo(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);var n,n=(this.serializer,e,null==(n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return Pr()}}(e.purpose))?null:{"goog-listen-tags":n});n&&(t.labels=n),this.Yo(t)}__(e){const t={};t.database=cu(this.serializer),t.removeTarget=e,this.Yo(t)}}class Kh extends $h{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.a_=!1}get u_(){return this.a_}start(){this.a_=!1,this.lastStreamToken=void 0,super.start()}e_(){this.a_&&this.c_([])}i_(e,t){return this.connection.bo("Write",e,t)}onMessage(e){if(Vr(!!e.streamToken),this.lastStreamToken=e.streamToken,this.a_){this.Uo.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(Vr(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?nu(e.updateTime):nu(t);return n.isEqual(ti.min())&&(n=nu(t)),new fo(n,e.transformResults||[])}(e,i))):[]),n=nu(e.commitTime);return this.listener.l_(n,t)}var r,i;return Vr(!e.writeResults||0===e.writeResults.length),this.a_=!0,this.listener.h_()}P_(){const e={};e.database=cu(this.serializer),this.Yo(e)}c_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>fu(this.serializer,e))};this.Yo(t)}}class Qh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.I_=!1}T_(){if(this.I_)throw new qr(Ur.FAILED_PRECONDITION,"The client has already been terminated.")}fo(n,r,i){return this.T_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.fo(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Ur.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new qr(Ur.UNKNOWN,e.toString())})}So(n,r,i,s){return this.T_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.So(n,r,i,e,t,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Ur.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new qr(Ur.UNKNOWN,e.toString())})}terminate(){this.I_=!0}}class Hh{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.d_=0,this.A_=null,this.R_=!0}V_(){0===this.d_&&(this.m_("Unknown"),this.A_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.A_=null,this.f_("Backend didn't respond within 10 seconds."),this.m_("Offline"),Promise.resolve())))}g_(e){"Online"===this.state?this.m_("Unknown"):(this.d_++,1<=this.d_&&(this.p_(),this.f_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.m_("Offline")))}set(e){this.p_(),this.d_=0,"Online"===e&&(this.R_=!1),this.m_(e)}m_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}f_(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.R_?(Lr(t),this.R_=!1):Mr("OnlineStateTracker",t)}p_(){null!==this.A_&&(this.A_.cancel(),this.A_=null)}}class Wh{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.y_=[],this.w_=new Map,this.S_=new Set,this.b_=[],this.D_=i,this.D_.Xs(e=>{n.enqueueAndForget(async()=>{il(this)&&(Mr("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.S_.add(4),await Xh(t),t.v_.set("Unknown"),t.S_.delete(4),await Yh(t)}(this))})}),this.v_=new Hh(n,r)}}async function Yh(e){if(il(e))for(const t of e.b_)await t(!0)}async function Xh(e){for(const t of e.b_)await t(!1)}function Jh(e,t){const n=e;n.w_.has(t.targetId)||(n.w_.set(t.targetId,t),rl(n)?nl(n):gl(n).Go()&&el(n,t))}function Zh(e,t){const n=e,r=gl(n);n.w_.delete(t),r.Go()&&tl(n,t),0===n.w_.size&&(r.Go()?r.Ho():il(n)&&n.v_.set("Unknown"))}function el(e,t){var n;e.C_.Le(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(ti.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),gl(e).o_(t)}function tl(e,t){e.C_.Le(t),gl(e).__(t)}function nl(t){t.C_=new Ko({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>t.w_.get(e)||null,st:()=>t.datastore.serializer.databaseId}),gl(t).start(),t.v_.V_()}function rl(e){return il(e)&&!gl(e).Wo()&&0<e.w_.size}function il(e){return 0===e.S_.size}function sl(e){e.C_=void 0}async function al(e,t,n){if(!Ti(t))throw t;e.S_.add(1),await Xh(e),e.v_.set("Offline"),n=n||(()=>fh(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Mr("RemoteStore","Retrying IndexedDB access"),await n(),e.S_.delete(1),await Yh(e)})}function ol(t,n){return n().catch(e=>al(t,e,n))}async function ul(e){const t=e,n=ml(t);let r=0<t.y_.length?t.y_[t.y_.length-1].batchId:-1;for(;il(i=t)&&i.y_.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.y_.length&&n.Ho();break}r=e.batchId,function(e,t){e.y_.push(t);const n=ml(e);n.Go()&&n.u_&&n.c_(t.mutations)}(t,e)}catch(e){await al(t,e)}var i;cl(t)&&hl(t)}function cl(e){return il(e)&&!ml(e).Wo()&&0<e.y_.length}function hl(e){ml(e).start()}async function ll(e,t){t&&ml(e).u_&&await async function(e,t){if(Ro(n=t.code)&&n!==Ur.ABORTED){const r=e.y_.shift();ml(e).jo(),await ol(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await ul(e)}var n}(e,t),cl(e)&&hl(e)}async function dl(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Mr("RemoteStore","RemoteStore received new credentials");var r=il(n);n.S_.add(3),await Xh(n),r&&n.v_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.S_.delete(3),await Yh(n)}async function fl(e,t){const n=e;t?(n.S_.delete(2),await Yh(n)):(n.S_.add(2),await Xh(n),n.v_.set("Unknown"))}function gl(t){return t.F_||(t.F_=function(e,t,n){const r=e;return r.T_(),new zh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{uo:(async function(n){n.w_.forEach((e,t)=>{el(n,e)})}).bind(null,t),lo:(async function(e,t){sl(e),rl(e)?(e.v_.g_(t),nl(e)):e.v_.set("Unknown")}).bind(null,t),s_:(async function(e,t,n){if(e.v_.set("Online"),t instanceof $o&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.w_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.w_.delete(r),e.C_.removeTarget(r))}(e,t)}catch(n){Mr("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await al(e,n)}else if(t instanceof jo?e.C_.Ge(t):t instanceof Go?e.C_.Xe(t):e.C_.He(t),!n.isEqual(ti.min()))try{const t=await fh(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.C_._t(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.w_.get(t);n&&i.w_.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.w_.get(e);var r;n&&(i.w_.set(e,n.withResumeToken(_s.EMPTY_BYTE_STRING,n.snapshotVersion)),tl(i,e),r=new Eu(n.target,e,t,n.sequenceNumber),el(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){Mr("RemoteStore","Failed to raise snapshot:",t),await al(e,t)}}).bind(null,t)}),t.b_.push(async e=>{e?(t.F_.jo(),rl(t)?nl(t):t.v_.set("Unknown")):(await t.F_.stop(),sl(t))})),t.F_}function ml(t){return t.M_||(t.M_=function(e,t,n){const r=e;return r.T_(),new Kh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{uo:(async function(e){ml(e).P_()}).bind(null,t),lo:ll.bind(null,t),h_:(async function(e){const t=ml(e);for(const n of e.y_)t.c_(n.mutations)}).bind(null,t),l_:(async function(e,t,n){const r=e.y_.shift(),i=Co.from(r,t,n);await ol(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await ul(e)}).bind(null,t)}),t.b_.push(async e=>{e?(t.M_.jo(),await ul(t)):(await t.M_.stop(),0<t.y_.length&&(Mr("RemoteStore",`Stopping write stream with ${t.y_.length} pending writes`),t.y_=[]))})),t.M_}class pl{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new Br,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new pl(e,t,s,r,i);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 qr(Ur.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 yl(e,t){if(Lr("AsyncQueue",`${t}: ${e}`),Ti(e))return new qr(Ur.UNAVAILABLE,`${t}: ${e}`);throw e}class vl{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ai.comparator(e.key,t.key):(e,t)=>ai.comparator(e.key,t.key),this.keyedMap=za(),this.sortedSet=new ds(this.comparator)}static emptySet(e){return new vl(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 vl))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 vl;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class wl{constructor(){this.x_=new ds(ai.comparator)}track(e){var t=e.doc.key,n=this.x_.get(t);!n||0!==e.type&&3===n.type?this.x_=this.x_.insert(t,e):3===e.type&&1!==n.type?this.x_=this.x_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.x_=this.x_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.x_=this.x_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.x_=this.x_.remove(t):1===e.type&&2===n.type?this.x_=this.x_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.x_=this.x_.insert(t,{type:2,doc:e.doc}):Pr()}O_(){const n=[];return this.x_.inorderTraversal((e,t)=>{n.push(t)}),n}}class _l{constructor(e,t,n,r,i,s,a,o,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new _l(e,t,vl.emptySet(t),s,n,r,!0,!1,i)}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)&&Fa(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 bl{constructor(){this.N_=void 0,this.listeners=[]}}class Il{constructor(){this.queries=new ja(e=>Pa(e),Fa),this.onlineState="Unknown",this.B_=new Set}}async function El(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new bl),i)try{s.N_=await n.onListen(r)}catch(e){const n=yl(e,`Initialization of query '${Va(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.L_(n.onlineState),!s.N_||t.k_(s.N_)&&Sl(n)}async function Tl(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function Sl(e){e.B_.forEach(e=>{e.next()})}class xl{constructor(e,t,n){this.query=e,this.q_=t,this.Q_=!1,this.K_=null,this.onlineState="Unknown",this.options=n||{}}k_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new _l(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Q_?this.U_(e)&&(this.q_.next(e),t=!0):this.W_(e,this.onlineState)&&(this.G_(e),t=!0),this.K_=e,t}onError(e){this.q_.error(e)}L_(e){this.onlineState=e;let t=!1;return this.K_&&!this.Q_&&this.W_(this.K_,e)&&(this.G_(this.K_),t=!0),t}W_(e,t){return!e.fromCache||(!this.options.z_||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}U_(e){if(0<e.docChanges.length)return!0;var t=this.K_&&this.K_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}G_(e){e=_l.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Q_=!0,this.q_.next(e)}}class Al{constructor(e,t){this.j_=e,this.byteLength=t}H_(){return"metadata"in this.j_}}class Dl{constructor(e){this.serializer=e}us(e){return au(this.serializer,e)}cs(e){return e.metadata.exists?du(this.serializer,e.document,!1):Ws.newNoDocument(this.us(e.metadata.name),this.ls(e.metadata.readTime))}ls(e){return nu(e)}}class Cl{constructor(e,t,n){this.J_=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Nl(e)}Y_(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.j_.namedQuery)this.queries.push(e.j_.namedQuery);else if(e.j_.documentMetadata){this.documents.push({metadata:e.j_.documentMetadata}),e.j_.documentMetadata.exists||++t;const n=ri.fromString(e.j_.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.j_.document&&(this.documents[this.documents.length-1].document=e.j_.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Z_(e){const t=new Map,n=new Dl(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.us(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||Ya()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=Ya(),a=Ga;for(const e of n){const n=t.us(e.metadata.name);e.document&&(s=s.add(n));const c=t.cs(e);c.setReadTime(t.ls(e.metadata.readTime)),a=a.insert(n,c)}const o=i.ts.newChangeBuffer({trackRemovals:!0}),u=await ph(i,(r=r,Ma(Aa(ri.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>mh(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Qr.removeMatchingKeysForTargetId(t,u.targetId).next(()=>i.Qr.addMatchingKeys(t,s,u.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.ss,e.os)).next(()=>e.ss)))}(this.localStore,new Dl(this.serializer),this.documents,this.J_.id),t=this.Z_(this.documents);for(const e of this.queries)await async function(e,n,r=Ya()){const i=await ph(e,Ma(Ru(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=nu(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.$r.saveNamedQuery(e,n);t=i.withResumeToken(_s.EMPTY_BYTE_STRING,t);return s.Zi=s.Zi.insert(t.targetId,t),s.Qr.updateTargetData(e,t).next(()=>s.Qr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Qr.addMatchingKeys(e,r,i.targetId)).next(()=>s.$r.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,X_:this.collectionGroups,ea:e}}}function Nl(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class kl{constructor(e){this.key=e}}class Rl{constructor(e){this.key=e}}class Ml{constructor(e,t){this.query=e,this.ta=t,this.na=null,this.hasCachedResults=!1,this.current=!1,this.ra=Ya(),this.mutatedKeys=Ya(),this.ia=Ba(e),this.sa=new vl(this.ia)}get oa(){return this.ta}_a(e,t){const o=t?t.aa:new wl,u=(t||this).sa;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=Ua(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.ua(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.ia(r,d)||f&&this.ia(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),s?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{sa:h,aa:o,Hi:l,mutatedKeys:c}}ua(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.sa;this.sa=e.sa,this.mutatedKeys=e.mutatedKeys;const i=e.aa.O_();i.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 Pr()}};return n(e)-n(t)}(e.type,t.type)||this.ia(e.doc,t.doc)),this.ca(n);var s=t?this.la():[],a=0===this.ra.size&&this.current?1:0,o=a!==this.na;return this.na=a,0!==i.length||o?{snapshot:new _l(this.query,e.sa,r,i,e.mutatedKeys,0==a,o,!1,!!n&&0<n.resumeToken.approximateByteSize()),ha:s}:{ha:s}}L_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({sa:this.sa,aa:new wl,mutatedKeys:this.mutatedKeys,Hi:!1},!1)):{ha:[]}}Pa(e){return!this.ta.has(e)&&!!this.sa.has(e)&&!this.sa.get(e).hasLocalMutations}ca(e){e&&(e.addedDocuments.forEach(e=>this.ta=this.ta.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.ta=this.ta.delete(e)),this.current=e.current)}la(){if(!this.current)return[];const t=this.ra;this.ra=Ya(),this.sa.forEach(e=>{this.Pa(e.key)&&(this.ra=this.ra.add(e.key))});const n=[];return t.forEach(e=>{this.ra.has(e)||n.push(new Rl(e))}),this.ra.forEach(e=>{t.has(e)||n.push(new kl(e))}),n}Ia(e){this.ta=e._s,this.ra=Ya();var t=this._a(e.documents);return this.applyChanges(t,!0)}Ta(){return _l.fromInitialDocuments(this.query,this.sa,this.mutatedKeys,0===this.na,this.hasCachedResults)}}class Ll{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Ol{constructor(e){this.key=e,this.Ea=!1}}class Fl{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.da={},this.Aa=new ja(e=>Pa(e),Fa),this.Ra=new Map,this.Va=new Set,this.ma=new ds(ai.comparator),this.fa=new Map,this.ga=new Kc,this.pa={},this.ya=new Map,this.wa=Ic.Bn(),this.onlineState="Unknown",this.Sa=void 0}get isPrimaryClient(){return!0===this.Sa}}async function Pl(r,e,t,n,i){r.ba=(e,t,n)=>async function(e,t,n,r){let i=t.view._a(n);i.Hi&&(i=await vh(e.localStore,t.query,!1).then(({documents:e})=>t.view._a(e,i)));var s=r&&r.targetChanges.get(t.targetId),s=t.view.applyChanges(i,e.isPrimaryClient,s);return Kl(e,t.targetId,s.ha),s.snapshot}(r,e,t,n);const s=await vh(r.localStore,e,!0),a=new Ml(e,s._s),o=a._a(s.documents),u=Bo.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),c=a.applyChanges(o,r.isPrimaryClient,u);Kl(r,t,c.ha);var h=new Ll(e,t,a);return r.Aa.set(e,h),r.Ra.has(t)?r.Ra.get(t).push(e):r.Ra.set(t,[e]),c.snapshot}async function Vl(e,t,n){const r=Zl(e);try{const e=await function(e,i){const s=e,a=ei.now(),o=i.reduce((e,t)=>e.add(t.key),Ya());let u,c;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=Ga,r=Ya();return s.ts.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=no(r.transform,e||null);null!=i&&(null===n&&(n=Hs.empty()),n.set(r.field,i))}return n||null}(n,u.get(n.key).overlayedDocument);null!=i&&t.push(new Io(n.key,i,function r(e){const i=[];return hs(e.fields,(e,t)=>{const n=new si([e]);if(Gs(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new vs(i)}(i.value.mapValue),go.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:Ka(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.pa[e.currentUser.toKey()];r=r||new ds(Xr),r=r.insert(t,n),e.pa[e.currentUser.toKey()]=r}(r,e.batchId,n),await Hl(r,e.changes),await ul(r.remoteStore)}catch(e){const t=yl(e,"Failed to persist write");n.reject(t)}}async function Ul(e,t){const r=e;try{const e=await gh(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.fa.get(t);n&&(Vr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.Ea=!0:0<e.modifiedDocuments.size?Vr(n.Ea):0<e.removedDocuments.size&&(Vr(n.Ea),n.Ea=!1))}),await Hl(r,e,t)}catch(e){await vi(e)}}function ql(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Aa.forEach((e,t)=>{var n=t.view.L_(i);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.L_(n)&&(r=!0)}),r&&Sl(t)}(t.eventManager,i),r.length&&t.da.s_(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function Bl(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.ts.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=wi.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Vr(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Ya();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(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);Gl(n,r,null),jl(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Hl(n,e)}catch(e){await vi(e)}}function jl(e,t){(e.ya.get(t)||[]).forEach(e=>{e.resolve()}),e.ya.delete(t)}function Gl(e,t,n){const r=e;let i=r.pa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.pa[r.currentUser.toKey()]=i}}function $l(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Ra.get(e))t.Aa.delete(r),n&&t.da.Da(r,n);t.Ra.delete(e),t.isPrimaryClient&&t.ga.Vr(e).forEach(e=>{t.ga.containsKey(e)||zl(t,e)})}function zl(e,t){e.Va.delete(t.path.canonicalString());var n=e.ma.get(t);null!==n&&(Zh(e.remoteStore,n),e.ma=e.ma.remove(t),e.fa.delete(n),Ql(e))}function Kl(e,t,n){for(const r of n)r instanceof kl?(e.ga.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.ma.get(n)||e.Va.has(r)||(Mr("SyncEngine","New document in limbo: "+n),e.Va.add(r),Ql(e))}(e,r)):r instanceof Rl?(Mr("SyncEngine","Document no longer in limbo: "+r.key),e.ga.removeReference(r.key,t),e.ga.containsKey(r.key)||zl(e,r.key)):Pr()}function Ql(e){for(;0<e.Va.size&&e.ma.size<e.maxConcurrentLimboResolutions;){var t=e.Va.values().next().value;e.Va.delete(t);var n=new ai(ri.fromString(t)),t=e.wa.next();e.fa.set(t,new Ol(n)),e.ma=e.ma.insert(n,t),Jh(e.remoteStore,new Eu(Ma(Aa(n.path)),t,"TargetPurposeLimboResolution",ki.ae))}}async function Hl(e,t,r){const i=e,s=[],a=[],o=[];i.Aa.isEmpty()||(i.Aa.forEach((e,n)=>{o.push(i.ba(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=uh.Ki(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.da.s_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>wi.forEach(t,t=>wi.forEach(t.qi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>wi.forEach(t.Qi,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!Ti(e))throw e;Mr("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.Zi.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.Zi=r.Zi.insert(t,i)}}}(i.localStore,a))}async function Wl(r,e){const i=r;if(Jl(i),Zl(i),!0===e&&!0!==i.Sa){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await Yl(i,r.toArray());i.Sa=!0,await fl(i.remoteStore,!0);for(const r of e)Jh(i.remoteStore,r)}else if(!1===e&&!1!==i.Sa){const r=[];let n=Promise.resolve();i.Ra.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>($l(i,t),yh(i.localStore,t,!0))),Zh(i.remoteStore,t)}),await n,await Yl(i,r),function(e){const n=e;n.fa.forEach((e,t)=>{Zh(n.remoteStore,t)}),n.ga.mr(),n.fa=new Map,n.ma=new ds(ai.comparator)}(i),i.Sa=!1,await fl(i.remoteStore,!1)}}async function Yl(t,n){const r=t,i=[],s=[];for(const t of n){let e;const h=r.Ra.get(t);if(h&&0!==h.length){e=await ph(r.localStore,Ma(h[0]));for(const t of h){const n=r.Aa.get(t),h=(a=r,o=n,c=u=void 0,c=await vh((u=a).localStore,o.query,!0),c=o.view.Ia(c),u.isPrimaryClient&&Kl(u,o.targetId,c.ha),await c);h.snapshot&&s.push(h.snapshot)}}else{const h=await wh(r.localStore,t);e=await ph(r.localStore,h),await Pl(r,Xl(h),t,!1,e.resumeToken)}i.push(e)}var a,o,u,c;return r.da.s_(s),i}function Xl(e){return xa(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Jl(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Ul.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.fa.get(t);if(r&&r.Ea)return Ya().add(r.key);{let e=Ya();const r=n.Ra.get(t);if(!r)return e;for(const t of r){const r=n.Aa.get(t);e=e.unionWith(r.view.oa)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.fa.get(t),s=i&&i.key;if(s){let e=new ds(ai.comparator);e=e.insert(s,Ws.newNoDocument(s,ti.min()));const n=Ya().add(s),i=new qo(ti.min(),new Map,new ds(Xr),e,n);await Ul(r,i),r.ma=r.ma.remove(s),r.fa.delete(t),Ql(r)}else await yh(r.localStore,t,!1).then(()=>$l(r,t,n)).catch(vi)}).bind(null,t),t.da.s_=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.k_(e)&&(r=!0);i.N_=e}}r&&Sl(n)}).bind(null,t.eventManager),t.da.Da=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function Zl(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=Bl.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(Vr(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);Gl(r,t,n),jl(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Hl(r,e)}catch(n){await vi(n)}}).bind(null,t),t}class ed{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=jh(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return lh(this.persistence,new ch,e.initialUser,this.serializer)}createPersistence(e){return new Jc(eh.Hr,this.serializer)}createSharedClientState(e){return new kh}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class td extends ed{constructor(e,t,n){super(),this.Ca=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ca.initialize(this,e),await Zl(this.Ca.syncEngine),await ul(this.Ca.remoteStore),await this.persistence.fi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return lh(this.persistence,new ch,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new Cc(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new Ni(t,this.persistence);return new Ci(e.asyncQueue,n)}createPersistence(e){var t=oh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?gc.withCacheSize(this.cacheSizeBytes):gc.DEFAULT;return new ih(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,qh(),Bh(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new kh}}class nd extends td{constructor(e,t){super(e,t,!1),this.Ca=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ca.syncEngine;this.sharedClientState instanceof Nh&&(this.sharedClientState.syncEngine={js:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Cn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):wi.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await ul(i.remoteStore):"acknowledged"===n||"rejected"===n?(Gl(i,t,r||null),jl(i,t),i.localStore.mutationQueue.Mn(t)):Pr(),await Hl(i,s)):Mr("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Hs:(async function(e,t,n,r){const i=e;if(i.Sa)Mr("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.Ra.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await _h(i.localStore,qa(s[0])),r=qo.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,_s.EMPTY_BYTE_STRING);await Hl(i,e,r);break}case"rejected":await yh(i.localStore,t,!0),$l(i,t,r);break;default:Pr()}}}).bind(null,t),Js:(async function(e,t,n){const r=Jl(e);if(r.Sa){for(const e of t)if(r.Ra.has(e))Mr("SyncEngine","Adding an already active target "+e);else{const t=await wh(r.localStore,e),n=await ph(r.localStore,t);await Pl(r,Xl(t),n.targetId,!1,n.resumeToken),Jh(r.remoteStore,n)}for(const e of n)r.Ra.has(e)&&await yh(r.localStore,e,!1).then(()=>{Zh(r.remoteStore,e),$l(r,e)}).catch(vi)}}).bind(null,t),Li:(function(e){return e.localStore.persistence.Li()}).bind(null,t),zs:(async function(e,t){const n=e;return _h(n.localStore,t).then(e=>Hl(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.fi(async e=>{await Wl(this.Ca.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())})}createSharedClientState(e){var t=qh();if(!Nh.v(t))throw new qr(Ur.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=oh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Nh(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class rd{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=>ql(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){Mr("SyncEngine","User change. New user:",t.toKey());const i=await dh(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.ya.forEach(e=>{e.forEach(e=>{e.reject(new qr(Ur.CANCELLED,r))})}),e.ya.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await Hl(n,i.rs)}var r}).bind(null,this.syncEngine),await fl(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Il}createDatastore(e){var t,n,r,i=jh(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new Uh(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new Qh(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>ql(this.syncEngine,e,0),e=new(Mh.v()?Mh:Rh),new Wh(t,n,r,i,e);var t,n,r,i}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Fl(e,t,n,r,i,s);return a&&(o.Sa=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;Mr("RemoteStore","RemoteStore shutting down."),t.S_.add(5),await Xh(t),t.D_.shutdown(),t.v_.set("Unknown")}(this.remoteStore)}}function id(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.resolve()}}class sd{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Fa(this.observer.next,e)}error(e){this.observer.error?this.Fa(this.observer.error,e):Lr("Uncaught Error in snapshot listener:",e.toString())}Ma(){this.muted=!0}Fa(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class ad{constructor(e,t){this.xa=e,this.serializer=t,this.metadata=new Br,this.buffer=new Uint8Array,this.Oa=new TextDecoder("utf-8"),this.Na().then(e=>{e&&e.H_()?this.metadata.resolve(e.j_.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.j_)}`))},e=>this.metadata.reject(e))}close(){return this.xa.cancel()}async getMetadata(){return this.metadata.promise}async va(){return await this.getMetadata(),this.Na()}async Na(){var e=await this.Ba();if(null===e)return null;var t=this.Oa.decode(e),n=Number(t);isNaN(n)&&this.La(`length string (${t}) is not valid number`);t=await this.ka(n);return new Al(JSON.parse(t),e.length+n)}qa(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Ba(){for(;this.qa()<0&&!await this.Qa(););if(0===this.buffer.length)return null;var e=this.qa();e<0&&this.La("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 ka(e){for(;this.buffer.length<e;)await this.Qa()&&this.La("Reached the end of bundle when more is expected.");var t=this.Oa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}La(e){throw this.xa.cancel(),new Error(`Invalid bundle format: ${e}`)}async Qa(){var e=await this.xa.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 od{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 qr(Ur.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=cu(r.serializer)+"/documents",i={documents:t.map(e=>su(r.serializer,e))},s=await r.So("BatchGetDocuments",n,i,t.length),a=new Map;s.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){Vr(!!t.found),t.found.name,t.found.updateTime;var n=au(e,t.found.name),r=nu(t.found.updateTime),i=t.found.createTime?nu(t.found.createTime):ti.min(),s=new Hs({mapValue:{fields:t.found.fields}});return Ws.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){Vr(!!t.missing),Vr(!!t.readTime);var n=au(e,t.missing),r=nu(t.readTime);return Ws.newNoDocument(n,r)}(n,e):Pr());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Vr(!!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 xo(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=ai.fromPath(t);this.mutations.push(new Ao(n,this.precondition(n)))}),await async function(e,t){const n=e,r=cu(n.serializer)+"/documents",i={writes:t.map(e=>fu(n.serializer,e))};await n.fo("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Pr();t=ti.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new qr(Ur.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(ti.min())?go.exists(!1):go.updateTime(t):go.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return go.exists(!0);if(t.isEqual(ti.min()))throw new qr(Ur.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return go.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class ud{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Ka=n.maxAttempts,this.Uo=new Gh(this.asyncQueue,"transaction_retry")}run(){--this.Ka,this.$a()}$a(){this.Uo.No(async()=>{const t=new od(this.datastore),e=this.Ua(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Wa(e)}))}).catch(e=>{this.Wa(e)})})}Ua(e){try{var t=this.updateFunction(e);return!Ri(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}}Wa(e){0<this.Ka&&this.Ga(e)?(--this.Ka,this.asyncQueue.enqueueAndForget(()=>(this.$a(),Promise.resolve()))):this.deferred.reject(e)}Ga(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!Ro(t)}}class cd{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Cr.UNAUTHENTICATED,this.clientId=Yr.V(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Mr("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Mr("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 qr(Ur.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new Br;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=yl(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function hd(e,t){e.asyncQueue.verifyOperationInProgress(),Mr("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await dh(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function ld(e,n){e.asyncQueue.verifyOperationInProgress();var t=await fd(e);Mr("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>dl(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>dl(n.remoteStore,t)),e._onlineComponents=n}function dd(e){return"FirebaseError"===e.name?e.code===Ur.FAILED_PRECONDITION||e.code===Ur.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function fd(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){Mr("FirestoreClient","Using user provided OfflineComponentProvider");try{await hd(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!dd(n))throw n;Or("Error using user provided cache. Falling back to memory cache: "+n),await hd(t,new ed)}}else Mr("FirestoreClient","Using default OfflineComponentProvider"),await hd(t,new ed);return t._offlineComponents}async function gd(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Mr("FirestoreClient","Using user provided OnlineComponentProvider"),await ld(e,e._uninitializedComponentsProvider._online)):(Mr("FirestoreClient","Using default OnlineComponentProvider"),await ld(e,new rd))),e._onlineComponents}function md(e){return fd(e).then(e=>e.persistence)}function pd(e){return fd(e).then(e=>e.localStore)}function yd(e){return gd(e).then(e=>e.remoteStore)}function vd(e){return gd(e).then(e=>e.syncEngine)}async function wd(e){const t=await gd(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=Jl(e);let r,i;const s=n.Aa.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Ta();else{const e=await ph(n.localStore,Ma(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await Pl(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&Jh(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.Aa.get(t),i=n.Ra.get(r.targetId);if(1<i.length)return n.Ra.set(r.targetId,i.filter(e=>!Fa(e,t))),void n.Aa.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await yh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),Zh(n.remoteStore,r.targetId),$l(n,r.targetId)}).catch(vi)):($l(n,r.targetId),await yh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function _d(e,t,n={}){const r=new Br;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new sd({next:e=>{r.enqueueAndForget(()=>Tl(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new qr(Ur.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new qr(Ur.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 xl(Aa(i.path),e,{includeMetadataChanges:!0,z_:!0});return El(n,o)}(await wd(e),e.asyncQueue,t,n,r)),r.promise}function bd(e,t,n={}){const r=new Br;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new sd({next:e=>{n.enqueueAndForget(()=>Tl(t,a)),e.fromCache&&"server"===r.source?i.reject(new qr(Ur.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.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new xl(e,s,{includeMetadataChanges:!0,z_:!0});return El(t,a)}(await wd(e),e.asyncQueue,t,n,r)),r.promise}function Id(e,t,n,r){const i=(n=n,t=jh(t),s="string"==typeof n?Lo().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return id(e,t);if(e instanceof ArrayBuffer)return id(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new ad(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=nu(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.$r.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(Nl(i));const a=new Cl(i,t.localStore,n.serializer);let e=await n.va();for(;e;){const t=await a.Y_(e);t&&r._updateProgress(t),e=await n.va()}var s=await a.complete();return await Hl(t,s.ea,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.$r.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.X_)}catch(t){return Or("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await vd(e),i,r)})}function Ed(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Td=new Map;function Sd(e,t,n){if(!n)throw new qr(Ur.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function xd(e,t,n,r){if(!0===t&&!0===r)throw new qr(Ur.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Ad(e){if(!ai.isDocumentKey(e))throw new qr(Ur.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Dd(e){if(ai.isDocumentKey(e))throw new qr(Ur.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Cd(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":Pr();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 Nd(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new qr(Ur.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Cd(e);throw new qr(Ur.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function kd(e,t){if(t<=0)throw new qr(Ur.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Rd{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new qr(Ur.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,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new qr(Ur.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}xd("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Ed(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new qr(Ur.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new qr(Ur.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new qr(Ur.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}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&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class Md{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 Rd({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new qr(Ur.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 qr(Ur.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 Rd(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Gr;switch(e.type){case"firstParty":return new Qr(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new qr(Ur.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=Td.get(e);t&&(Mr("ComponentProvider","Removing Datastore"),Td.delete(e),t.terminate())}(this),Promise.resolve()}}function Ld(n,e,t,r={}){var i;const s=(n=Nd(n,Md))._getSettings(),a=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&Or("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),n._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=Cr.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,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e),[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(i)),""].join(".")}(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new qr(Ur.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new Cr(s)}n._authCredentials=new $r(new jr(e,t))}}class Od{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Od(this.firestore,e,this._query)}}class Fd{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 Pd(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Fd(this.firestore,e,this._key)}}class Pd extends Od{constructor(e,t,n){super(e,t,Aa(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 Fd(this.firestore,null,new ai(e))}withConverter(e){return new Pd(this.firestore,e,this._path)}}function Vd(e,t,...n){if(e=m(e),Sd("collection","path",t),e instanceof Md){var r=ri.fromString(t,...n);return Dd(r),new Pd(e,null,r)}if(!(e instanceof Fd||e instanceof Pd))throw new qr(Ur.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ri.fromString(t,...n));return Dd(r),new Pd(e.firestore,null,r)}function Ud(e,t,...n){if(e=m(e),Sd("doc","path",t=1===arguments.length?Yr.V():t),e instanceof Md){var r=ri.fromString(t,...n);return Ad(r),new Fd(e,null,new ai(r))}if(!(e instanceof Fd||e instanceof Pd))throw new qr(Ur.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ri.fromString(t,...n));return Ad(r),new Fd(e.firestore,e instanceof Pd?e.converter:null,new ai(r))}function qd(e,t){return e=m(e),t=m(t),(e instanceof Fd||e instanceof Pd)&&(t instanceof Fd||t instanceof Pd)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function Bd(e,t){return e=m(e),t=m(t),e instanceof Od&&t instanceof Od&&e.firestore===t.firestore&&Fa(e._query,t._query)&&e.converter===t.converter}class jd{constructor(){this.za=Promise.resolve(),this.ja=[],this.Ha=!1,this.Ja=[],this.Ya=null,this.Za=!1,this.Xa=!1,this.eu=[],this.Uo=new Gh(this,"async_queue_retry"),this.tu=()=>{var e=Bh();e&&Mr("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Uo.Lo()};const e=Bh();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.tu)}get isShuttingDown(){return this.Ha}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.nu(),this.ru(e)}enterRestrictedMode(e){if(!this.Ha){this.Ha=!0,this.Xa=e||!1;const t=Bh();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.tu)}}enqueue(e){if(this.nu(),this.Ha)return new Promise(()=>{});const t=new Br;return this.ru(()=>this.Ha&&this.Xa?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.ja.push(e),this.iu()))}async iu(){if(0!==this.ja.length){try{await this.ja[0](),this.ja.shift(),this.Uo.reset()}catch(e){if(!Ti(e))throw e;Mr("AsyncQueue","Operation failed with retryable error: "+e)}0<this.ja.length&&this.Uo.No(()=>this.iu())}}ru(e){var t=this.za.then(()=>(this.Za=!0,e().catch(e=>{throw this.Ya=e,this.Za=!1,Lr("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.Za=!1,e))));return this.za=t}enqueueAfterDelay(e,t,n){this.nu(),-1<this.eu.indexOf(e)&&(t=0);var r=pl.createAndSchedule(this,e,t,n,e=>this.su(e));return this.Ja.push(r),r}nu(){this.Ya&&Pr()}verifyOperationInProgress(){}async ou(){for(var e;await(e=this.za),e!==this.za;);}_u(e){for(const t of this.Ja)if(t.timerId===e)return!0;return!1}au(t){return this.ou().then(()=>{this.Ja.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Ja)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.ou()})}uu(e){this.eu.push(e)}su(e){var t=this.Ja.indexOf(e);this.Ja.splice(t,1)}}function Gd(e){return function(e,t){if("object"==typeof e&&null!==e){var n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return 1}}(e,["next","error","complete"])}class $d{constructor(){this._progressObserver={},this._taskCompletionResolver=new Br,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 zd,Kd,Qd,Hd,Wd;class Yd extends Md{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new jd,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||Jd(this),this._firestoreClient.terminate()}}function Xd(e){return e._firestoreClient||Jd(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Jd(e){var t,n,r,i,s,a=e._freezeSettings(),o=(n=e._databaseId,r=(null===(o=e._app)||void 0===o?void 0:o.options.appId)||"",i=e._persistenceKey,s=a,new Ds(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Ed(s.experimentalLongPollingOptions),s.useFetchStreams));e._firestoreClient=new cd(e._authCredentials,e._appCheckCredentials,e._queue,o),null!==(o=a.localCache)&&void 0!==o&&o._offlineComponentProvider&&null!==(t=a.localCache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:a.localCache.kind,_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider})}function Zd(e,t,n){const r=new Br;return e.asyncQueue.enqueue(async()=>{try{await hd(e,n),await ld(e,t),r.resolve()}catch(e){const t=e;if(!dd(t))throw t;Or("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function ef(e){return function(e){const t=new Br;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;il(n.remoteStore)||Mr("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.ya.get(e)||[];r.push(t),n.ya.set(e,r)}catch(e){const n=yl(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await vd(e),t)),t.promise}(Xd(e=Nd(e,Yd)))}function tf(e){return(n=Xd(e=Nd(e,Yd))).asyncQueue.enqueue(async()=>{const e=await md(n),t=await yd(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.S_.delete(0),Yh(t)}(t)});var n}function nf(e){return(n=Xd(e=Nd(e,Yd))).asyncQueue.enqueue(async()=>{const e=await md(n),t=await yd(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.S_.add(0),await Xh(t),t.v_.set("Offline")}(t)});var n}function rf(t,e){return n=Xd(t=Nd(t,Yd)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.$r.getNamedQuery(e,t))}(await pd(n),r)).then(e=>e?new Od(t,null,e.query):null);var n,r}function sf(e){if(e._initialized||e._terminated)throw new qr(Ur.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 af{constructor(e){this._byteString=e}static fromBase64String(e){try{return new af(_s.fromBase64String(e))}catch(e){throw new qr(Ur.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new af(_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 of{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new qr(Ur.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new si(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class uf{constructor(e){this._methodName=e}}class cf{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new qr(Ur.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new qr(Ur.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 Xr(this._lat,e._lat)||Xr(this._long,e._long)}}const hf=/^__.*__$/;class lf{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Io(e,this.data,this.fieldMask,t,this.fieldTransforms):new bo(e,this.data,t,this.fieldTransforms)}}class df{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Io(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function ff(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Pr()}}class gf{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.cu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get lu(){return this.settings.lu}hu(e){return new gf(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Pu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.hu({path:n,Iu:!1});return r.Tu(e),r}Eu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.hu({path:n,Iu:!1});return r.cu(),r}du(e){return this.hu({path:void 0,Iu:!0})}Au(e){return Lf(e,this.settings.methodName,this.settings.Ru||!1,this.path,this.settings.Vu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}cu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Tu(this.path.get(e))}Tu(e){if(0===e.length)throw this.Au("Document fields must not be empty");if(ff(this.lu)&&hf.test(e))throw this.Au('Document fields cannot begin and end with "__"')}}class mf{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||jh(e)}mu(e,t,n,r=!1){return new gf({lu:e,methodName:t,Vu:n,path:si.emptyPath(),Iu:!1,Ru:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function pf(e){var t=e._freezeSettings(),n=jh(e._databaseId);return new mf(e._databaseId,!!t.ignoreUndefinedProperties,n)}function yf(e,t,n,r,i,s={}){const a=e.mu(s.merge||s.mergeFields?2:0,t,n,i);Nf("Data must be an object, but it was:",a,r);var o=Df(r,a);let u,c;if(s.merge)u=new vs(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=kf(t,r,n);if(!a.contains(i))throw new qr(Ur.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Of(e,i)||e.push(i)}u=new vs(e),c=a.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,c=a.fieldTransforms;return new lf(new Hs(o),u,c)}class vf extends uf{_toFieldTransform(e){if(2!==e.lu)throw 1===e.lu?e.Au(`${this._methodName}() can only appear at the top level of your update data`):e.Au(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof vf}}function wf(e,t,n){return new gf({lu:3,Vu:t.settings.Vu,methodName:e._methodName,Iu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class _f extends uf{_toFieldTransform(e){return new lo(e.path,new ro)}isEqual(e){return e instanceof _f}}class bf extends uf{constructor(e,t){super(e),this.fu=t}_toFieldTransform(e){const t=wf(this,e,!0),n=this.fu.map(e=>Af(e,t)),r=new io(n);return new lo(e.path,r)}isEqual(e){return this===e}}class If extends uf{constructor(e,t){super(e),this.fu=t}_toFieldTransform(e){const t=wf(this,e,!0),n=this.fu.map(e=>Af(e,t)),r=new ao(n);return new lo(e.path,r)}isEqual(e){return this===e}}class Ef extends uf{constructor(e,t){super(e),this.gu=t}_toFieldTransform(e){var t=new uo(e.serializer,eo(e.serializer,this.gu));return new lo(e.path,t)}isEqual(e){return this===e}}function Tf(e,i,s,t){const a=e.mu(1,i,s);Nf("Data must be an object, but it was:",a,t);const o=[],u=Hs.empty();hs(t,(e,t)=>{var n=Mf(i,e,s);t=m(t);var r=a.Eu(n);if(t instanceof vf)o.push(n);else{const e=Af(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new vs(o);return new df(u,n,a.fieldTransforms)}function Sf(e,t,n,r,i,s){const a=e.mu(1,t,n),o=[kf(t,r,n)],u=[i];if(s.length%2!=0)throw new qr(Ur.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<s.length;f+=2)o.push(kf(t,s[f])),u.push(s[f+1]);const c=[],h=Hs.empty();for(let g=o.length-1;0<=g;--g)if(!Of(c,o[g])){const t=o[g];var l=m(l=u[g]);const r=a.Eu(t);if(l instanceof vf)c.push(t);else{const e=Af(l,r);null!=e&&(c.push(t),h.set(t,e))}}var d=new vs(c);return new df(h,d,a.fieldTransforms)}function xf(e,t,n,r=!1){return Af(n,e.mu(r?4:3,t))}function Af(e,t){if(Cf(e=m(e)))return Nf("Unsupported field value:",t,e),Df(e,t);if(e instanceof uf)return function(e,t){if(!ff(t.lu))throw t.Au(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Au(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Iu&&4!==t.lu)throw t.Au("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=Af(i,t.du(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=m(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return eo(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=ei.fromDate(e);return{timestampValue:eu(t.serializer,n)}}if(e instanceof ei){n=new ei(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:eu(t.serializer,n)}}if(e instanceof cf)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof af)return{bytesValue:tu(t.serializer,e._byteString)};if(e instanceof Fd){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.Au(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:ru(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Au(`Unsupported field value: ${Cd(e)}`)}(e,t)}function Df(e,r){const i={};return ls(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):hs(e,(e,t)=>{var n=Af(t,r.Pu(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function Cf(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ei||e instanceof cf||e instanceof af||e instanceof Fd||e instanceof uf)}function Nf(e,t,n){if(!Cf(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=Cd(n);throw"an object"===r?t.Au(e+" a custom object"):t.Au(e+" "+r)}var i}function kf(e,t,n){if((t=m(t))instanceof of)return t._internalPath;if("string"==typeof t)return Mf(e,t);throw Lf("Field path arguments must be of type string or ",e,!1,void 0,n)}const Rf=new RegExp("[~\\*/\\[\\]]");function Mf(t,n,r){if(0<=n.search(Rf))throw Lf(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new of(...n.split("."))._internalPath}catch(e){throw Lf(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Lf(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(s||a)&&(u+=" (found",s&&(u+=` in field ${r}`),a&&(u+=` in document ${i}`),u+=")"),new qr(Ur.INVALID_ARGUMENT,o+e+u)}function Of(e,t){return e.some(e=>e.isEqual(t))}class Ff{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Fd(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new Pf(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(Vf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Pf extends Ff{data(){return super.data()}}function Vf(e,t){return"string"==typeof t?Mf(e,t):(t instanceof of?t:t._delegate)._internalPath}function Uf(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new qr(Ur.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class qf{}class Bf extends qf{}function jf(e,t,...n){let r=[];t instanceof qf&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof $f).length,n=e.filter(e=>e instanceof Gf).length;if(1<t||0<t&&0<n)throw new qr(Ur.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 Gf extends Bf{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Gf(e,t,n)}_apply(e){var t=this._parse(e);return Jf(e._query,t),new Od(e.firestore,e.converter,La(e._query,t))}_parse(e){var t=pf(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new qr(Ur.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){Xf(a,s);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"!==s&&"not-in"!==s&&"array-contains-any"!==s||Xf(a,s),o=xf(n,t,a,"in"===s||"not-in"===s);return ta.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class $f extends qf{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new $f(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]:na.create(e,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(const e of t.getFlattenedFilters())Jf(n,e),n=La(n,e)}(e._query,t),new Od(e.firestore,e.converter,La(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class zf extends Bf{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new zf(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new qr(Ur.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new qr(Ur.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new Zs(t,n);return n=i,null!==Ca(e=e)||null!==(r=Na(e))&&Zf(0,r,n.field),i}(e._query,this._field,this._direction);return new Od(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Sa(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class Kf extends Bf{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new Kf(e,t,n)}_apply(e){return new Od(e.firestore,e.converter,Oa(e._query,this._limit,this._limitType))}}class Qf extends Bf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Qf(e,t,n)}_apply(e){var t,n=Wf(e,this.type,this._docOrFields,this._inclusive);return new Od(e.firestore,e.converter,(t=e._query,e=n,new Sa(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class Hf extends Bf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Hf(e,t,n)}_apply(e){var t,n=Wf(e,this.type,this._docOrFields,this._inclusive);return new Od(e.firestore,e.converter,(t=e._query,e=n,new Sa(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function Wf(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof Ff)return function(e,t,n,r,i){if(!r)throw new qr(Ur.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Ra(e))if(n.field.isKeyField())s.push(Vs(t,r.key));else{const e=r.data.field(n.field);if(Ss(e))throw new qr(Ur.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 qr(Ur.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.`)}s.push(e)}return new Ys(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=pf(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new qr(Ur.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<i.length;u++){const c=i[u];if(a[u].field.isKeyField()){if("string"!=typeof c)throw new qr(Ur.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!ka(e)&&-1!==c.indexOf("/"))throw new qr(Ur.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(ri.fromString(c));if(!ai.isDocumentKey(n))throw new qr(Ur.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 i=new ai(n);o.push(Vs(t,i))}else{const e=xf(n,r,c);o.push(e)}}return new Ys(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function Yf(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new qr(Ur.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!ka(t)&&-1!==n.indexOf("/"))throw new qr(Ur.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(ri.fromString(n));if(!ai.isDocumentKey(r))throw new qr(Ur.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 Vs(e,new ai(r))}if(n instanceof Fd)return Vs(e,n._key);throw new qr(Ur.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Cd(n)}.`)}function Xf(e,t){if(!Array.isArray(e)||0===e.length)throw new qr(Ur.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Jf(e,t){if(t.isInequality()){const r=Na(e),i=t.field;if(null!==r&&!r.isEqual(i))throw new qr(Ur.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 '${i.toString()}'`);var n=Ca(e);null!==n&&Zf(0,i,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(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==r)throw r===t.op?new qr(Ur.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new qr(Ur.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function Zf(e,t,n){if(!n.isEqual(t))throw new qr(Ur.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 eg{convertValue(e,t="none"){switch(Rs(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Es(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(Ts(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 Pr()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return hs(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new cf(Es(e.latitude),Es(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=xs(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(As(e));default:return null}}convertTimestamp(e){var t=Is(e);return new ei(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=ri.fromString(e);Vr(Iu(n));const r=new Cs(n.get(1),n.get(3)),i=new ai(n.popFirst(5));return r.isEqual(t)||Lr(`Document ${i} 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.`),i}}function tg(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class ng extends eg{constructor(e){super(),this.firestore=e}convertBytes(e){return new af(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Fd(this.firestore,null,t)}}class rg{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class ig extends Ff{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new sg(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(Vf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class sg extends ig{data(e={}){return super.data(e)}}class ag{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new rg(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 sg(this._firestore,this._userDataWriter,e.key,e,new rg(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 qr(Ur.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(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new sg(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rg(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new sg(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rg(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.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 Pr()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function og(e,t){return e instanceof ig&&t instanceof ig?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 ag&&t instanceof ag&&e._firestore===t._firestore&&Bd(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class ug extends eg{constructor(e){super(),this.firestore=e}convertBytes(e){return new af(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Fd(this.firestore,null,t)}}function cg(t){t=Nd(t,Fd);const n=Nd(t.firestore,Yd),e=Xd(n),r=new ug(n);return function(e,t){const n=new Br;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(e,t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new qr(Ur.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=yl(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await pd(e),t,n)),n.promise}(e,t._key).then(e=>new ig(n,r,t._key,e,new rg(null!==e&&e.hasLocalMutations,!0),t.converter))}function hg(t){t=Nd(t,Od);const n=Nd(t.firestore,Yd),e=Xd(n),r=new ug(n);return function(e,t){const n=new Br;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await vh(e,t,!0),s=new Ml(t,i._s),a=s._a(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=yl(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await pd(e),t,n)),n.promise}(e,t._query).then(e=>new ag(n,r,t,e))}function lg(e,t,n){e=Nd(e,Fd);var r=Nd(e.firestore,Yd),i=tg(e.converter,t,n);return mg(r,[yf(pf(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,go.none())])}function dg(e,t,n,...r){e=Nd(e,Fd);var i=Nd(e.firestore,Yd),s=pf(i);let a;return a="string"==typeof(t=m(t))||t instanceof of?Sf(s,"updateDoc",e._key,t,n,r):Tf(s,"updateDoc",e._key,t),mg(i,[a.toMutation(e._key,go.exists(!0))])}function fg(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||Gd(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(Gd(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Fd)o=Nd(t.firestore,Yd),u=Aa(t._key.path),a={next:e=>{n[i]&&n[i](pg(o,t,e))},error:n[i+1],complete:n[i+2]};else{const c=Nd(t,Od);o=Nd(c.firestore,Yd),u=c._query;const h=new ug(o);a={next:e=>{n[i]&&n[i](new ag(o,h,c,e))},error:n[i+1],complete:n[i+2]},Uf(t._query)}return function(e,t,n,r){const i=new sd(r),s=new xl(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>El(await wd(e),s)),()=>{i.Ma(),e.asyncQueue.enqueueAndForget(async()=>Tl(await wd(e),s))}}(Xd(o),u,s,a)}function gg(e,t){return function(e,t){const n=new sd(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.B_.add(t),t.next()}(await wd(e),n)),()=>{n.Ma(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.B_.delete(t)}(await wd(e),n))}}(Xd(e=Nd(e,Yd)),Gd(t)?t:{next:t})}function mg(e,t){return function(e,t){const n=new Br;return e.asyncQueue.enqueueAndForget(async()=>Vl(await vd(e),t,n)),n.promise}(Xd(e),t)}function pg(e,t,n){var r=n.docs.get(t._key),i=new ug(e);return new ig(e,i,t._key,r,new rg(n.hasPendingWrites,n.fromCache),t.converter)}const yg={maxAttempts:5};class vg{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=pf(e)}set(e,t,n){this._verifyNotCommitted();const r=wg(e,this._firestore),i=tg(r.converter,t,n),s=yf(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,go.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=wg(e,this._firestore);let s;return s="string"==typeof(t=m(t))||t instanceof of?Sf(this._dataReader,"WriteBatch.update",i._key,t,n,r):Tf(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,go.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=wg(e,this._firestore);return this._mutations=this._mutations.concat(new xo(t._key,go.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 qr(Ur.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function wg(e,t){if((e=m(e)).firestore!==t)throw new qr(Ur.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class _g extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=pf(e)}get(e){const n=wg(e,this._firestore),r=new ng(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return Pr();const t=e[0];if(t.isFoundDocument())return new Ff(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Ff(this._firestore,r,n._key,null,n.converter);throw Pr()})}set(e,t,n){var r=wg(e,this._firestore),i=tg(r.converter,t,n),i=yf(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=wg(e,this._firestore),s="string"==typeof(t=m(t))||t instanceof of?Sf(this._dataReader,"Transaction.update",i._key,t,n,r):Tf(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=wg(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=wg(e,this._firestore),n=new ug(this._firestore);return super.get(e).then(e=>new ig(this._firestore,n,t._key,e._document,new rg(!1,!1),t.converter))}}function bg(t,n,e){t=Nd(t,Yd);var r=Object.assign(Object.assign({},yg),e);return function(e){if(e.maxAttempts<1)throw new qr(Ur.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new Br;return t.asyncQueue.enqueueAndForget(async()=>{var e=await gd(t).then(e=>e.datastore);new ud(t.asyncQueue,e,r,n,i).run()}),i.promise}(Xd(t),e=>n(new _g(t,e)),r)}Kd=!0,Qd=Hg.SDK_VERSION,Nr=Qd,Hg._registerComponent(new p("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new Yd(new zr(e.getProvider("auth-internal")),new Wr(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new qr(Ur.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Cs(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:Kd},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),Hg.registerVersion(Dr,"4.1.2",zd),Hg.registerVersion(Dr,"4.1.2","esm2017");function Ig(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new qr("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Eg(){if("undefined"==typeof Uint8Array)throw new qr("unimplemented","Uint8Arrays are not available in this environment.")}function Tg(){if("undefined"==typeof atob)throw new qr("unimplemented","Blobs are unavailable in Firestore in this environment.")}class Sg{constructor(e){this._delegate=e}static fromBase64String(e){return Tg(),new Sg(af.fromBase64String(e))}static fromUint8Array(e){return Eg(),new Sg(af.fromUint8Array(e))}toBase64(){return Tg(),this._delegate.toBase64()}toUint8Array(){return Eg(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function xg(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 Ag{enableIndexedDbPersistence(e,t){return function(e,t){sf(e=Nd(e,Yd));var n=Xd(e);if(n._uninitializedComponentsProvider)throw new qr(Ur.FAILED_PRECONDITION,"SDK cache is already specified.");Or("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new rd;return Zd(n,i,new td(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){sf(e=Nd(e,Yd));var t=Xd(e);if(t._uninitializedComponentsProvider)throw new qr(Ur.FAILED_PRECONDITION,"SDK cache is already specified.");Or("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new rd;return Zd(t,r,new nd(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new qr(Ur.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new Br;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!bi.v())return Promise.resolve();var t=e+"main";await bi.delete(t)}(oh(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Dg{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Cs||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Or("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={}){Ld(this._delegate,e,t,n)}enableNetwork(){return tf(this._delegate)}disableNetwork(){return nf(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,xd("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 ef(this._delegate)}onSnapshotsInSync(e){return gg(this._delegate,e)}get app(){if(!this._appCompat)throw new qr("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new jg(this,Vd(this._delegate,e))}catch(e){throw Lg(e,"collection()","Firestore.collection()")}}doc(e){try{return new Mg(this,Ud(this._delegate,e))}catch(e){throw Lg(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Ug(this,function(e,t){if(e=Nd(e,Md),Sd("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new qr(Ur.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Od(e,null,(t=t,new Sa(ri.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Lg(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return bg(this._delegate,e=>t(new Ng(this,e)))}batch(){return Xd(this._delegate),new kg(new vg(this._delegate,e=>mg(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=Xd(t=Nd(t,Yd)),r=new $d,Id(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return rf(this._delegate,e).then(e=>e?new Ug(this,e):null)}}class Cg extends eg{constructor(e){super(),this.firestore=e}convertBytes(e){return new Sg(new af(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Mg.forKey(t,this.firestore,null)}}class Ng{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Cg(e)}get(e){const t=Gg(e);return this._delegate.get(t).then(e=>new Pg(this._firestore,new ig(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=Gg(e);return n?(Ig("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=Gg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=Gg(e);return this._delegate.delete(t),this}}class kg{constructor(e){this._delegate=e}set(e,t,n){var r=Gg(e);return n?(Ig("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=Gg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=Gg(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Rg{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new sg(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Vg(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=Rg.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new Rg(e,new Cg(e),t),r.set(t,i)),i}}Rg.INSTANCES=new WeakMap;class Mg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Cg(e)}static forPath(e,t,n){if(e.length%2!=0)throw new qr("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Mg(t,new Fd(t._delegate,n,new ai(e)))}static forKey(e,t,n){return new Mg(t,new Fd(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new jg(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new jg(this.firestore,Vd(this._delegate,e))}catch(e){throw Lg(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Fd&&qd(this._delegate,e)}set(e,t){t=Ig("DocumentReference.set",t);try{return t?lg(this._delegate,e,t):lg(this._delegate,e)}catch(e){throw Lg(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?dg(this._delegate,e):dg(this._delegate,e,t,...n)}catch(e){throw Lg(e,"updateDoc()","DocumentReference.update()")}}delete(){return mg(Nd((e=this._delegate).firestore,Yd),[new xo(e._key,go.none())]);var e}onSnapshot(...e){var t=Og(e),n=Fg(e,e=>new Pg(this.firestore,new ig(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return fg(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?cg:"server"===(null==e?void 0:e.source)?function(t){t=Nd(t,Fd);const n=Nd(t.firestore,Yd);return _d(Xd(n),t._key,{source:"server"}).then(e=>pg(n,t,e))}:function(t){t=Nd(t,Fd);const n=Nd(t.firestore,Yd);return _d(Xd(n),t._key).then(e=>pg(n,t,e))})(this._delegate),t.then(e=>new Pg(this.firestore,new ig(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Mg(this.firestore,e?this._delegate.withConverter(Rg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Lg(e,t,n){return e.message=e.message.replace(t,n),e}function Og(e){for(const t of e)if("object"==typeof t&&!xg(t))return t;return{}}function Fg(e,t){var n;let r;return r=xg(e[0])?e[0]:xg(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 Pg{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Mg(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 og(this._delegate,e._delegate)}}class Vg extends Pg{data(e){var t=this._delegate.data(e);return void 0!==t||Pr(),t}}class Ug{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Cg(e)}where(e,t,n){try{return new Ug(this.firestore,jf(this._delegate,(r=n,i=t,s=Vf("where",e),Gf._create(s,i,r))))}catch(e){throw Lg(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new Ug(this.firestore,jf(this._delegate,([n,r="asc"]=[e,t],i=r,s=Vf("orderBy",n),zf._create(s,i))))}catch(e){throw Lg(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new Ug(this.firestore,jf(this._delegate,(kd("limit",t=e),Kf._create("limit",t,"F"))))}catch(e){throw Lg(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Ug(this.firestore,jf(this._delegate,(kd("limitToLast",t=e),Kf._create("limitToLast",t,"L"))))}catch(e){throw Lg(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Ug(this.firestore,jf(this._delegate,function(...e){return Qf._create("startAt",e,!0)}(...e)))}catch(e){throw Lg(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Ug(this.firestore,jf(this._delegate,function(...e){return Qf._create("startAfter",e,!1)}(...e)))}catch(e){throw Lg(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Ug(this.firestore,jf(this._delegate,function(...e){return Hf._create("endBefore",e,!1)}(...e)))}catch(e){throw Lg(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Ug(this.firestore,jf(this._delegate,function(...e){return Hf._create("endAt",e,!0)}(...e)))}catch(e){throw Lg(e,"endAt()","Query.endAt()")}}isEqual(e){return Bd(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?hg:"server"===(null==e?void 0:e.source)?function(t){t=Nd(t,Od);const n=Nd(t.firestore,Yd),e=Xd(n),r=new ug(n);return bd(e,t._query,{source:"server"}).then(e=>new ag(n,r,t,e))}:function(t){t=Nd(t,Od);const n=Nd(t.firestore,Yd),e=Xd(n),r=new ug(n);return Uf(t._query),bd(e,t._query).then(e=>new ag(n,r,t,e))})(this._delegate),t.then(e=>new Bg(this.firestore,new ag(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Og(e),n=Fg(e,e=>new Bg(this.firestore,new ag(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return fg(this._delegate,t,n)}withConverter(e){return new Ug(this.firestore,e?this._delegate.withConverter(Rg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class qg{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Vg(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class Bg{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Ug(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 Vg(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new qg(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Vg(this._firestore,e))})}isEqual(e){return og(this._delegate,e._delegate)}}class jg extends Ug{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 Mg(this.firestore,e):null}doc(e){try{return void 0===e?new Mg(this.firestore,Ud(this._delegate)):new Mg(this.firestore,Ud(this._delegate,e))}catch(e){throw Lg(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=Nd(e.firestore,Yd),r=Ud(e),i=tg(e.converter,t);return mg(n,[yf(pf(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,go.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Mg(this.firestore,e))}isEqual(e){return qd(this._delegate,e._delegate)}withConverter(e){return new jg(this.firestore,e?this._delegate.withConverter(Rg.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Gg(e){return Nd(e,Fd)}const $g={Firestore:Dg,GeoPoint:cf,Timestamp:ei,Blob:Sg,Transaction:Ng,WriteBatch:kg,DocumentReference:Mg,DocumentSnapshot:Pg,Query:Ug,QueryDocumentSnapshot:Vg,QuerySnapshot:Bg,CollectionReference:jg,FieldPath:class zg{constructor(...e){this._delegate=new of(...e)}static documentId(){return new zg(si.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof of&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Kg{constructor(e){this._delegate=e}static serverTimestamp(){const e=new _f("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Kg(e)}static delete(){const e=new vf("deleteField");return e._methodName="FieldValue.delete",new Kg(e)}static arrayUnion(...e){const t=function(...e){return new bf("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Kg(t)}static arrayRemove(...e){const t=function(...e){return new If("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Kg(t)}static increment(e){const t=new Ef("increment",e);return t._methodName="FieldValue.increment",new Kg(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,kr.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};Hd=t.default,Wd=(e,t)=>new Dg(e,t,new Ag),Hd.INTERNAL.registerComponent(new p("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return Wd(t,n)},"PUBLIC").setServiceProps(Object.assign({},$g))),Hd.registerVersion("@firebase/firestore-compat","0.3.16")}).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.")}});
|
|
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(Hg,Wg){"use strict";try{!(function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l,t=e(Hg);function n(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),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 i=[];for(let h=0;h<n.length;h+=3){var s=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)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.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 i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}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 i=n[e.charAt(u++)],s=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==i||null==s||null==a||null==o)throw new c;r.push(i<<2|s>>4),64!==a&&(r.push(s<<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)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const o=function(e){return e=e,t=n(e),r.encodeByteArray(t,!0).replace(/\./g,"");var t};const i=()=>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__,s=()=>{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)}},a=()=>{try{return i()||(()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}})()||s()}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 h(){return!function(){var e=null===(e=a())||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 d extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,d.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,f.prototype.create)}}class f{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(g,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new d(i,s,n)}}const g=/\{\$([^}]+)}/g;function m(e){return e&&e._delegate?e._delegate:e}class p{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}}(Hd=l=l||{})[Hd.DEBUG=0]="DEBUG",Hd[Hd.VERBOSE=1]="VERBOSE",Hd[Hd.INFO=2]="INFO",Hd[Hd.WARN=3]="WARN",Hd[Hd.ERROR=4]="ERROR",Hd[Hd.SILENT=5]="SILENT";const y={debug:l.DEBUG,verbose:l.VERBOSE,info:l.INFO,warn:l.WARN,error:l.ERROR,silent:l.SILENT},v=l.INFO,w={[l.DEBUG]:"log",[l.VERBOSE]:"log",[l.INFO]:"info",[l.WARN]:"warn",[l.ERROR]:"error"},_=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=w[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};var b,I="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},E={},T=I||self;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 C="closure_uid_"+(1e9*Math.random()>>>0),A=0;function D(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")?D: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 O(e,s){function t(){}t.prototype=s.prototype,e.$=s.prototype,e.prototype=new t,(e.prototype.constructor=e).ac=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function M(){this.s=this.s,this.o=this.o}M.prototype.s=!1,M.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,C)&&e[C]||(e[C]=++A))},M.prototype.N=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 L(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 P(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(S(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function V(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}V.prototype.h=function(){this.defaultPrevented=!0};var B=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 U(e){return/^[\s\xa0]*$/.test(e)}function q(){var e=T.navigator;return(e=e&&e.userAgent)?e:""}function j(e){return-1!=q().indexOf(e)}function G(e){return G[" "](e),e}G[" "]=function(){};var K,z=j("Opera"),$=j("Trident")||j("MSIE"),Q=j("Edge"),H=Q||$,W=j("Gecko")&&!(-1!=q().toLowerCase().indexOf("webkit")&&!j("Edge"))&&!(j("Trident")||j("MSIE"))&&!j("Edge"),Y=-1!=q().toLowerCase().indexOf("webkit")&&!j("Edge");function X(){var e=T.document;return e?e.documentMode:void 0}e:{var J="",Z=(Z=q(),W?/rv:([^\);]+)(\)|;)/.exec(Z):Q?/Edge\/([\d\.]+)/.exec(Z):$?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(Z):Y?/WebKit\/(\S+)/.exec(Z):z?/(?:Version)[ \/]?(\S+)/.exec(Z):void 0);if(Z&&(J=Z?Z[1]:""),$){Z=X();if(null!=Z&&Z>parseFloat(J)){K=String(Z);break e}}K=J}var ee=T.document&&$&&(X()||parseInt(K,10))||void 0;function te(e,t){if(V.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(W){e:{try{G(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,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:ne[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&te.$.h.call(this)}}O(te,V);var ne={2:"touch",3:"pen",4:"mouse"};te.prototype.h=function(){te.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var re="closure_listenable_"+(1e6*Math.random()|0),ie=0;function se(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++ie,this.fa=this.ia=!1}function ae(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function oe(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function ue(e){const t={};for(const n in e)t[n]=e[n];return t}const ce="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function he(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<ce.length;e++)n=ce[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function le(e){this.src=e,this.g={},this.h=0}function de(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=F(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(ae(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function fe(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}le.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=fe(e,t,r,i);return-1<a?(t=e[a],n||(t.ia=!1)):((t=new se(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var ge="closure_lm_"+(1e6*Math.random()|0),me={};function pe(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=Ee(r);return t&&t[re]?t.P(n,r,x(i)?!!i.capture:!!i,s):ye(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)pe(e,t[s],n,r,i);return null}return n=Ee(n),e&&e[re]?e.O(t,n,x(r)?!!r.capture:!!r,i):ye(e,t,n,!1,r,i)}function ye(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=x(i)?!!i.capture:!!i,o=be(e);if(o||(e[ge]=o=new le(e)),(n=o.add(t,n,r,a,s)).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===(i=!B?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(we(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function ve(e){var t,n,r;"number"!=typeof e&&e&&!e.fa&&((t=e.src)&&t[re]?de(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(we(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=be(t))?(de(n,e),0==n.h&&(n.src=null,t[ge]=null)):ae(e)))}function we(e){return e in me?me[e]:me[e]="on"+e}function _e(e,t){var n,r;return e=!!e.fa||(t=new te(t,this),n=e.listener,r=e.la||e.src,e.ia&&ve(e),n.call(r,t))}function be(e){return(e=e[ge])instanceof le?e:null}var Ie="__closure_events_fn_"+(1e9*Math.random()>>>0);function Ee(t){return"function"==typeof t?t:(t[Ie]||(t[Ie]=function(e){return t.handleEvent(e)}),t[Ie])}function Te(){M.call(this),this.i=new le(this),(this.S=this).J=null}function Se(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"==typeof t?t=new V(t,e):t instanceof V?t.target=t.target||e:(a=t,he(t=new V(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=xe(s,r,!0,t)&&a;if(a=xe(s=t.g=e,r,!0,t)&&a,a=xe(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=xe(s=t.g=n[i],r,!1,t)&&a}function xe(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,u=t[s];u&&!u.fa&&u.capture==n&&(a=u.listener,o=u.la||u.src,u.ia&&de(e.i,u),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}O(Te,M),Te.prototype[re]=!0,Te.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=x(i)?!!i.capture:!!i,r=Ee(r),t&&t[re]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=fe(a=t.g[n],r,i,s))&&(ae(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&be(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?fe(n,r,i,s):t)?n[t]:null)&&ve(r))}(this,e,t,n,r)},Te.prototype.N=function(){if(Te.$.N.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++)ae(n[r]);delete t.g[e],t.h--}}this.J=null},Te.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Te.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Ce=T.JSON.stringify;var Ae=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 De,e=>e.reset());class De{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}}let Ne,ke=!1,Re=new class{constructor(){this.h=this.g=null}add(e,t){const n=Ae.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},Oe=()=>{const e=T.Promise.resolve(void 0);Ne=()=>{e.then(Me)}};var Me=()=>{for(var e;e=function(){var e=Re;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=Ae;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}ke=!1};function Fe(e,t){Te.call(this),this.h=e||1,this.g=t||T,this.j=k(this.qb,this),this.l=Date.now()}function Le(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function Pe(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)}O(Fe,Te),(b=Fe.prototype).ga=!1,b.T=null,b.qb=function(){var e;this.ga&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),Se(this,"tick"),this.ga&&(Le(this),this.start())))},b.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},b.N=function(){Fe.$.N.call(this),Le(this),delete this.g};class Ve 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=Pe(()=>{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)}N(){super.N(),this.g&&(T.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function Be(e){M.call(this),this.h=e,this.g={}}O(Be,M);var Ue=[];function qe(e,t,n,r){Array.isArray(n)||(n&&(Ue[0]=n.toString()),n=Ue);for(var i=0;i<n.length;i++){var s=pe(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function je(e){oe(e.g,function(e,t){this.g.hasOwnProperty(t)&&ve(e)},e),e.g={}}function Ge(){this.g=!0}function Ke(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 i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return Ce(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}Be.prototype.N=function(){Be.$.N.call(this),je(this)},Be.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},Ge.prototype.Ea=function(){this.g=!1},Ge.prototype.info=function(){};var ze={},$e=null;function Qe(){return $e=$e||new Te}function He(e){V.call(this,ze.Ta,e)}function We(){var e=Qe();Se(e,new He(e))}function Ye(e,t){V.call(this,ze.STAT_EVENT,e),this.stat=t}function Xe(e){var t=Qe();Se(t,new Ye(t,e))}function Je(e,t){V.call(this,ze.Ua,e),this.size=t}function Ze(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return T.setTimeout(function(){e()},t)}ze.Ta="serverreachability",O(He,V),ze.STAT_EVENT="statevent",O(Ye,V),ze.Ua="timingevent",O(Je,V);var et={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},tt={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function nt(){}function rt(e){return e.h||(e.h=e.i())}function it(){}nt.prototype.h=null;I={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function st(){V.call(this,"d")}function at(){V.call(this,"c")}function ot(){}function ut(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new Be(this),this.P=lt,this.V=new Fe(e=H?125:void 0),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new ct}function ct(){this.i=null,this.g="",this.h=!1}O(st,V),O(at,V),O(ot,nt),ot.prototype.g=function(){return new XMLHttpRequest},ot.prototype.i=function(){return{}};var ht=new ot,lt=45e3,dt={},ft={};function gt(e,t,n){e.L=1,e.v=Rt(Ct(t)),e.s=n,e.S=!0,mt(e,null)}function mt(e,t){e.G=Date.now(),vt(e),e.A=Ct(e.v);var a,o,u,c,h,l,n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),zt(n.i,"t",r),e.C=0,n=e.l.J,e.h=new ct,e.g=zn(e.l,n?t:null,!e.s),0<e.O&&(e.M=new Ve(k(e.Pa,e,e.g),e.O)),qe(e.U,e.g,"readystatechange",e.nb),t=e.I?ue(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),We(),a=e.j,o=e.u,u=e.A,c=e.m,h=e.W,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,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=l;return"XMLHTTP REQ ("+c+") [attempt "+h+"]: "+o+"\n"+u+"\n"+e})}function pt(e){return e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function yt(e,t,n){let r=!0,i;for(;!e.J&&e.C<n.length;){if(i=(a=n,u=o=void 0,o=(s=e).C,-1==(u=a.indexOf("\n",o))?ft:(o=Number(a.substring(o,u)),isNaN(o)?dt:(u+=1)+o>a.length?ft:(a=a.slice(u,u+o),s.C=u+o,a))),i==ft){4==t&&(e.o=4,Xe(14),r=!1),Ke(e.j,e.m,null,"[Incomplete Response]");break}if(i==dt){e.o=4,Xe(15),Ke(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}Ke(e.j,e.m,i,null),Et(e,i)}var s,a,o,u;pt(e)&&i!=ft&&i!=dt&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,Xe(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),Pn(t),t.M=!0,Xe(11))):(Ke(e.j,e.m,n,"[Invalid Chunked Response]"),It(e),bt(e))}function vt(e){e.Y=Date.now()+e.P,wt(e,e.P)}function wt(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=Ze(k(e.lb,e),t)}function _t(e){e.B&&(T.clearTimeout(e.B),e.B=null)}function bt(e){0==e.l.H||e.J||Un(e.l,e)}function It(e){_t(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,Le(e.V),je(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function Et(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Xt(n.i,e)))if(!e.K&&Xt(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;Bn(n),Dn(n)}Ln(n),Xe(18)}}else n.Fa=i[1],0<n.Fa-n.V&&i[2]<37500&&n.G&&0==n.A&&!n.v&&(n.v=Ze(k(n.ib,n),6e3));if(Yt(n.i)<=1&&n.oa){try{n.oa()}catch(e){}n.oa=void 0}}else jn(n,11)}else if(!e.K&&n.g!=e||Bn(n),!U(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.V=s[0],s=s[1],2==n.H)if("c"==s[0]){n.K=s[1],n.pa=s[2];var a=s[3];null!=a&&(n.ra=a,n.l.info("VER="+n.ra));var o=s[4];null!=o&&(n.Ga=o,n.l.info("SVER="+n.Ga));var u,c,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.L=r,n.l.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.i).g||-1==m.indexOf("spdy")&&-1==m.indexOf("quic")&&-1==m.indexOf("h2")||(u.j=u.l,u.g=new Set,u.h&&(Jt(u,u.h),u.h=null))),!r.F||(c=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.Da=c,kt(r.I,r.F,c))}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var l,d,f=e;(r=n).wa=Kn(r,r.J?r.pa:null,r.Y),f.K?(Zt(r.i,f),l=f,(d=r.L)&&l.setTimeout(d),l.B&&(_t(l),vt(l)),r.g=f):Fn(r),0<n.j.length&&kn(n)}else"stop"!=s[0]&&"close"!=s[0]||jn(n,7);else 3==n.H&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?jn(n,7):An(n):"noop"!=s[0]&&n.h&&n.h.Aa(s),n.A=0)}We()}catch(e){}}function Tt(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.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){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.Z&&"function"==typeof e.Z)return e.Z();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),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(b=ut.prototype).setTimeout=function(e){this.P=e},b.nb=function(e){e=e.target;const t=this.M;t&&3==In(e)?t.l():this.Pa(e)},b.Pa=function(e){try{if(e==this.g)e:{var t=In(this.g),n=this.g.Ia();this.g.da();if(!(t<3)&&(3!=t||H||this.g&&(this.h.h||this.g.ja()||En(this.g)))){this.J||4!=t||7==n||We(),_t(this);var r=this.g.da();this.ca=r;t:if(pt(this)){var i=En(this.g);e="";var s=i.length,a=4==In(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){It(this),bt(this);var o="";break t}this.h.i=new T.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:a&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ja();if(this.i=200==r,l=this.j,d=this.u,f=this.A,g=this.m,m=this.W,p=t,y=r,l.info(function(){return"XMLHTTP RESP ("+g+") [ attempt "+m+"]: "+d+"\n"+f+"\n"+p+" "+y}),this.i){if(this.aa&&!this.K){t:{if(this.g){var u,c=this.g;if((u=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!U(u)){var h=u;break t}}h=null}if(!(r=h)){this.i=!1,this.o=3,Xe(12),It(this),bt(this);break e}Ke(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Et(this,r)}this.S?(yt(this,t,o),H&&this.i&&3==t&&(qe(this.U,this.V,"tick",this.mb),this.V.start())):(Ke(this.j,this.m,o,null),Et(this,o)),4==t&&It(this),this.i&&!this.J&&(4==t?Un(this.l,this):(this.i=!1,vt(this)))}else(function(e){const t={};e=(e.g&&2<=In(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!U(e[i])){var n=function(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}(e[i]),r=n[0];if("string"==typeof(n=n[1])){n=n.trim();const s=t[r]||[];t[r]=s,s.push(n)}}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==r&&0<o.indexOf("Unknown SID")?(this.o=3,Xe(12)):(this.o=0,Xe(13)),It(this),bt(this)}}}catch(e){}var l,d,f,g,m,p,y},b.mb=function(){var e,t;this.g&&(e=In(this.g),t=this.g.ja(),this.C<t.length&&(_t(this),yt(this,e,t),this.i&&4!=e&&vt(this)))},b.cancel=function(){this.J=!0,It(this)},b.lb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(We(),Xe(17)),It(this),this.o=2,bt(this)):wt(this,this.Y-n)};var St=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function xt(e){var t,n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof xt?(this.h=e.h,At(this,e.j),this.s=e.s,this.g=e.g,Dt(this,e.m),this.l=e.l,t=e.i,(n=new qt).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Nt(this,n),this.o=e.o):e&&(t=String(e).match(St))?(this.h=!1,At(this,t[1]||"",!0),this.s=Ot(t[2]||""),this.g=Ot(t[3]||"",!0),Dt(this,t[4]),this.l=Ot(t[5]||"",!0),Nt(this,t[6]||"",!0),this.o=Ot(t[7]||"")):(this.h=!1,this.i=new qt(null,this.h))}function Ct(e){return new xt(e)}function At(e,t,n){e.j=n?Ot(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Dt(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 Nt(e,t,n){var r,i;t instanceof qt?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(jt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(Gt(this,t),zt(this,n,e))},r)),r.j=i):(n||(t=Mt(t,Bt)),e.i=new qt(t,e.h))}function kt(e,t,n){e.i.set(t,n)}function Rt(e){return kt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Ot(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Mt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Ft),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Ft(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}xt.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Mt(t,Lt,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Mt(t,Lt,!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(Mt(n,"/"==n.charAt(0)?Vt:Pt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Mt(n,Ut)),e.join("")};var Lt=/[#\/\?@]/g,Pt=/[#\?:]/g,Vt=/[#\?]/g,Bt=/[#\?@]/g,Ut=/#/g;function qt(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function jt(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,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function Gt(e,t){jt(e),t=$t(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Kt(e,t){return jt(e),t=$t(e,t),e.g.has(t)}function zt(e,t,n){Gt(e,t),0<n.length&&(e.i=null,e.g.set($t(e,t),L(n)),e.h+=n.length)}function $t(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(b=qt.prototype).add=function(e,t){jt(this),this.i=null,e=$t(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},b.forEach=function(n,r){jt(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},b.ta=function(){jt(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},b.Z=function(t){jt(this);let n=[];if("string"==typeof t)Kt(this,t)&&(n=n.concat(this.g.get($t(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},b.set=function(e,t){return jt(this),this.i=null,Kt(this,e=$t(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},b.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},b.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],i=encodeURIComponent(String(r)),s=this.Z(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")};var Qt=class{constructor(e,t){this.g=e,this.map=t}};function Ht(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.Ka&&T.g.Ka()&&T.g.Ka().ec),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Wt(e){return e.h||e.g&&e.g.size>=e.j}function Yt(e){return e.h?1:e.g?e.g.size:0}function Xt(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Jt(e,t){e.g?e.g.add(t):e.h=t}function Zt(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function en(t){if(null!=t.h)return t.i.concat(t.h.F);if(null==t.g||0===t.g.size)return L(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.F);return e}}Ht.prototype.cancel=function(){if(this.i=en(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()}};var tn,nn=class{stringify(e){return T.JSON.stringify(e,void 0)}parse(e){return T.JSON.parse(e,void 0)}};function rn(){this.g=new nn}function sn(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function an(e){this.l=e.fc||null,this.j=e.ob||!1}function on(e,t){Te.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=un,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}O(an,nt),an.prototype.g=function(){return new on(this.l,this.j)},an.prototype.i=(tn={},function(){return tn}),O(on,Te);var un=0;function cn(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function hn(e){e.readyState=4,e.l=null,e.j=null,e.A=null,ln(e)}function ln(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(b=on.prototype).open=function(e,t){if(this.readyState!=un)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,ln(this)},b.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.F||T).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},b.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,hn(this)),this.readyState=un},b.$a=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,ln(this)),this.g&&(this.readyState=3,ln(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.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;cn(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},b.Xa=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?hn:ln)(this),3==this.readyState&&cn(this))},b.Za=function(e){this.g&&(this.response=this.responseText=e,hn(this))},b.Ya=function(e){this.g&&(this.response=e,hn(this))},b.ka=function(){this.g&&hn(this)},b.setRequestHeader=function(e,t){this.v.append(e,t)},b.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},b.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(on.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var dn=T.JSON.parse;function fn(e){Te.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=gn,this.L=this.M=!1}O(fn,Te);var gn="",mn=/^https?$/i,pn=["POST","PUT"];function yn(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,vn(e),_n(e)}function vn(e){e.F||(e.F=!0,Se(e,"complete"),Se(e,"error"))}function wn(e){if(e.h&&void 0!==E&&(!e.C[1]||4!=In(e)||2!=e.da()))if(e.v&&4==In(e))Pe(e.La,0,e);else if(Se(e,"readystatechange"),4==In(e)){e.h=!1;try{var t,n,r,i=e.da();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break e;default:s=!1}if((t=s)||((n=0===i)&&(!(r=String(e.I).match(St)[1]||null)&&T.self&&T.self.location&&(r=T.self.location.protocol.slice(0,-1)),n=!mn.test(r?r.toLowerCase():"")),t=n),t)Se(e,"complete"),Se(e,"success");else{e.m=6;try{var a=2<In(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.da()+"]",vn(e)}}finally{_n(e)}}}function _n(e,t){if(e.g){bn(e);const n=e.g,r=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||Se(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function bn(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(T.clearTimeout(e.A),e.A=null)}function In(e){return e.g?e.g.readyState:0}function En(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case gn:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Tn(e){let n="";return oe(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function Sn(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Tn(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):kt(e,t,n))}function xn(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Cn(e){this.Ga=0,this.j=[],this.l=new Ge,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=xn("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=xn("baseRetryDelayMs",5e3,e),this.hb=xn("retryDelaySeedMs",1e4,e),this.eb=xn("forwardChannelMaxRetries",2,e),this.xa=xn("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.dc||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Ht(e&&e.concurrentRequestLimit),this.Ja=new rn,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function An(e){if(Nn(e),3==e.H){var t=e.W++,n=Ct(e.I);if(kt(n,"SID",e.K),kt(n,"RID",t),kt(n,"TYPE","terminate"),On(e,n),(t=new ut(e,e.l,t)).L=2,t.v=Rt(Ct(n)),n=!1,T.navigator&&T.navigator.sendBeacon)try{n=T.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&T.Image&&((new Image).src=t.v,n=!0),n||(t.g=zn(t.l,null),t.g.ha(t.v)),t.G=Date.now(),vt(t)}Gn(e)}function Dn(e){e.g&&(Pn(e),e.g.cancel(),e.g=null)}function Nn(e){Dn(e),e.u&&(T.clearTimeout(e.u),e.u=null),Bn(e),e.i.cancel(),e.m&&("number"==typeof e.m&&T.clearTimeout(e.m),e.m=null)}function kn(e){var t;Wt(e.i)||e.m||(e.m=!0,t=e.Na,Ne||Oe(),ke||(Ne(),ke=!0),Re.add(t,e),e.C=0)}function Rn(e,t){var n=t?t.m:e.W++,r=Ct(e.I);kt(r,"SID",e.K),kt(r,"RID",n),kt(r,"AID",e.V),On(e,r),e.o&&e.s&&Sn(r,e.o,e.s),n=new ut(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=Mn(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),Jt(e.i,n),gt(n,r,t)}function On(e,n){e.na&&oe(e.na,function(e,t){kt(n,t,e)}),e.h&&Tt({},function(e,t){kt(n,t,e)})}function Mn(e,t,r){r=Math.min(e.j.length,r);var i=e.h?k(e.h.Va,e.h,e):null;e:{var s=e.j;let n=-1;for(;;){const u=["count="+r];-1==n?0<r?(n=s[0].g,u.push("ofs="+n)):n=0:u.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].g,o=s[t].map;if((a-=n)<0)n=Math.max(0,s[t].g-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Tt(e,function(e,t){let n=e;x(e)&&(n=Ce(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,u,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=u.join("&");break e}}}return e=e.j.splice(0,r),t.F=e,i}function Fn(e){var t;e.g||e.u||(e.ba=1,t=e.Ma,Ne||Oe(),ke||(Ne(),ke=!0),Re.add(t,e),e.A=0)}function Ln(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=Ze(k(e.Ma,e),qn(e,e.A)),e.A++,1)}function Pn(e){null!=e.B&&(T.clearTimeout(e.B),e.B=null)}function Vn(e){e.g=new ut(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=Ct(e.wa);kt(t,"RID","rpc"),kt(t,"SID",e.K),kt(t,"AID",e.V),kt(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&kt(t,"TO",e.qa),kt(t,"TYPE","xmlhttp"),On(e,t),e.o&&e.s&&Sn(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=Rt(Ct(t)),n.s=null,n.S=!0,mt(n,e)}function Bn(e){null!=e.v&&(T.clearTimeout(e.v),e.v=null)}function Un(e,t){var n,r,i,s=null;if(e.g==t){Bn(e),Pn(e),e.g=null;var a=2}else{if(!Xt(e.i,t))return;s=t.F,Zt(e.i,t),a=1}if(0!=e.H)if(t.i)1==a?(s=t.s?t.s.length:0,t=Date.now()-t.G,n=e.C,Se(a=Qe(),new Je(a,s)),kn(e)):Fn(e);else if(3==(n=t.o)||0==n&&0<t.ca||(1!=a||(i=t,Yt((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.j=i.F.concat(r.j),0):1==r.H||2==r.H||r.C>=(r.cb?0:r.eb)||(r.m=Ze(k(r.Na,r,i),qn(r,r.C)),r.C++,0))))&&(2!=a||!Ln(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:jn(e,5);break;case 4:jn(e,10);break;case 3:jn(e,6);break;default:jn(e,2)}}function qn(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function jn(e,t){var n,r;e.l.info("Error code "+t),2==t?(n=null,e.h&&(n=null),r=k(e.pb,e),n||(n=new xt("//www.google.com/images/cleardot.gif"),T.location&&"http"==T.location.protocol||At(n,"https"),Rt(n)),function(e,t){var n=new Ge;if(T.Image){const r=new Image;r.onload=R(sn,n,r,"TestLoadImage: loaded",!0,t),r.onerror=R(sn,n,r,"TestLoadImage: error",!1,t),r.onabort=R(sn,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=R(sn,n,r,"TestLoadImage: timeout",!1,t),T.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):Xe(2),e.H=0,e.h&&e.h.za(t),Gn(e),Nn(e)}function Gn(e){var t;e.H=0,e.ma=[],e.h&&(0==(t=en(e.i)).length&&0==e.j.length||(P(e.ma,t),P(e.ma,e.j),e.i.i.length=0,L(e.j),e.j.length=0),e.h.ya())}function Kn(e,t,n){var r,i,s=n instanceof xt?Ct(n):new xt(n);return""!=s.g?(t&&(s.g=t+"."+s.g),Dt(s,s.m)):(s=(r=T.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new xt(null),s&&At(i,s),t&&(i.g=t),r&&Dt(i,r),n&&(i.l=n),s=i),n=e.F,t=e.Da,n&&t&&kt(s,n,t),kt(s,"VER",e.ra),On(e,s),s}function zn(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new fn(new an({ob:!0})):new fn(e.va)).Oa(e.J),t}function $n(){}function Qn(){if($&&!(10<=Number(ee)))throw Error("Environmental error: no available transport.")}function Hn(e,t){Te.call(this),this.g=new Cn(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.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!U(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!U(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new Xn(this)}function Wn(e){st.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);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 Yn(){at.call(this),this.status=1}function Xn(e){this.g=e}function Jn(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function Zn(e,t,n){n=n||0;var r=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;i<16;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1];var i=e.g[2],s=e.g[3],a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+((a=t+(s^n&(i^s))+r[0]+3614090360&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function er(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(b=fn.prototype).Oa=function(e){this.M=e},b.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=(this.u||ht).g(),this.C=this.u?rt(this.u):rt(ht),this.g.onreadystatechange=k(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void yn(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);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()),i=T.FormData&&e instanceof T.FormData,0<=F(pn,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{bn(this),0<this.B&&((this.L=(o=this.g,$&&"number"==typeof o.timeout&&void 0!==o.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=k(this.ua,this)):this.A=Pe(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){yn(this,e)}var o},b.ua=function(){void 0!==E&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Se(this,"timeout"),this.abort(8))},b.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Se(this,"complete"),Se(this,"abort"),_n(this))},b.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),_n(this,!0)),fn.$.N.call(this)},b.La=function(){this.s||(this.G||this.v||this.l?wn(this):this.kb())},b.kb=function(){wn(this)},b.isActive=function(){return!!this.g},b.da=function(){try{return 2<In(this)?this.g.status:-1}catch(e){return-1}},b.ja=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},b.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),dn(t)}},b.Ia=function(){return this.m},b.Sa=function(){return"string"==typeof this.j?this.j:String(this.j)},(b=Cn.prototype).ra=8,b.H=1,b.Na=function(t){if(this.m)if(this.m=null,1==this.H){if(!t){this.W=Math.floor(1e5*Math.random()),t=this.W++;const s=new ut(this,this.l,t);let e=this.s;if(this.U&&(e?(e=ue(e),he(e,this.U)):e=this.U),null!==this.o||this.O||(s.I=e,e=null),this.P)e:{for(var n=0,r=0;r<this.j.length;r++){var i=this.j[r];if("__data__"in i.map&&"string"==typeof(i=i.map.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.j.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Mn(this,s,n),kt(r=Ct(this.I),"RID",t),kt(r,"CVER",22),this.F&&kt(r,"X-HTTP-Session-Id",this.F),On(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(Tn(e)))+"&"+n:this.o&&Sn(r,this.o,e)),Jt(this.i,s),this.bb&&kt(r,"TYPE","init"),this.P?(kt(r,"$req",n),kt(r,"SID","null"),s.aa=!0,gt(s,r,null)):gt(s,r,n),this.H=2}}else 3==this.H&&(t?Rn(this,t):0==this.j.length||Wt(this.i)||Rn(this))},b.Ma=function(){var e;this.u=null,Vn(this),this.ca&&!(this.M||null==this.g||this.S<=0)&&(e=2*this.S,this.l.info("BP detection timer enabled: "+e),this.B=Ze(k(this.jb,this),e))},b.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,Xe(10),Dn(this),Vn(this))},b.ib=function(){null!=this.v&&(this.v=null,Dn(this),Ln(this),Xe(19))},b.pb=function(e){e?(this.l.info("Successfully pinged google.com"),Xe(2)):(this.l.info("Failed to ping google.com"),Xe(1))},b.isActive=function(){return!!this.h&&this.h.isActive(this)},(b=$n.prototype).Ba=function(){},b.Aa=function(){},b.za=function(){},b.ya=function(){},b.isActive=function(){return!0},b.Va=function(){},Qn.prototype.g=function(e,t){return new Hn(e,t)},O(Hn,Te),Hn.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;Xe(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=Kn(e,null,e.Y),kn(e)},Hn.prototype.close=function(){An(this.g)},Hn.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Ce(e),e=t),n.j.push(new Qt(n.fb++,e)),3==n.H&&kn(n)},Hn.prototype.N=function(){this.g.h=null,delete this.j,An(this.g),delete this.g,Hn.$.N.call(this)},O(Wn,st),O(Yn,at),O(Xn,$n),Xn.prototype.Ba=function(){Se(this.g,"a")},Xn.prototype.Aa=function(e){Se(this.g,new Wn(e))},Xn.prototype.za=function(e){Se(this.g,new Yn)},Xn.prototype.ya=function(){Se(this.g,"b")},O(Jn,function(){this.blockSize=-1}),Jn.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Jn.prototype.j=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)Zn(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){Zn(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){Zn(this,r),i=0;break}}this.h=i,this.i+=t},Jn.prototype.l=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var n=8*this.i,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;t<4;++t)for(var r=0;r<32;r+=8)e[n++]=this.g[t]>>>r&255;return e};var tr={};function nr(e){return-128<=e&&e<128?(t=e,n=function(e){return new er([0|e],e<0?-1:0)},r=tr,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new er([0|e],e<0?-1:0);var t,n,r}function rr(e){if(isNaN(e)||!isFinite(e))return sr;if(e<0)return hr(rr(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=ir;return new er(t,0)}var ir=4294967296,sr=nr(0),ar=nr(1),or=nr(16777216);function ur(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function cr(e){return-1==e.h}function hr(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new er(n,~e.h).add(ar)}function lr(e,t){return e.add(hr(t))}function dr(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function fr(e,t){this.g=e,this.h=t}function gr(e,t){if(ur(t))throw Error("division by zero");if(ur(e))return new fr(sr,sr);if(cr(e))return t=gr(hr(e),t),new fr(hr(t.g),hr(t.h));if(cr(t))return t=gr(e,hr(t)),new fr(hr(t.g),t.h);if(30<e.g.length){if(cr(e)||cr(t))throw Error("slowDivide_ only works with positive integers.");for(var n=ar,r=t;r.X(e)<=0;)n=mr(n),r=mr(r);for(var i=pr(n,1),s=pr(r,1),r=pr(r,2),n=pr(n,2);!ur(r);){var a=s.add(r);a.X(e)<=0&&(i=i.add(n),s=a),r=pr(r,1),n=pr(n,1)}return t=lr(e,i.R(t)),new fr(i,t)}for(i=sr;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),a=(s=rr(n)).R(t);cr(a)||0<a.X(e);)a=(s=rr(n-=r)).R(t);ur(s)&&(s=ar),i=i.add(s),e=lr(e,a)}return new fr(i,e)}function mr(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new er(n,e.h)}function pr(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new er(i,e.h)}(b=er.prototype).ea=function(){if(cr(this))return-hr(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:ir+r)*t,t*=ir}return e},b.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(ur(this))return"0";if(cr(this))return"-"+hr(this).toString(e);for(var t=rr(Math.pow(e,6)),n=this,r="";;){var i=gr(n,t).g,s=((0<(n=lr(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(ur(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},b.D=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},b.X=function(e){return cr(e=lr(this,e))?-1:ur(e)?0:1},b.abs=function(){return cr(this)?hr(this):this},b.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),a=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new er(n,-2147483648&n[n.length-1]?-1:0)},b.R=function(e){if(ur(this)||ur(e))return sr;if(cr(this))return cr(e)?hr(this).R(hr(e)):hr(hr(this).R(e));if(cr(e))return hr(this.R(hr(e)));if(this.X(or)<0&&e.X(or)<0)return rr(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,a=65535&this.D(r),o=e.D(i)>>>16,u=65535&e.D(i);n[2*r+2*i]+=a*u,dr(n,2*r+2*i),n[2*r+2*i+1]+=s*u,dr(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,dr(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,dr(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new er(n,0)},b.gb=function(e){return gr(this,e).h},b.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new er(n,this.h&e.h)},b.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new er(n,this.h|e.h)},b.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new er(n,this.h^e.h)},Qn.prototype.createWebChannel=Qn.prototype.g,Hn.prototype.send=Hn.prototype.u,Hn.prototype.open=Hn.prototype.m,et.NO_ERROR=0,et.TIMEOUT=8,et.HTTP_ERROR=6,tt.COMPLETE="complete",(it.EventType=I).OPEN="a",I.CLOSE="b",I.ERROR="c",I.MESSAGE="d",Te.prototype.listen=Te.prototype.O,fn.prototype.listenOnce=fn.prototype.P,fn.prototype.getLastError=fn.prototype.Sa,fn.prototype.getLastErrorCode=fn.prototype.Ia,fn.prototype.getStatus=fn.prototype.da,fn.prototype.getResponseJson=fn.prototype.Wa,fn.prototype.getResponseText=fn.prototype.ja,fn.prototype.send=fn.prototype.ha,fn.prototype.setWithCredentials=fn.prototype.Oa,Jn.prototype.digest=Jn.prototype.l,Jn.prototype.update=Jn.prototype.j,er.prototype.multiply=er.prototype.R,er.prototype.modulo=er.prototype.gb,er.prototype.compare=er.prototype.X,er.prototype.toNumber=er.prototype.ea,er.prototype.getBits=er.prototype.D,er.fromNumber=rr,er.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if((n=n||10)<2||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return hr(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=rr(Math.pow(n,8)),i=sr,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n),i=a<8?(a=rr(Math.pow(n,a)),i.R(a).add(rr(o))):(i=i.R(r)).add(rr(o));return i};var yr,vr=Qe,wr=et,_r=tt,br=ze,Ir=10,Er=11,Tr=it,Sr=fn,xr=Jn,Cr=er;const Ar="@firebase/firestore";class Dr{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}}Dr.UNAUTHENTICATED=new Dr(null),Dr.GOOGLE_CREDENTIALS=new Dr("google-credentials-uid"),Dr.FIRST_PARTY=new Dr("first-party-uid"),Dr.MOCK_USER=new Dr("mock-user");let Nr="10.3.1";const kr=new class{constructor(e){this.name=e,this._logLevel=v,this._logHandler=_,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?y[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 Rr(){return kr.logLevel}function Or(e,...t){var n;kr.logLevel<=l.DEBUG&&(n=t.map(Lr),kr.debug(`Firestore (${Nr}): ${e}`,...n))}function Mr(e,...t){var n;kr.logLevel<=l.ERROR&&(n=t.map(Lr),kr.error(`Firestore (${Nr}): ${e}`,...n))}function Fr(e,...t){var n;kr.logLevel<=l.WARN&&(n=t.map(Lr),kr.warn(`Firestore (${Nr}): ${e}`,...n))}function Lr(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function Pr(e="Unexpected state"){var t=`FIRESTORE (${Nr}) INTERNAL ASSERTION FAILED: `+e;throw Mr(t),new Error(t)}function Vr(e){e||Pr()}const Br={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 Ur extends d{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class qr{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class jr{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Gr{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Dr.UNAUTHENTICATED))}shutdown(){}}class Kr{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 zr{constructor(e){this.t=e,this.currentUser=Dr.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new qr;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new qr,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{Or("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):(Or("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new qr))},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?(Or("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Vr("string"==typeof e.accessToken),new jr(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 Vr(null===e||"string"==typeof e),new Dr(e)}}class $r{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=Dr.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);var e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class Qr{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new $r(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(Dr.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Hr{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 Wr{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,n){const r=e=>{null!=e.error&&Or("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.R;return this.R=e.token,Or("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{Or("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):Or("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Vr("string"==typeof e.token),this.R=e.token,new Hr(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Yr{static V(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=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<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function Xr(e,t){return e<t?-1:t<e?1:0}function Jr(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function Zr(e){return e+"\0"}class ei{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new Ur(Br.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new Ur(Br.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new Ur(Br.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new Ur(Br.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return ei.fromMillis(Date.now())}static fromDate(e){return ei.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new ei(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Xr(this.nanoseconds,e.nanoseconds):Xr(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 ti{constructor(e){this.timestamp=e}static fromTimestamp(e){return new ti(e)}static min(){return new ti(new ei(0,0))}static max(){return new ti(new ei(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 ni{constructor(e,t,n){void 0===t?t=0:t>e.length&&Pr(),void 0===n?n=e.length-t:n>e.length-t&&Pr(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===ni.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof ni?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),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class ri extends ni{construct(e,t,n){return new ri(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 Ur(Br.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new ri(t)}static emptyPath(){return new ri([])}}const ii=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class si extends ni{construct(e,t,n){return new si(e,t,n)}static isValidIdentifier(e){return ii.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!si.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new si(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new Ur(Br.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new Ur(Br.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new Ur(Br.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new Ur(Br.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new si(t)}static emptyPath(){return new si([])}}class ai{constructor(e){this.path=e}static fromPath(e){return new ai(ri.fromString(e))}static fromName(e){return new ai(ri.fromString(e).popFirst(5))}static empty(){return new ai(ri.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===ri.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return ri.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ai(new ri(e.slice()))}}class oi{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function ui(e){return e.fields.find(e=>2===e.kind)}function ci(e){return e.fields.filter(e=>2!==e.kind)}oi.UNKNOWN_ID=-1;class hi{constructor(e,t){this.fieldPath=e,this.kind=t}}class li{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new li(0,gi.min())}}function di(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=ti.fromTimestamp(1e9===r?new ei(n+1,0):new ei(n,r));return new gi(r,ai.empty(),t)}function fi(e){return new gi(e.readTime,e.key,-1)}class gi{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new gi(ti.min(),ai.empty(),-1)}static max(){return new gi(ti.max(),ai.empty(),-1)}}function mi(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ai.comparator(e.documentKey,t.documentKey),0!==n?n:Xr(e.largestBatchId,t.largestBatchId))}const pi="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class yi{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function vi(e){if(e.code!==Br.FAILED_PRECONDITION||e.message!==pi)throw e;Or("LocalStore","Unexpectedly lost primary lease")}class wi{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,i){return this.callbackAttached&&Pr(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new wi((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof wi?t:wi.resolve(t)}catch(e){return wi.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):wi.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):wi.reject(t)}static resolve(n){return new wi((e,t)=>{e(n)})}static reject(n){return new wi((e,t)=>{t(n)})}static waitFor(e){return new wi((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=wi.resolve(!1);for(const n of e)t=t.next(e=>e?wi.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 wi((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;u(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new wi((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class _i{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.m=new qr,this.transaction.oncomplete=()=>{this.m.resolve()},this.transaction.onabort=()=>{e.error?this.m.reject(new Ei(n,e.error)):this.m.resolve()},this.transaction.onerror=e=>{var t=Ai(e.target.error);this.m.reject(new Ei(n,t))}}static open(e,t,n,r){try{return new _i(t,e.transaction(r,n))}catch(e){throw new Ei(t,e)}}get g(){return this.m.promise}abort(e){e&&this.m.reject(e),this.aborted||(Or("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}p(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Si(t)}}class bi{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===bi.D(u())&&Mr("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 Or("SimpleDb","Removing database:",e),xi(window.indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!function(){try{return"object"==typeof indexedDB}catch(e){return}}())return!1;if(bi.v())return!0;const e=u(),t=bi.D(e),n=0<t&&t<10,r=bi.F(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static v(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.M)}static O(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 F(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async N(s){return this.db||(Or("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new Ei(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new Ur(Br.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 Ur(Br.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 Ei(s,t))},i.onupgradeneeded=e=>{Or("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.B(t,i.transaction,e.oldVersion,this.version).next(()=>{Or("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.L&&(this.db.onversionchange=e=>this.L(e)),this.db}k(t){this.L=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.N(e);const t=_i.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.p(),e)).catch(e=>(t.abort(e),wi.reject(e))).toPromise();return s.catch(()=>{}),await t.g,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Or("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 Ii{constructor(e){this.q=e,this.K=!1,this.$=null}get isDone(){return this.K}get U(){return this.$}set cursor(e){this.q=e}done(){this.K=!0}W(e){this.$=e}delete(){return xi(this.q.delete())}}class Ei extends Ur{constructor(e,t){super(Br.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Ti(e){return"IndexedDbTransactionError"===e.name}class Si{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Or("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Or("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),xi(n)}add(e){return Or("SimpleDb","ADD",this.store.name,e,e),xi(this.store.add(e))}get(t){return xi(this.store.get(t)).next(e=>(Or("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Or("SimpleDb","DELETE",this.store.name,e),xi(this.store.delete(e))}count(){return Or("SimpleDb","COUNT",this.store.name),xi(this.store.count())}G(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.j(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new wi((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}H(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new wi((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}J(e,t){Or("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Y=!1;var r=this.cursor(n);return this.j(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.j(r,t)}X(i){const e=this.cursor({});return new wi((n,r)=>{e.onerror=e=>{var t=Ai(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}j(e,s){const a=[];return new wi((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new Ii(t),r=s(t.primaryKey,t.value,n);if(r instanceof wi){const e=r.catch(e=>(n.done(),wi.reject(e)));a.push(e)}n.isDone?i():null===n.U?t.continue():t.continue(n.U)}else i()}}).next(()=>wi.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.Y?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function xi(e){return new wi((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Ai(e.target.error);r(t)}})}let Ci=!1;function Ai(e){const t=bi.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 Ur("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 Ci||(Ci=!0,setTimeout(()=>{throw e},0)),e}}return e}class Di{constructor(e,t){this.asyncQueue=e,this.ee=t,this.task=null}start(){this.te(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}te(e){Or("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{Or("IndexBackiller",`Documents written: ${await this.ee.ne()}`)}catch(e){Ti(e)?Or("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await vi(e)}await this.te(6e4)})}}class Ni{constructor(e,t){this.localStore=e,this.persistence=t}async ne(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.re(e,t))}re(e,t){const n=new Set;let r=t,i=!0;return wi.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(Or("IndexBackiller",`Processing collection: ${t}`),this.ie(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}ie(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.se(n,e)).next(e=>(Or("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}se(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=fi(t);0<mi(n,r)&&(r=n)}),new gi(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ki{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.oe(e),this._e=e=>t.writeSequenceNumber(e))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this._e&&this._e(e),e}}function Ri(e){return null==e}function Oi(e){return 0===e&&1/e==-1/0}function Mi(e){return"number"==typeof e&&Number.isInteger(e)&&!Oi(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Fi(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Li(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Li(t)}function Li(e){return e+""}function Pi(t){const n=t.length;if(Vr(2<=n),2===n)return Vr(""===t.charAt(0)&&""===t.charAt(1)),ri.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=n-2,r=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>__PRIVATE_lastReasonableEscapeIndex)&&Pr(),t.charAt(n+1)){case"":var s=t.substring(a,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:Pr()}a=n+2}return new ri(r)}ki.ae=-1;const Vi=["userId","batchId"];function Bi(e,t){return[e,Fi(t)]}function Ui(e,t,n){return[e,Fi(t),n]}const qi={},ji=["prefixPath","collectionGroup","readTime","documentId"],Gi=["prefixPath","collectionGroup","documentId"],Ki=["collectionGroup","readTime","prefixPath","documentId"],zi=["canonicalId","targetId"],$i=["targetId","path"],Qi=["path","targetId"],Hi=["collectionId","parent"],Wi=["indexId","uid"],Yi=["uid","sequenceNumber"],Xi=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Ji=["indexId","uid","orderedDocumentKey"],Zi=["userId","collectionPath","documentId"],es=["userId","collectionPath","largestBatchId"],ts=["userId","collectionGroup","largestBatchId"],ns=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],rs=[...ns,"documentOverlays"],is=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ss=is,as=[...ss,"indexConfiguration","indexState","indexEntries"];class os extends yi{constructor(e,t){super(),this.ue=e,this.currentSequenceNumber=t}}function us(e,t){var n=e;return bi.O(n.ue,t)}function cs(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function hs(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function ls(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class ds{constructor(e,t){this.comparator=e,this.root=t||gs.EMPTY}insert(e,t){return new ds(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,gs.BLACK,null,null))}remove(e){return new ds(this.comparator,this.root.remove(e,this.comparator).copy(null,null,gs.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 fs(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new fs(this.root,e,this.comparator,!1)}getReverseIterator(){return new fs(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new fs(this.root,e,this.comparator,!0)}}class fs{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}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 gs{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:gs.RED,this.left=null!=r?r:gs.EMPTY,this.right=null!=i?i:gs.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new gs(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i: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 i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return gs.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 gs.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,gs.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,gs.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 Pr();if(this.right.isRed())throw Pr();var e=this.left.check();if(e!==this.right.check())throw Pr();return e+(this.isRed()?0:1)}}gs.EMPTY=null,gs.RED=!0,gs.BLACK=!1,gs.EMPTY=new class{constructor(){this.size=0}get key(){throw Pr()}get value(){throw Pr()}get color(){throw Pr()}get left(){throw Pr()}get right(){throw Pr()}copy(e,t,n,r,i){return this}insert(e,t,n){return new gs(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 ms{constructor(e){this.comparator=e,this.data=new ds(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 ps(this.data.getIterator())}getIteratorFrom(e){return new ps(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 ms))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 ms(this.comparator);return t.data=e,t}}class ps{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function ys(e){return e.hasNext()?e.getNext():void 0}class vs{constructor(e){(this.fields=e).sort(si.comparator)}static empty(){return new vs([])}unionWith(e){let t=new ms(si.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new vs(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Jr(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class ws extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class _s{constructor(e){this.binaryString=e}static fromBase64String(e){var t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new ws("Invalid base64 string: "+e):e}}(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 Xr(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}_s.EMPTY_BYTE_STRING=new _s("");const bs=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Is(t){if(Vr(!!t),"string"!=typeof t)return{seconds:Es(t.seconds),nanos:Es(t.nanos)};{let e=0;var n=bs.exec(t);Vr(!!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 Es(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Ts(e){return"string"==typeof e?_s.fromBase64String(e):_s.fromUint8Array(e)}function Ss(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 xs(e){var t=e.mapValue.fields.__previous_value__;return Ss(t)?xs(t):t}function Cs(e){var t=Is(e.mapValue.fields.__local_write_time__.timestampValue);return new ei(t.seconds,t.nanos)}class As{constructor(e,t,n,r,i,s,a,o,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=u}}class Ds{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Ds("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Ds&&e.projectId===this.projectId&&e.database===this.database}}const Ns={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},ks={nullValue:"NULL_VALUE"};function Rs(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?Ss(e)?4:zs(e)?9007199254740991:10:Pr()}function Os(e,t){if(e===t)return!0;var n,r,i=Rs(e);if(i!==Rs(t))return!1;switch(i){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Cs(e).isEqual(Cs(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;var n=Is(e.timestampValue),r=Is(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return r=t,Ts(e.bytesValue).isEqual(Ts(r.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return n=t,Es((r=e).geoPointValue.latitude)===Es(n.geoPointValue.latitude)&&Es(r.geoPointValue.longitude)===Es(n.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Es(e.integerValue)===Es(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Es(e.doubleValue),r=Es(t.doubleValue);return n===r?Oi(n)===Oi(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return Jr(e.arrayValue.values||[],t.arrayValue.values||[],Os);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(cs(n)!==cs(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Os(n[e],r[e])))return!1;return!0}(e,t);default:return Pr()}}function Ms(e,t){return void 0!==(e.values||[]).find(e=>Os(e,t))}function Fs(e,t){if(e===t)return 0;var n,r,i,s,a=Rs(e),o=Rs(t);if(a!==o)return Xr(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Xr(e.booleanValue,t.booleanValue);case 2:return r=t,i=Es((n=e).integerValue||n.doubleValue),s=Es(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Ls(e.timestampValue,t.timestampValue);case 4:return Ls(Cs(e),Cs(t));case 5:return Xr(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Ts(e),r=Ts(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=Xr(n[i],r[i]);if(0!==t)return t}return Xr(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=Xr(Es(n.latitude),Es(r.latitude)))?s:Xr(Es(n.longitude),Es(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Fs(n[i],r[i]);if(t)return t}return Xr(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Ns.mapValue&&t===Ns.mapValue)return 0;if(e===Ns.mapValue)return 1;if(t===Ns.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=Xr(r[o],s[o]);if(0!==t)return t;var a=Fs(n[r[o]],i[s[o]]);if(0!==a)return a}return Xr(r.length,s.length)}(e.mapValue,t.mapValue);default:throw Pr()}}function Ls(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Xr(e,t);var n=Is(e),r=Is(t),i=Xr(n.seconds,r.seconds);return 0!==i?i:Xr(n.nanos,r.nanos)}function Ps(e){return function s(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=Is(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return Ts(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return ai.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):Pr()}(e)}function Vs(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 qs(e){return e&&"nullValue"in e}function js(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Gs(e){return e&&"mapValue"in e}function Ks(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 hs(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Ks(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Ks(t.arrayValue.values[e]);return r}return Object.assign({},t)}function zs(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function $s(e,t){var n=Fs(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Qs(e,t){var n=Fs(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Hs{constructor(e){this.value=e}static empty(){return new Hs({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)],!Gs(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Ks(t)}setAll(e){let n=si.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Ks(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());Gs(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Os(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)];Gs(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){hs(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Hs(Ks(this.value))}}class Ws{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Ws(e,0,ti.min(),ti.min(),ti.min(),Hs.empty(),0)}static newFoundDocument(e,t,n,r){return new Ws(e,1,t,ti.min(),n,r,0)}static newNoDocument(e,t){return new Ws(e,2,t,ti.min(),ti.min(),Hs.empty(),0)}static newUnknownDocument(e,t){return new Ws(e,3,t,ti.min(),ti.min(),Hs.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(ti.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=Hs.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Hs.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ti.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 Ws&&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 Ws(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 Ys{constructor(e,t){this.position=e,this.inclusive=t}}function Xs(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?ai.comparator(ai.fromName(a.referenceValue),n.key):Fs(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Js(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(!Os(e.position[n],t.position[n]))return!1;return!0}class Zs{constructor(e,t="asc"){this.field=e,this.dir=t}}class ea{}class ta extends ea{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 ca(e,t,n):"array-contains"===t?new fa(e,n):"in"===t?new ga(e,n):"not-in"===t?new ma(e,n):"array-contains-any"===t?new pa(e,n):new ta(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?ha:la)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Fs(t,this.value)):null!==t&&Rs(this.value)===Rs(t)&&this.matchesComparison(Fs(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 Pr()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class na extends ea{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new na(e,t)}matches(t){return ra(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ce||(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){var e=this.le(e=>e.isInequality());return null!==e?e.field:null}le(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function ra(e){return"and"===e.op}function ia(e){return"or"===e.op}function sa(e){return aa(e)&&ra(e)}function aa(e){for(const t of e.filters)if(t instanceof na)return!1;return!0}function oa(e,t){var n=e.filters.concat(t);return na.create(n,e.op)}function ua(e){return e instanceof ta?`${(t=e).field.canonicalString()} ${t.op} ${Ps(t.value)}`:e instanceof na?(e=e).op.toString()+" {"+e.getFilters().map(ua).join(" ,")+"}":"Filter";var t}class ca extends ta{constructor(e,t,n){super(e,t,n),this.key=ai.fromName(n.referenceValue)}matches(e){var t=ai.comparator(e.key,this.key);return this.matchesComparison(t)}}class ha extends ta{constructor(e,t){super(e,"in",t),this.keys=da(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class la extends ta{constructor(e,t){super(e,"not-in",t),this.keys=da(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function da(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ai.fromName(e.referenceValue))}class fa extends ta{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Us(t)&&Ms(t.arrayValue,this.value)}}class ga extends ta{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Ms(this.value.arrayValue,t)}}class ma extends ta{constructor(e,t){super(e,"not-in",t)}matches(e){if(Ms(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Ms(this.value.arrayValue,t)}}class pa extends ta{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=>Ms(this.value.arrayValue,e))}}class ya{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.he=null}}function va(e,t=null,n=[],r=[],i=null,s=null,a=null){return new ya(e,t,n,r,i,s,a)}function wa(e){const t=e;if(null===t.he){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 ta)return e.field.canonicalString()+e.op.toString()+Ps(e.value);if(sa(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(","),Ri(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.he=e}return t.he}function _a(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(n=e.orderBy[i],r=t.orderBy[i],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 s=0;s<e.filters.length;s++)if(!function r(e,t){return e instanceof ta?(n=e,(s=t)instanceof ta&&n.op===s.op&&n.field.isEqual(s.field)&&Os(n.value,s.value)):e instanceof na?(i=t)instanceof na&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void Pr();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Js(e.startAt,t.startAt)&&Js(e.endAt,t.endAt)}function ba(e){return ai.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Ia(e,t){return e.filters.filter(e=>e instanceof ta&&e.field.isEqual(t))}function Ea(t,n,r){let i=ks,s=!0;for(const r of Ia(t,n)){let e=ks,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?ks:"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?Vs(Ds.empty(),ai.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:Pr();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=ks}$s({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=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];$s({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function Ta(t,n,r){let i=Ns,s=!0;for(const r of Ia(t,n)){let e=Ns,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?Vs(Ds.empty(),ai.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Ns:Pr(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Ns}0<Qs({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=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<Qs({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class Sa{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Pe=null,this.Ie=null,this.de=null,this.startAt,this.endAt}}function xa(e,t,n,r,i,s,a,o){return new Sa(e,t,n,r,i,s,a,o)}function Ca(e){return new Sa(e)}function Aa(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 Da(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function Na(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function ka(e){return null!==e.collectionGroup}function Ra(t){const n=t;if(null===n.Pe){n.Pe=[];const t=Na(n),e=Da(n);if(null!==t&&null===e)t.isKeyField()||n.Pe.push(new Zs(t)),n.Pe.push(new Zs(si.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.Pe.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.Pe.push(new Zs(si.keyField(),t))}}}return n.Pe}function Oa(e){const t=e;return t.Ie||(t.Ie=function(e,t){if("F"===e.limitType)return va(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new Zs(e.field,t)});var n=e.endAt?new Ys(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Ys(e.startAt.position,e.startAt.inclusive):null;return va(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,Ra(e))),t.Ie}function Ma(e,t){t.getFirstInequalityField(),Na(e);var n=e.filters.concat([t]);return new Sa(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Fa(e,t,n){return new Sa(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function La(e,t){return _a(Oa(e),Oa(t))&&e.limitType===t.limitType}function Pa(e){return`${wa(Oa(e))}|lt:${e.limitType}`}function Va(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=>ua(e)).join(", ")}]`),Ri(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})`}(Oa(e))}; limitType=${e.limitType})`}function Ba(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):ai.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of Ra(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return;return 1}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return;return 1}(e,t)&&(i=t,(!(t=e).startAt||(n=t.startAt,e=Ra(t),r=Xs(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=Ra(t),r=Xs(n,t,i),n.inclusive?0<=r:0<r)));var n,r,i,s,a}function Ua(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function qa(i){return(e,t)=>{let n=!1;for(const r of Ra(i)){const i=function(e,t,n){var r=e.field.isKeyField()?ai.comparator(t.key,n.key):function(e,t,n){var r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Fs(r,i):Pr()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Pr()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class ja{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 i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[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){hs(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return ls(this.inner)}size(){return this.innerSize}}const Ga=new ds(ai.comparator);const Ka=new ds(ai.comparator);function za(...e){let t=Ka;for(const n of e)t=t.insert(n.key,n);return t}function $a(e){let n=Ka;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function Qa(){return new ja(e=>e.toString(),(e,t)=>e.isEqual(t))}const Ha=new ds(ai.comparator),Wa=new ms(ai.comparator);function Ya(...e){let t=Wa;for(const n of e)t=t.add(n);return t}const Xa=new ms(Xr);function Ja(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Oi(t)?"-0":t}}function Za(e){return{integerValue:""+e}}function eo(e,t){return Mi(t)?Za(t):Ja(e,t)}class to{constructor(){this._=void 0}}function no(e,t){return e instanceof uo?Bs(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class ro extends to{}class io extends to{constructor(e){super(),this.elements=e}}function so(e,t){const n=ho(t);for(const t of e.elements)n.some(e=>Os(e,t))||n.push(t);return{arrayValue:{values:n}}}class ao extends to{constructor(e){super(),this.elements=e}}function oo(e,t){let n=ho(t);for(const t of e.elements)n=n.filter(e=>!Os(e,t));return{arrayValue:{values:n}}}class uo extends to{constructor(e,t){super(),this.serializer=e,this.Te=t}}function co(e){return Es(e.integerValue||e.doubleValue)}function ho(e){return Us(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class lo{constructor(e,t){this.field=e,this.transform=t}}class fo{constructor(e,t){this.version=e,this.transformResults=t}}class go{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new go}static exists(e){return new go(void 0,e)}static updateTime(e){return new go(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 mo(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class po{}function yo(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new xo(e.key,go.none()):new bo(e.key,e.data,go.none());{const i=e.data,s=Hs.empty();let t=new ms(si.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new Io(e.key,s,new vs(t.toArray()),go.none())}}function vo(e,t,n){e instanceof bo?function(e,t,n){const r=e.value.clone(),i=To(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Io?function(e,t,n){if(!mo(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=To(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Eo(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function wo(e,t,n,r){return e instanceof bo?function(e,t,n,r){if(!mo(e.precondition,t))return n;const i=e.value.clone(),s=So(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof Io?function(e,t,n,r){if(!mo(e.precondition,t))return n;const i=So(e.fieldTransforms,r,t),s=t.data;return s.setAll(Eo(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,mo(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function _o(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&&Jr(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof io&&t instanceof io||e instanceof ao&&t instanceof ao?Jr(e.elements,t.elements,Os):e instanceof uo&&t instanceof uo?Os(e.Te,t.Te):e instanceof ro&&t instanceof ro)}(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 bo extends po{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 Io extends po{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Eo(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 To(e,t,n){const r=new Map;Vr(e.length===n.length);for(let h=0;h<n.length;h++){var i=e[h],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,u=a,c=n[h],o instanceof io?so(o,u):o instanceof ao?oo(o,u):c))}var o,u,c;return r}function So(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,(i=e,s=h,a=t,u=o=void 0,i instanceof ro?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return(t=t&&Ss(t)?xs(t):t)&&(n.fields.__previous_value__=t),{mapValue:n}}(a,s):i instanceof io?so(i,s):i instanceof ao?oo(i,s):(o=no(i=i,s),u=co(o)+co(i.Te),Bs(o)&&Bs(i.Te)?Za(u):Ja(i.serializer,u))))}var i,s,a,o,u;return r}class xo extends po{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Co extends po{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Ao{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 i=this.mutations[r];i.key.isEqual(e.key)&&vo(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=wo(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=wo(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=Qa();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=yo(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(ti.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Ya())}isEqual(e){return this.batchId===e.batchId&&Jr(this.mutations,e.mutations,(e,t)=>_o(e,t))&&Jr(this.baseMutations,e.baseMutations,(e,t)=>_o(e,t))}}class Do{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Vr(e.mutations.length===n.length);let r=Ha;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new Do(e,t,n,r)}}class No{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 ko{constructor(e,t){this.count=e,this.unchangedNames=t}}function Ro(e){switch(e){default:return Pr();case Br.CANCELLED:case Br.UNKNOWN:case Br.DEADLINE_EXCEEDED:case Br.RESOURCE_EXHAUSTED:case Br.INTERNAL:case Br.UNAVAILABLE:case Br.UNAUTHENTICATED:return!1;case Br.INVALID_ARGUMENT:case Br.NOT_FOUND:case Br.ALREADY_EXISTS:case Br.PERMISSION_DENIED:case Br.FAILED_PRECONDITION:case Br.ABORTED:case Br.OUT_OF_RANGE:case Br.UNIMPLEMENTED:case Br.DATA_LOSS:return!0}}function Oo(e){if(void 0===e)return Mr("GRPC error has no .code"),Br.UNKNOWN;switch(e){case yr.OK:return Br.OK;case yr.CANCELLED:return Br.CANCELLED;case yr.UNKNOWN:return Br.UNKNOWN;case yr.DEADLINE_EXCEEDED:return Br.DEADLINE_EXCEEDED;case yr.RESOURCE_EXHAUSTED:return Br.RESOURCE_EXHAUSTED;case yr.INTERNAL:return Br.INTERNAL;case yr.UNAVAILABLE:return Br.UNAVAILABLE;case yr.UNAUTHENTICATED:return Br.UNAUTHENTICATED;case yr.INVALID_ARGUMENT:return Br.INVALID_ARGUMENT;case yr.NOT_FOUND:return Br.NOT_FOUND;case yr.ALREADY_EXISTS:return Br.ALREADY_EXISTS;case yr.PERMISSION_DENIED:return Br.PERMISSION_DENIED;case yr.FAILED_PRECONDITION:return Br.FAILED_PRECONDITION;case yr.ABORTED:return Br.ABORTED;case yr.OUT_OF_RANGE:return Br.OUT_OF_RANGE;case yr.UNIMPLEMENTED:return Br.UNIMPLEMENTED;case yr.DATA_LOSS:return Br.DATA_LOSS;default:return Pr()}}function Mo(){return new TextEncoder}(tt=yr=yr||{})[tt.OK=0]="OK",tt[tt.CANCELLED=1]="CANCELLED",tt[tt.UNKNOWN=2]="UNKNOWN",tt[tt.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",tt[tt.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",tt[tt.NOT_FOUND=5]="NOT_FOUND",tt[tt.ALREADY_EXISTS=6]="ALREADY_EXISTS",tt[tt.PERMISSION_DENIED=7]="PERMISSION_DENIED",tt[tt.UNAUTHENTICATED=16]="UNAUTHENTICATED",tt[tt.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",tt[tt.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",tt[tt.ABORTED=10]="ABORTED",tt[tt.OUT_OF_RANGE=11]="OUT_OF_RANGE",tt[tt.UNIMPLEMENTED=12]="UNIMPLEMENTED",tt[tt.INTERNAL=13]="INTERNAL",tt[tt.UNAVAILABLE=14]="UNAVAILABLE",tt[tt.DATA_LOSS=15]="DATA_LOSS";const Fo=new Cr([4294967295,4294967295],0);function Lo(e){const t=Mo().encode(e),n=new xr;return n.update(t),new Uint8Array(n.digest())}function Po(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new Cr([n,r],0),new Cr([i,s],0)]}class Vo{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new Bo(`Invalid padding: ${t}`);if(n<0)throw new Bo(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new Bo(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Bo(`Invalid padding when bitmap length is 0: ${t}`);this.Ae=8*e.length-t,this.Re=Cr.fromNumber(this.Ae)}Ve(e,t,n){let r=e.add(t.multiply(Cr.fromNumber(n)));return 1===r.compare(Fo)&&(r=new Cr([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Re).toNumber()}me(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ae)return!1;const t=Lo(e),[n,r]=Po(t);for(let i=0;i<this.hashCount;i++){const t=this.Ve(n,r,i);if(!this.me(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new Vo(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.Ae){const n=Lo(t),[r,i]=Po(n);for(let e=0;e<this.hashCount;e++){const n=this.Ve(r,i,e);this.fe(n)}}}fe(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class Bo extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Uo{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,qo.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Uo(ti.min(),r,new ds(Xr),Ga,Ya())}}class qo{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new qo(n,t,Ya(),Ya(),Ya())}}class jo{constructor(e,t,n,r){this.ge=e,this.removedTargetIds=t,this.key=n,this.pe=r}}class Go{constructor(e,t){this.targetId=e,this.ye=t}}class Ko{constructor(e,t,n=_s.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class zo{constructor(){this.we=0,this.Se=Ho(),this.be=_s.EMPTY_BYTE_STRING,this.De=!1,this.Ce=!0}get current(){return this.De}get resumeToken(){return this.be}get ve(){return 0!==this.we}get Fe(){return this.Ce}Me(e){0<e.approximateByteSize()&&(this.Ce=!0,this.be=e)}xe(){let n=Ya(),r=Ya(),i=Ya();return this.Se.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:Pr()}}),new qo(this.be,this.De,n,r,i)}Oe(){this.Ce=!1,this.Se=Ho()}Ne(e,t){this.Ce=!0,this.Se=this.Se.insert(e,t)}Be(e){this.Ce=!0,this.Se=this.Se.remove(e)}Le(){this.we+=1}ke(){--this.we}qe(){this.Ce=!0,this.De=!0}}class $o{constructor(e){this.Qe=e,this.Ke=new Map,this.$e=Ga,this.Ue=Qo(),this.We=new ds(Xr)}Ge(e){for(const t of e.ge)e.pe&&e.pe.isFoundDocument()?this.ze(t,e.pe):this.je(t,e.key,e.pe);for(const n of e.removedTargetIds)this.je(n,e.key,e.pe)}He(n){this.forEachTarget(n,e=>{const t=this.Je(e);switch(n.state){case 0:this.Ye(e)&&t.Me(n.resumeToken);break;case 1:t.ke(),t.ve||t.Oe(),t.Me(n.resumeToken);break;case 2:t.ke(),t.ve||this.removeTarget(e);break;case 3:this.Ye(e)&&(t.qe(),t.Me(n.resumeToken));break;case 4:this.Ye(e)&&(this.Ze(e),t.Me(n.resumeToken));break;default:Pr()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Ke.forEach((e,t)=>{this.Ye(t)&&n(t)})}Xe(e){const t=e.targetId,n=e.ye.count,r=this.et(t);if(r){var i=r.target;if(ba(i))if(0===n){const e=new ai(i.path);this.je(t,e,Ws.newNoDocument(e,ti.min()))}else Vr(1===n);else{const r=this.tt(t);if(r!==n){const n=this.nt(e),s=n?this.rt(n,e,r):1;if(0!==s){this.Ze(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.We=this.We.insert(t,e)}}}}}nt(e){var t=e.ye.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=Ts(n).toUint8Array()}catch(e){if(e instanceof ws)return Fr("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new Vo(i,r,t)}catch(e){return Fr(e instanceof Bo?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ae?null:s}rt(e,t,n){return t.ye.count===n-this.ot(e,t.targetId)?0:2}ot(n,r){const e=this.Qe.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Qe.st(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.je(r,e,null),i++)}),i}_t(r){const i=new Map;this.Ke.forEach((e,t)=>{var n=this.et(t);if(n){if(e.current&&ba(n.target)){const i=new ai(n.target.path);null!==this.$e.get(i)||this.ut(t,i)||this.je(t,i,Ws.newNoDocument(i,r))}e.Fe&&(i.set(t,e.xe()),e.Oe())}});let s=Ya();this.Ue.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.et(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.$e.forEach((e,t)=>t.setReadTime(r));var e=new Uo(r,i,this.We,this.$e,s);return this.$e=Ga,this.Ue=Qo(),this.We=new ds(Xr),e}ze(e,t){var n;this.Ye(e)&&(n=this.ut(e,t.key)?2:0,this.Je(e).Ne(t.key,n),this.$e=this.$e.insert(t.key,t),this.Ue=this.Ue.insert(t.key,this.ct(t.key).add(e)))}je(e,t,n){if(this.Ye(e)){const r=this.Je(e);this.ut(e,t)?r.Ne(t,1):r.Be(t),this.Ue=this.Ue.insert(t,this.ct(t).delete(e)),n&&(this.$e=this.$e.insert(t,n))}}removeTarget(e){this.Ke.delete(e)}tt(e){var t=this.Je(e).xe();return this.Qe.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Le(e){this.Je(e).Le()}Je(e){let t=this.Ke.get(e);return t||(t=new zo,this.Ke.set(e,t)),t}ct(e){let t=this.Ue.get(e);return t||(t=new ms(Xr),this.Ue=this.Ue.insert(e,t)),t}Ye(e){var t=null!==this.et(e);return t||Or("WatchChangeAggregator","Detected inactive target",e),t}et(e){var t=this.Ke.get(e);return t&&t.ve?null:this.Qe.lt(e)}Ze(t){this.Ke.set(t,new zo),this.Qe.getRemoteKeysForTarget(t).forEach(e=>{this.je(t,e,null)})}ut(e,t){return this.Qe.getRemoteKeysForTarget(e).has(t)}}function Qo(){return new ds(ai.comparator)}function Ho(){return new ds(ai.comparator)}const Wo={asc:"ASCENDING",desc:"DESCENDING"},Yo={"<":"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"},Xo={and:"AND",or:"OR"};class Jo{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Zo(e,t){return e.useProto3Json||Ri(t)?t:{value:t}}function eu(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function tu(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function nu(e){return Vr(!!e),ti.fromTimestamp((t=Is(e),new ei(t.seconds,t.nanos)));var t}function ru(e,t){return e=e,new ri(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function iu(e){var t=ri.fromString(e);return Vr(Iu(t)),t}function su(e,t){return ru(e.databaseId,t.path)}function au(e,t){const n=iu(t);if(n.get(1)!==e.databaseId.projectId)throw new Ur(Br.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 Ur(Br.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ai(hu(n))}function ou(e,t){return ru(e.databaseId,t)}function uu(e){var t=iu(e);return 4===t.length?ri.emptyPath():hu(t)}function cu(e){return new ri(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function hu(e){return Vr(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function lu(e,t,n){return{name:su(e,t),fields:n.value.mapValue.fields}}function du(e,t,n){const r=au(e,t.name),i=nu(t.updateTime),s=t.createTime?nu(t.createTime):ti.min(),a=new Hs({mapValue:{fields:t.fields}}),o=Ws.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function fu(e,t){let n;if(t instanceof bo)n={update:lu(e,t.key,t.value)};else if(t instanceof xo)n={delete:su(e,t.key)};else if(t instanceof Io)n={update:lu(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 Co))return Pr();n={verify:su(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof ro)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof io)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof ao)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof uo)return{fieldPath:e.field.canonicalString(),increment:t.Te};throw Pr()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,eu(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:Pr())),n;var r}function gu(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?go.updateTime(nu(i.updateTime)):void 0!==i.exists?go.exists(i.exists):go.none():go.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Vr("REQUEST_TIME"===t.setToServerValue),n=new ro;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new io(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new ao(e)}else"increment"in t?n=new uo(e,t.increment):Pr();var r=si.fromServerFormat(t.fieldPath);return new lo(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=au(t,e.update.name),a=new Hs({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new vs(t.map(e=>si.fromServerFormat(e)))}(e.updateMask);return new Io(s,a,t,n,r)}return new bo(s,a,n,r)}if(e.delete){const r=au(t,e.delete);return new xo(r,n)}if(e.verify){const r=au(t,e.verify);return new Co(r,n)}return Pr()}function mu(e,t){return{documents:[ou(e,t.path)]}}function pu(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=ou(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=ou(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length)return function n(e){return e instanceof ta?function(e){if("=="===e.op){if(js(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NAN"}};if(qs(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(js(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NOT_NAN"}};if(qs(e.value))return{unaryFilter:{field:_u(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:_u(e.field),op:vu(e.op),value:e.value}}}(e):e instanceof na?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:wu(e.op),filters:t}}}(e):Pr()}(na.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:_u(e.field),direction:(e=e.dir,Wo[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);i=Zo(e,t.limit);return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function yu(e){let t=uu(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0<a){Vr(1===a);const f=s.from[0];f.allDescendants?o=f.collectionId:t=t.child(f.collectionId)}let u=[];s.where&&(u=function(e){const t=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=bu(e.unaryFilter.field);return ta.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=bu(e.unaryFilter.field);return ta.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=bu(e.unaryFilter.field);return ta.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=bu(e.unaryFilter.field);return ta.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Pr()}}(e):void 0!==e.fieldFilter?function(e){return ta.create(bu(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 Pr()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return na.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Pr()}}(e.compositeFilter.op))}(e):Pr()}(e);return t instanceof na&&sa(t)?t.getFilters():[t]}(s.where));let c=[];s.orderBy&&(c=s.orderBy.map(e=>function(e){return new Zs(bu(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let h=null;s.limit&&(h=(e=s.limit,Ri(n="object"==typeof e?e.value:e)?null:n));let l=null;s.startAt&&(l=(r=s.startAt,i=!!r.before,n=r.values||[],new Ys(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new Ys(s,i))),xa(t,o,c,u,h,"F",l,d)}function vu(e){return Yo[e]}function wu(e){return Xo[e]}function _u(e){return{fieldPath:e.canonicalString()}}function bu(e){return si.fromServerFormat(e.fieldPath)}function Iu(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class Eu{constructor(e,t,n,r,i=ti.min(),s=ti.min(),a=_s.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new Eu(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Eu(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Eu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Eu(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Tu{constructor(e){this.ht=e}}function Su(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:xu(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:su(i=e.ht,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:eu(i,e.version.toTimestamp()),createTime:eu(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Cu(t.version)};else{if(!t.isUnknownDocument())return Pr();r.unknownDocument={path:n.path.toArray(),version:Cu(t.version)}}var i;return r}function xu(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Cu(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Au(e){var t=new ei(e.seconds,e.nanoseconds);return ti.fromTimestamp(t)}function Du(t,e){const n=(e.baseMutations||[]).map(e=>gu(t.ht,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>gu(t.ht,e)),i=ei.fromMillis(e.localWriteTimeMs);return new Ao(e.batchId,i,n,r)}function Nu(e){var t,n=Au(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?Au(e.lastLimboFreeSnapshotVersion):ti.min(),i=void 0!==e.query.documents?(Vr(1===(t=e.query).documents.length),Oa(Ca(uu(t.documents[0])))):Oa(yu(e.query));return new Eu(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,_s.fromBase64String(e.resumeToken))}function ku(e,t){var n=Cu(t.snapshotVersion),r=Cu(t.lastLimboFreeSnapshotVersion),i=(ba(t.target)?mu:pu)(e.ht,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:wa(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Ru(e){var t=yu({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Fa(t,t.limit,"L"):t}function Ou(e,t){return new No(t.largestBatchId,gu(e.ht,t.overlayMutation))}function Mu(e,t){var n=t.path.lastSegment();return[e,Fi(t.path.popLast()),n]}function Fu(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:Cu(r.readTime),documentKey:Fi(r.documentKey.path),largestBatchId:r.largestBatchId}}class Lu{getBundleMetadata(e,t){return Pu(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:Au(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return Pu(e).put({bundleId:(t=t).id,createTime:Cu(nu(t.createTime)),version:t.version})}getNamedQuery(e,t){return Vu(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:Ru(e.bundledQuery),readTime:Au(e.readTime)}})}saveNamedQuery(e,t){return Vu(e).put({name:(t=t).name,readTime:Cu(nu(t.readTime)),bundledQuery:t.bundledQuery})}}function Pu(e){return us(e,"bundles")}function Vu(e){return us(e,"namedQueries")}class Bu{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){var n=t.uid||"";return new Bu(e,n)}getOverlay(e,t){return Uu(e).get(Mu(this.userId,t)).next(e=>e?Ou(this.serializer,e):null)}getOverlays(e,t){const n=Qa();return wi.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new No(i,t);s.push(this.It(r,n))}),wi.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Fi(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(Uu(n).J("collectionPathOverlayIndex",t))}),wi.waitFor(i)}getOverlaysForCollection(e,t,n){const r=Qa(),i=Fi(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return Uu(e).G("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=Ou(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=Qa();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Uu(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=Ou(this.serializer,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}It(e,t){return Uu(e).put(function(e,t,n){var[,r,i]=Mu(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:fu(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function Uu(e){return us(e,"documentOverlays")}class qu{constructor(){}dt(e,t){this.Tt(e,t),t.Et()}Tt(e,t){var n,r;"nullValue"in e?this.At(t,5):"booleanValue"in e?(this.At(t,10),t.Rt(e.booleanValue?1:0)):"integerValue"in e?(this.At(t,15),t.Rt(Es(e.integerValue))):"doubleValue"in e?(n=Es(e.doubleValue),isNaN(n)?this.At(t,13):(this.At(t,15),Oi(n)?t.Rt(0):t.Rt(n))):"timestampValue"in e?(r=e.timestampValue,this.At(t,20),"string"==typeof r?t.Vt(r):(t.Vt(`${r.seconds||""}`),t.Rt(r.nanos||0))):"stringValue"in e?(this.ft(e.stringValue,t),this.gt(t)):"bytesValue"in e?(this.At(t,30),t.yt(Ts(e.bytesValue)),this.gt(t)):"referenceValue"in e?this.wt(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.At(t,45),t.Rt(r.latitude||0),t.Rt(r.longitude||0)):"mapValue"in e?zs(e)?this.At(t,Number.MAX_SAFE_INTEGER):(this.St(e.mapValue,t),this.gt(t)):"arrayValue"in e?(this.bt(e.arrayValue,t),this.gt(t)):Pr()}ft(e,t){this.At(t,25),this.Dt(e,t)}Dt(e,t){t.Vt(e)}St(e,t){var n=e.fields||{};this.At(t,55);for(const e of Object.keys(n))this.ft(e,t),this.Tt(n[e],t)}bt(e,t){var n=e.values||[];this.At(t,50);for(const e of n)this.Tt(e,t)}wt(e,t){this.At(t,37),ai.fromName(e).path.forEach(e=>{this.At(t,60),this.Dt(e,t)})}At(e,t){e.Rt(t)}gt(e){e.Rt(2)}}function ju(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)}qu.Ct=new qu;class Gu{constructor(){this.buffer=new Uint8Array(1024),this.position=0}vt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ft(n.value),n=t.next();this.Mt()}xt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ot(n.value),n=t.next();this.Nt()}Bt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ft(e);else if(e<2048)this.Ft(960|e>>>6),this.Ft(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ft(480|e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e);else{const e=t.codePointAt(0);this.Ft(240|e>>>18),this.Ft(128|63&e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e)}}this.Mt()}Lt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ot(e);else if(e<2048)this.Ot(960|e>>>6),this.Ot(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ot(480|e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e);else{const e=t.codePointAt(0);this.Ot(240|e>>>18),this.Ot(128|63&e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e)}}this.Nt()}kt(e){var t=this.qt(e),n=ju(t);this.Qt(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]}Kt(e){var t=this.qt(e),n=ju(t);this.Qt(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])}$t(){this.Ut(255),this.Ut(255)}Wt(){this.Gt(255),this.Gt(255)}reset(){this.position=0}seed(e){this.Qt(e.length),this.buffer.set(e,this.position),this.position+=e.length}zt(){return this.buffer.slice(0,this.position)}qt(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}Ft(e){var t=255&e;0==t?(this.Ut(0),this.Ut(255)):255==t?(this.Ut(255),this.Ut(0)):this.Ut(t)}Ot(e){var t=255&e;0==t?(this.Gt(0),this.Gt(255)):255==t?(this.Gt(255),this.Gt(0)):this.Gt(e)}Mt(){this.Ut(0),this.Ut(1)}Nt(){this.Gt(0),this.Gt(1)}Ut(e){this.Qt(1),this.buffer[this.position++]=e}Gt(e){this.Qt(1),this.buffer[this.position++]=~e}Qt(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 Ku{constructor(e){this.jt=e}yt(e){this.jt.vt(e)}Vt(e){this.jt.Bt(e)}Rt(e){this.jt.kt(e)}Et(){this.jt.$t()}}class zu{constructor(e){this.jt=e}yt(e){this.jt.xt(e)}Vt(e){this.jt.Lt(e)}Rt(e){this.jt.Kt(e)}Et(){this.jt.Wt()}}class $u{constructor(){this.jt=new Gu,this.Ht=new Ku(this.jt),this.Jt=new zu(this.jt)}seed(e){this.jt.seed(e)}Yt(e){return 0===e?this.Ht:this.Jt}zt(){return this.jt.zt()}reset(){this.jt.reset()}}class Qu{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Zt(){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 Qu(this.indexId,this.documentKey,this.arrayValue,n)}}function Hu(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Wu(e.arrayValue,t.arrayValue),0!==n?n:(n=Wu(e.directionalValue,t.directionalValue),0!==n?n:ai.comparator(e.documentKey,t.documentKey)))}function Wu(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 Yu{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Xt=e.orderBy,this.en=[];for(const t of e.filters){const e=t;e.isInequality()?this.tn=e:this.en.push(e)}}nn(e){Vr(e.collectionGroup===this.collectionId);var t=ui(e);if(void 0!==t&&!this.rn(t))return!1;const n=ci(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.rn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(void 0!==this.tn){if(!r.has(this.tn.field.canonicalString())){const e=n[i];if(!this.sn(this.tn,e)||!this.on(this.Xt[s++],e))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Xt.length||!this.on(this.Xt[s++],e))return!1}return!0}_n(){let e=new ms(si.comparator);const t=[];for(const n of this.en)n.field.isKeyField()||("array-contains"===n.op||"array-contains-any"===n.op?t.push(new hi(n.field,2)):e.has(n.field)||(e=e.add(n.field),t.push(new hi(n.field,0))));for(const r of this.Xt)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new hi(r.field,"asc"===r.dir?0:1)));return new oi(oi.UNKNOWN_ID,this.collectionId,t,li.empty())}rn(e){for(const t of this.en)if(this.sn(t,e))return!0;return!1}sn(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}on(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(Vr(e instanceof ta||e instanceof na),e instanceof ta)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=na.create(n,e.op);return r=rc(r),ec(r)?r:(Vr(r instanceof na),Vr(ra(r)),Vr(1<r.filters.length),r.filters.reduce((e,t)=>tc(e,t)))}(function t(n){var e;if(Vr(n instanceof ta||n instanceof na),n instanceof ta){if(n instanceof ga){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>ta.create(n.field,"==",e)))||[];return na.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return na.create(r,n.op)}(e));return Vr(ec(t)),Ju(t)||Zu(t)?[t]:t.getFilters()}function Ju(e){return e instanceof ta}function Zu(e){return e instanceof na&&sa(e)}function ec(e){return Ju(e)||Zu(e)||function(e){if(e instanceof na&&ia(e)){for(const t of e.getFilters())if(!Ju(t)&&!Zu(t))return!1;return!0}return!1}(e)}function tc(e,t){var n,r;return Vr(e instanceof ta||e instanceof na),Vr(t instanceof ta||t instanceof na),rc(e instanceof ta?t instanceof ta?(n=e,r=t,na.create([n,r],"and")):nc(e,t):t instanceof ta?nc(t,e):function(e,t){if(Vr(0<e.filters.length&&0<t.filters.length),ra(e)&&ra(t))return oa(e,t.getFilters());const n=ia(e)?e:t,r=ia(e)?t:e,i=n.filters.map(e=>tc(e,r));return na.create(i,"or")}(e,t))}function nc(t,e){if(ra(e))return oa(e,t.getFilters());var n=e.filters.map(e=>tc(t,e));return na.create(n,"or")}function rc(t){if(Vr(t instanceof ta||t instanceof na),t instanceof ta)return t;const e=t.getFilters();if(1===e.length)return rc(e[0]);if(aa(t))return t;const n=e.map(e=>rc(e)),r=[];return n.forEach(e=>{e instanceof ta?r.push(e):e instanceof na&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:na.create(r,t.op)}class ic{constructor(){this.an=new sc}addToCollectionParentIndex(e,t){return this.an.add(t),wi.resolve()}getCollectionParents(e,t){return wi.resolve(this.an.getEntries(t))}addFieldIndex(e,t){return wi.resolve()}deleteFieldIndex(e,t){return wi.resolve()}deleteAllFieldIndexes(e){return wi.resolve()}createTargetIndexes(e,t){return wi.resolve()}getDocumentsMatchingTarget(e,t){return wi.resolve(null)}getIndexType(e,t){return wi.resolve(0)}getFieldIndexes(e,t){return wi.resolve([])}getNextCollectionGroupToUpdate(e){return wi.resolve(null)}getMinOffset(e,t){return wi.resolve(gi.min())}getMinOffsetFromCollectionGroup(e,t){return wi.resolve(gi.min())}updateCollectionGroup(e,t,n){return wi.resolve()}updateIndexEntries(e,t){return wi.resolve()}}class sc{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new ms(ri.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}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 ms(ri.comparator)).toArray()}}const ac=new Uint8Array(0);class oc{constructor(e,t){this.user=e,this.databaseId=t,this.un=new sc,this.cn=new ja(e=>wa(e),(e,t)=>_a(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.un.has(t))return wi.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.un.add(t)});r={collectionId:n,parent:Fi(r)};return uc(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[Zr(n),""],!1,!0);return uc(e).G(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Pi(t.parent))}return r})}addFieldIndex(e,t){const n=hc(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=lc(e);return i.next(e=>{n.put(Fu(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=hc(e),r=lc(e),i=cc(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){const t=hc(e),n=cc(e),r=lc(e);return t.J().next(()=>n.J()).next(()=>r.J())}createTargetIndexes(n,e){return wi.forEach(this.ln(e),t=>this.getIndexType(n,t).next(e=>{if(0===e||1===e){const e=new Yu(t);return this.addFieldIndex(n,e._n())}}))}getDocumentsMatchingTarget(e,h){const l=cc(e);let d=!0;const n=new Map;return wi.forEach(this.ln(h),t=>this.hn(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let c=Ya();const d=[];return wi.forEach(n,(e,t)=>{var n;Or("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${wa(h)}`);var r=function(e,t){var n=ui(t);if(void 0===n)return null;for(const t of Ia(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),i=function(e,t){const n=new Map;for(const r of ci(t))for(const t of Ia(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 i of ci(t)){const t=(0===i.kind?Ea:Ta)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Ys(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of ci(t)){const t=(0===i.kind?Ta:Ea)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Ys(n,r)}(t,e),o=this.Pn(e,t,s),u=this.Pn(e,t,a),i=this.In(e,t,i),i=this.dn(e.indexId,r,o,s.inclusive,u,a.inclusive,i);return wi.forEach(i,e=>l.H(e,h.limit).next(e=>{e.forEach(e=>{var t=ai.fromSegments(e.documentKey);c.has(t)||(c=c.add(t),d.push(t))})}))}).next(()=>d)}return wi.resolve(null)})}ln(t){let e=this.cn.get(t);return e||(e=0===t.filters.length?[t]:Xu(na.create(t.filters,"and")).map(e=>va(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.cn.set(t,e),e)}dn(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),u=o/(null!=e?e.length:1),c=[];for(let h=0;h<o;++h){const o=e?this.Tn(e[h/u]):ac,l=this.En(t,o,n[h%u],r),d=this.An(t,o,i[h%u],s),f=a.map(e=>this.En(t,o,e,!0));c.push(...this.createRange(l,d,f))}return c}En(e,t,n,r){const i=new Qu(e,ai.empty(),t,n);return r?i:i.Zt()}An(e,t,n,r){const i=new Qu(e,ai.empty(),t,n);return r?i.Zt():i}hn(e,t){const r=new Yu(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.nn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.ln(t);return wi.forEach(r,t=>this.hn(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new ms(si.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(()=>function(e){return null!==e.limit}(t)&&1<r.length&&2===n?1:n)}Rn(e,t){const n=new $u;for(const i of ci(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Yt(i.kind);qu.Ct.dt(e,r)}return n.zt()}Tn(e){const t=new $u;return qu.Ct.dt(e,t.Yt(0)),t.zt()}Vn(e,t){const n=new $u;return qu.Ct.dt(Vs(this.databaseId,t),n.Yt(0===(r=ci(e)).length?0:r[r.length-1].kind)),n.zt();var r}In(e,t,n){if(null===n)return[];let r=[];r.push(new $u);let i=0;for(const s of ci(e)){const e=n[i++];for(const n of r)if(this.mn(t,s.fieldPath)&&Us(e))r=this.fn(r,s,e);else{const t=n.Yt(s.kind);qu.Ct.dt(e,t)}}return this.gn(r)}Pn(e,t,n){return this.In(e,t,n.position)}gn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].zt();return t}fn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new $u;r.seed(n.zt()),qu.Ct.dt(e,r.Yt(t.kind)),i.push(r)}return i}mn(e,t){return!!e.filters.find(e=>e instanceof ta&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=hc(e),r=lc(e);return(t?n.G("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.G()).next(e=>{const s=[];return wi.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new li(e.sequenceNumber,new gi(Au(e.readTime),new ai(Pi(e.documentKey)),e.largestBatchId)):li.empty(),r=t.fields.map(([e,t])=>new hi(si.fromServerFormat(e),t)),new oi(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}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:Xr(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=hc(e),s=lc(e);return this.pn(e).next(t=>i.G("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>wi.forEach(e,e=>s.put(Fu(e.indexId,this.user,t,r)))))}updateIndexEntries(i,e){const n=new Map;return wi.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?wi.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),wi.forEach(e,n=>this.yn(i,t,n).next(e=>{var t=this.wn(r,n);return e.isEqual(t)?wi.resolve():this.Sn(i,r,n,e,t)}))))})}bn(e,t,n,r){return cc(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.Vn(n,t.key),documentKey:t.key.path.toArray()})}Dn(e,t,n,r){return cc(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.Vn(n,t.key),t.key.path.toArray()])}yn(e,n,r){const t=cc(e);let i=new ms(Hu);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.Vn(r,n)])},(e,t)=>{i=i.add(new Qu(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}wn(e,t){let n=new ms(Hu);var r=this.Rn(t,e);if(null==r)return n;const i=ui(t);if(null!=i){var s=e.data.field(i.fieldPath);if(Us(s))for(const i of s.arrayValue.values||[])n=n.add(new Qu(t.indexId,e.key,this.Tn(i),r))}else n=n.add(new Qu(t.indexId,e.key,ac,r));return n}Sn(t,n,r,e,i){Or("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,t,n,r,i){var s=e.getIterator(),a=t.getIterator();let o=ys(s),u=ys(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=ys(a)):t?(i(o),o=ys(s)):(o=ys(s),u=ys(a))}}(e,i,Hu,e=>{s.push(this.bn(t,n,r,e))},e=>{s.push(this.Dn(t,n,r,e))}),wi.waitFor(s)}pn(e){let r=1;return lc(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)=>Hu(e,t)).filter((e,t,n)=>!t||0!==Hu(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=Hu(i,e),s=Hu(i,t);if(0===n)r[0]=e.Zt();else if(0<n&&s<0)r.push(i),r.push(i.Zt());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2){if(this.Cn(r[a],r[a+1]))return[];const t=[r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,ac,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,ac,[]];i.push(IDBKeyRange.bound(t,n))}return i}Cn(e,t){return 0<Hu(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(dc)}getMinOffset(t,e){return wi.mapArray(this.ln(e),e=>this.hn(t,e).next(e=>e||Pr())).next(dc)}}function uc(e){return us(e,"collectionParents")}function cc(e){return us(e,"indexEntries")}function hc(e){return us(e,"indexConfiguration")}function lc(e){return us(e,"indexState")}function dc(e){Vr(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;mi(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new gi(t.readTime,t.documentKey,n)}const fc={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class gc{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new gc(e,gc.DEFAULT_COLLECTION_PERCENTILE,gc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function mc(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const u=r.Z({range:a},(e,t,n)=>(o++,n.delete()));s.push(u.next(()=>{Vr(1===o)}));const c=[];for(const e of n.mutations){const r=Ui(t,e.key.path,n.batchId);s.push(i.delete(r)),c.push(e.key)}return wi.waitFor(s).next(()=>c)}function pc(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 Pr();t=e.noDocument}return JSON.stringify(t).length}gc.DEFAULT_COLLECTION_PERCENTILE=10,gc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,gc.DEFAULT=new gc(41943040,gc.DEFAULT_COLLECTION_PERCENTILE,gc.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),gc.DISABLED=new gc(-1,0,0);class yc{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.vn={}}static Pt(e,t,n,r){Vr(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new yc(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return wc(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(h,l,d,f){const g=_c(h),m=wc(h);return m.add({}).next(e=>{Vr("number"==typeof e);const t=new Ao(e,l,d,f),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>fu(i.ht,e)),u=a.mutations.map(e=>fu(i.ht,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:u}),r=[];var i,s,a,o,u;let c=new ms((e,t)=>Xr(e.canonicalString(),t.canonicalString()));for(const h of f){const l=Ui(this.userId,h.key.path,e);c=c.add(h.key.path.popLast()),r.push(m.put(n)),r.push(g.put(l,qi))}return c.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(h,e))}),h.addOnCommittedListener(()=>{this.vn[e]=t.keys()}),wi.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return wc(e).get(t).next(e=>e?(Vr(e.userId===this.userId),Du(this.serializer,e)):null)}Fn(e,n){return this.vn[n]?wi.resolve(this.vn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.vn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return wc(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Vr(t.batchId>=r),i=Du(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return wc(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 wc(e).G("userMutationsIndex",t).next(e=>e.map(e=>Du(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=Bi(this.userId,o.path),t=IDBKeyRange.lowerBound(e),u=[];return _c(a).Z({range:t},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);if(r===this.userId&&o.path.isEqual(i))return wc(a).get(s).next(e=>{if(!e)throw Pr();Vr(e.userId===this.userId),u.push(Du(this.serializer,e))});n.done()}).next(()=>u)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new ms(Xr);const n=[];return e.forEach(a=>{var e=Bi(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=_c(t).Z({range:e},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),wi.waitFor(n).next(()=>this.Mn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=Bi(this.userId,a),r=IDBKeyRange.lowerBound(n);let u=new ms(Xr);return _c(e).Z({range:r},(e,t,n)=>{var[r,i,s]=e,i=Pi(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(u=u.add(s)):n.done()}).next(()=>this.Mn(e,u))}Mn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(wc(t).get(e).next(e=>{if(null===e)throw Pr();Vr(e.userId===this.userId),n.push(Du(this.serializer,e))}))}),wi.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return mc(t.ue,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.xn(n.batchId)}),wi.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}xn(e){delete this.vn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return wi.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return _c(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Pi(e[1]);r.push(t)}else n.done()}).next(()=>{Vr(0===r.length)})})}containsKey(e,t){return vc(e,this.userId,t)}On(e){return bc(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function vc(e,s,t){const n=Bi(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return _c(e).Z({range:r,Y:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function wc(e){return us(e,"mutations")}function _c(e){return us(e,"documentMutations")}function bc(e){return us(e,"mutationQueues")}class Ic{constructor(e){this.Nn=e}next(){return this.Nn+=2,this.Nn}static Bn(){return new Ic(0)}static Ln(){return new Ic(-1)}}class Ec{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.kn(n).next(e=>{const t=new Ic(e.highestTargetId);return e.highestTargetId=t.next(),this.qn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.kn(e).next(e=>ti.fromTimestamp(new ei(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.kn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.kn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.qn(t,e)))}addTargetData(t,n){return this.Qn(t,n).next(()=>this.kn(t).next(e=>(e.targetCount+=1,this.Kn(n,e),this.qn(t,e))))}updateTargetData(e,t){return this.Qn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>Tc(t).delete(e.targetId)).next(()=>this.kn(t)).next(e=>(Vr(0<e.targetCount),--e.targetCount,this.qn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return Tc(r).Z((e,t)=>{var n=Nu(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>wi.waitFor(o)).next(()=>a)}forEachTarget(e,r){return Tc(e).Z((e,t)=>{var n=Nu(t);r(n)})}kn(e){return Sc(e).get("targetGlobalKey").next(e=>(Vr(null!==e),e))}qn(e,t){return Sc(e).put("targetGlobalKey",t)}Qn(e,t){return Tc(e).put(ku(this.serializer,t))}Kn(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.kn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=wa(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return Tc(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=Nu(t);_a(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=xc(n);return e.forEach(e=>{var t=Fi(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),wi.waitFor(i)}removeMatchingKeys(n,e,r){const i=xc(n);return wi.forEach(e,e=>{var t=Fi(e.path);return wi.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=xc(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=xc(e);let i=Ya();return r.Z({range:n,Y:!0},(e,t,n)=>{var r=Pi(e[1]),r=new ai(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Fi(t.path),n=IDBKeyRange.bound([n],[Zr(n)],!1,!0);let r=0;return xc(e).Z({index:"documentTargetsIndex",Y:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}lt(e,t){return Tc(e).get(t).next(e=>e?Nu(e):null)}}function Tc(e){return us(e,"targets")}function Sc(e){return us(e,"targetGlobal")}function xc(e){return us(e,"targetDocuments")}function Cc([e,t],[n,r]){var i=Xr(e,n);return 0===i?Xr(t,r):i}class Ac{constructor(e){this.$n=e,this.buffer=new ms(Cc),this.Un=0}Wn(){return++this.Un}Gn(e){var t=[e,this.Wn()];if(this.buffer.size<this.$n)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Cc(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Dc{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.zn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.jn(6e4)}stop(){this.zn&&(this.zn.cancel(),this.zn=null)}get started(){return null!==this.zn}jn(e){Or("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.zn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.zn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Ti(e)?Or("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await vi(e)}await this.jn(3e5)})}}class Nc{constructor(e,t){this.Hn=e,this.params=t}calculateTargetCount(e,t){return this.Hn.Jn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return wi.resolve(ki.ae);const n=new Ac(t);return this.Hn.forEachTarget(e,e=>n.Gn(e.sequenceNumber)).next(()=>this.Hn.Yn(e,e=>n.Gn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Hn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Hn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Or("LruGarbageCollector","Garbage collection skipped; disabled"),wi.resolve(fc)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Or("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),fc):this.Zn(t,n))}getCacheSize(e){return this.Hn.getCacheSize(e)}Zn(t,n){let r,i,s,a,o,u,c;const h=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(Or("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,i))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,u=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(c=Date.now(),Rr()<=l.DEBUG&&Or("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-h}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(u-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-u)+"ms\n"+`Total Duration: ${c-h}ms`),wi.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class kc{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new Nc(e,t))}Jn(e){const n=this.Xn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Xn(e){let t=0;return this.Yn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Yn(e,n){return this.er(e,(e,t)=>n(t))}addReference(e,t,n){return Rc(e,n)}removeReference(e,t,n){return Rc(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return Rc(e,t)}tr(t,n){let r=!1;return bc(t).X(e=>vc(t,e,n).next(e=>(e&&(r=!0),wi.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.er(n,(t,e)=>{if(e<=r){const r=this.tr(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,ti.min()),xc(n).delete(function(e){return[0,Fi(e.path)]}(t))))});s.push(r)}}).next(()=>wi.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return Rc(e,t)}er(e,r){const t=xc(e);let i,s=ki.ae;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==ki.ae&&r(new ai(Pi(i)),s),s=n,i=t):s=ki.ae}).next(()=>{s!==ki.ae&&r(new ai(Pi(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function Rc(e,t){return xc(e).put((e=e.currentSequenceNumber,{targetId:0,path:Fi(t.path),sequenceNumber:e}))}class Oc{constructor(){this.changes=new ja(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,Ws.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?wi.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 Mc{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return Vc(e).put(n)}removeEntry(e,t,n){return Vc(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],xu(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.nr(t,e)))}getEntry(e,n){let r=Ws.newInvalidDocument(n);return Vc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Bc(n))},(e,t)=>{r=this.rr(n,t)}).next(()=>r)}ir(e,n){let r={size:0,document:Ws.newInvalidDocument(n)};return Vc(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(Bc(n))},(e,t)=>{r={document:this.rr(n,t),size:pc(t)}}).next(()=>r)}getEntries(e,t){let r=Ga;return this.sr(e,t,(e,t)=>{var n=this.rr(e,t);r=r.insert(e,n)}).next(()=>r)}_r(e,t){let r=Ga,i=new ds(ai.comparator);return this.sr(e,t,(e,t)=>{var n=this.rr(e,t);r=r.insert(e,n),i=i.insert(e,pc(t))}).next(()=>({documents:r,ar:i}))}sr(e,t,i){if(t.isEmpty())return wi.resolve();let n=new ms(qc);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(Bc(n.first()),Bc(n.last())),s=n.getIterator();let a=s.getNext();return Vc(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ai.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&qc(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.W(Bc(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,n,t,r,i){const s=n.path,a=[s.popLast().toArray(),s.lastSegment(),xu(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return Vc(e).G(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let t=Ga;for(const i of e){const e=this.rr(ai.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Ba(n,e)||r.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=Ga;var r=Uc(t,n),a=Uc(t,gi.max());return Vc(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.rr(ai.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new Lc(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return Pc(e).get("remoteDocumentGlobalKey").next(e=>(Vr(!!e),e))}nr(e,t){return Pc(e).put("remoteDocumentGlobalKey",t)}rr(e,t){if(t){const e=function(e,t){let n;if(t.document)n=du(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ai.fromSegments(t.noDocument.path),i=Au(t.noDocument.readTime);n=Ws.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Pr();{const e=ai.fromSegments(t.unknownDocument.path),s=Au(t.unknownDocument.version);n=Ws.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new ei(t[0],t[1]),ti.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(ti.min()))return e}return Ws.newInvalidDocument(e)}}function Fc(e){return new Mc(e)}class Lc extends Oc{constructor(e,t){super(),this.ur=e,this.trackRemovals=t,this.cr=new ja(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,u=new ms((e,t)=>Xr(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.cr.get(e);if(a.push(this.ur.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=Su(this.ur.serializer,t);u=u.add(e.path.popLast());var i=pc(r);o+=i-n.size,a.push(this.ur.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=Su(this.ur.serializer,t.convertToNoDocument(ti.min()));a.push(this.ur.addEntry(s,e,o))}}),u.forEach(e=>{a.push(this.ur.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.ur.updateMetadata(s,o)),wi.waitFor(a)}getFromCache(e,t){return this.ur.ir(e,t).next(e=>(this.cr.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.ur._r(e,t).next(({documents:n,ar:e})=>(e.forEach((e,t)=>{this.cr.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function Pc(e){return us(e,"remoteDocumentGlobal")}function Vc(e){return us(e,"remoteDocumentsV14")}function Bc(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function Uc(e,t){const n=t.documentKey.path.toArray();return[e,xu(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function qc(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=Xr(n[s],r[s]),i)return i;return i=Xr(n.length,r.length),i||(i=Xr(n[n.length-2],r[r.length-2]),i||Xr(n[n.length-1],r[r.length-1]))}class jc{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class Gc{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&&wo(r.mutation,e,vs.empty(),ei.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,Ya()).next(()=>e))}getLocalViewOfDocuments(e,t,n=Ya()){const r=Qa();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=za();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=Qa();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Ya()))}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,i){let s=Ga;const a=Qa(),o=Qa();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof Io)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),wo(n.mutation,t,n.mutation.getFieldMask(),ei.now())):a.set(t.key,vs.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new jc(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=Qa();let u=new ds((e,t)=>e-t),c=Ya();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||vs.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(u.get(r.batchId)||Ya()).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,i=Qa();r.forEach(e=>{var t;c.has(e)||(null!==(t=yo(a.get(e),o.get(e)))&&i.set(e,t),c=c.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return wi.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n,r){return i=t,ai.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):ka(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r);var i}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):wi.resolve(Qa());let r=-1,i=n;return e.next(e=>wi.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?wi.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,Ya())).next(e=>({batchId:r,changes:$a(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ai(t)).next(e=>{let t=za();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s,a){const o=i.collectionGroup;let u=za();return this.indexManager.getCollectionParents(r,o).next(e=>wi.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new Sa(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s,a).next(e=>{e.forEach((e,t)=>{u=u.insert(e,t)})})}).next(()=>u))}getDocumentsMatchingCollectionQuery(t,s,n,r){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,a,r))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Ws.newInvalidDocument(n)))});let i=za();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&wo(n.mutation,t,vs.empty(),ei.now()),Ba(s,t)&&(i=i.insert(e,t))}),i})}}class Kc{constructor(e){this.serializer=e,this.lr=new Map,this.hr=new Map}getBundleMetadata(e,t){return wi.resolve(this.lr.get(t))}saveBundleMetadata(e,t){return this.lr.set(t.id,{id:t.id,version:t.version,createTime:nu(t.createTime)}),wi.resolve()}getNamedQuery(e,t){return wi.resolve(this.hr.get(t))}saveNamedQuery(e,t){return this.hr.set(t.name,{name:(t=t).name,query:Ru(t.bundledQuery),readTime:nu(t.readTime)}),wi.resolve()}}class zc{constructor(){this.overlays=new ds(ai.comparator),this.Pr=new Map}getOverlay(e,t){return wi.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Qa();return wi.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.It(n,r,t)}),wi.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.Pr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Pr.delete(n)),wi.resolve()}getOverlaysForCollection(e,t,n){const r=Qa(),i=t.length+1,s=new ai(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return wi.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new ds((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=Qa(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=Qa(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return wi.resolve(a)}It(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.Pr.get(r.largestBatchId).delete(n.key);this.Pr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new No(t,n));let i=this.Pr.get(t);void 0===i&&(i=Ya(),this.Pr.set(t,i)),this.Pr.set(t,i.add(n.key))}}class $c{constructor(){this.Ir=new ms(Qc.dr),this.Tr=new ms(Qc.Er)}isEmpty(){return this.Ir.isEmpty()}addReference(e,t){var n=new Qc(e,t);this.Ir=this.Ir.add(n),this.Tr=this.Tr.add(n)}Ar(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Rr(new Qc(e,t))}Vr(e,t){e.forEach(e=>this.removeReference(e,t))}mr(e){const t=new ai(new ri([])),n=new Qc(t,e),r=new Qc(t,e+1),i=[];return this.Tr.forEachInRange([n,r],e=>{this.Rr(e),i.push(e.key)}),i}gr(){this.Ir.forEach(e=>this.Rr(e))}Rr(e){this.Ir=this.Ir.delete(e),this.Tr=this.Tr.delete(e)}pr(e){var t=new ai(new ri([])),n=new Qc(t,e),t=new Qc(t,e+1);let r=Ya();return this.Tr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new Qc(e,0),t=this.Ir.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class Qc{constructor(e,t){this.key=e,this.yr=t}static dr(e,t){return ai.comparator(e.key,t.key)||Xr(e.yr,t.yr)}static Er(e,t){return Xr(e.yr,t.yr)||ai.comparator(e.key,t.key)}}class Hc{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.wr=1,this.Sr=new ms(Qc.dr)}checkEmpty(e){return wi.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.wr;this.wr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new Ao(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.Sr=this.Sr.add(new Qc(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return wi.resolve(s)}lookupMutationBatch(e,t){return wi.resolve(this.br(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.Dr(t+1),n=n<0?0:n;return wi.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return wi.resolve(0===this.mutationQueue.length?-1:this.wr-1)}getAllMutationBatches(e){return wi.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new Qc(t,0),r=new Qc(t,Number.POSITIVE_INFINITY),i=[];return this.Sr.forEachInRange([n,r],e=>{var t=this.br(e.yr);i.push(t)}),wi.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new ms(Xr);return t.forEach(e=>{var t=new Qc(e,0),n=new Qc(e,Number.POSITIVE_INFINITY);this.Sr.forEachInRange([t,n],e=>{r=r.add(e.yr)})}),wi.resolve(this.Cr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ai.isDocumentKey(i)||(i=i.child(""));var s=new Qc(new ai(i),0);let a=new ms(Xr);return this.Sr.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.yr)),!0)},s),wi.resolve(this.Cr(a))}Cr(e){const n=[];return e.forEach(e=>{var t=this.br(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Vr(0===this.vr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.Sr;return wi.forEach(r.mutations,e=>{var t=new Qc(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.Sr=i})}xn(e){}containsKey(e,t){var n=new Qc(t,0),n=this.Sr.firstAfterOrEqual(n);return wi.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,wi.resolve()}vr(e,t){return this.Dr(e)}Dr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}br(e){var t=this.Dr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Wc{constructor(e){this.Fr=e,this.docs=new ds(ai.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Fr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,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 wi.resolve(n?n.document.mutableCopy():Ws.newInvalidDocument(t))}getEntries(e,t){let n=Ga;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ws.newInvalidDocument(e))}),wi.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Ga;const s=t.path,a=new ai(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||mi(fi(a),n)<=0||(r.has(a.key)||Ba(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return wi.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Pr()}Mr(e,t){return wi.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new Yc(this)}getSize(e){return wi.resolve(this.size)}}class Yc extends Oc{constructor(e){super(),this.ur=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.ur.addEntry(n,t)):this.ur.removeEntry(e)}),wi.waitFor(r)}getFromCache(e,t){return this.ur.getEntry(e,t)}getAllFromCache(e,t){return this.ur.getEntries(e,t)}}class Xc{constructor(e){this.persistence=e,this.Or=new ja(e=>wa(e),_a),this.lastRemoteSnapshotVersion=ti.min(),this.highestTargetId=0,this.Nr=0,this.Br=new $c,this.targetCount=0,this.Lr=Ic.Bn()}forEachTarget(e,n){return this.Or.forEach((e,t)=>n(t)),wi.resolve()}getLastRemoteSnapshotVersion(e){return wi.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return wi.resolve(this.Nr)}allocateTargetId(e){return this.highestTargetId=this.Lr.next(),wi.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Nr&&(this.Nr=t),wi.resolve()}Qn(e){this.Or.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Lr=new Ic(t),this.highestTargetId=t),e.sequenceNumber>this.Nr&&(this.Nr=e.sequenceNumber)}addTargetData(e,t){return this.Qn(t),this.targetCount+=1,wi.resolve()}updateTargetData(e,t){return this.Qn(t),wi.resolve()}removeTargetData(e,t){return this.Or.delete(t.target),this.Br.mr(t.targetId),--this.targetCount,wi.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Or.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Or.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),wi.waitFor(a).next(()=>s)}getTargetCount(e){return wi.resolve(this.targetCount)}getTargetData(e,t){var n=this.Or.get(t)||null;return wi.resolve(n)}addMatchingKeys(e,t,n){return this.Br.Ar(t,n),wi.resolve()}removeMatchingKeys(t,e,n){this.Br.Vr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),wi.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Br.mr(t),wi.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Br.pr(t);return wi.resolve(n)}containsKey(e,t){return wi.resolve(this.Br.containsKey(t))}}class Jc{constructor(e,t){this.kr={},this.overlays={},this.qr=new ki(0),this.Qr=!1,this.Qr=!0,this.referenceDelegate=e(this),this.Kr=new Xc(this),this.indexManager=new ic,this.remoteDocumentCache=(e=e=>this.referenceDelegate.$r(e),new Wc(e)),this.serializer=new Tu(t),this.Ur=new Kc(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Qr=!1,Promise.resolve()}get started(){return this.Qr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new zc,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.kr[e.toKey()];return n||(n=new Hc(t,this.referenceDelegate),this.kr[e.toKey()]=n),n}getTargetCache(){return this.Kr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ur}runTransaction(e,t,n){Or("MemoryPersistence","Starting transaction:",e);const r=new Zc(this.qr.next());return this.referenceDelegate.Wr(),n(r).next(e=>this.referenceDelegate.Gr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}zr(t,n){return wi.or(Object.values(this.kr).map(e=>()=>e.containsKey(t,n)))}}class Zc extends yi{constructor(e){super(),this.currentSequenceNumber=e}}class eh{constructor(e){this.persistence=e,this.jr=new $c,this.Hr=null}static Jr(e){return new eh(e)}get Yr(){if(this.Hr)return this.Hr;throw Pr()}addReference(e,t,n){return this.jr.addReference(n,t),this.Yr.delete(n.toString()),wi.resolve()}removeReference(e,t,n){return this.jr.removeReference(n,t),this.Yr.add(n.toString()),wi.resolve()}markPotentiallyOrphaned(e,t){return this.Yr.add(t.toString()),wi.resolve()}removeTarget(e,t){this.jr.mr(t.targetId).forEach(e=>this.Yr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Yr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Wr(){this.Hr=new Set}Gr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return wi.forEach(this.Yr,e=>{const t=ai.fromPath(e);return this.Zr(n,t).next(e=>{e||r.removeEntry(t,ti.min())})}).next(()=>(this.Hr=null,r.apply(n)))}updateLimboDocument(e,t){return this.Zr(e,t).next(e=>{e?this.Yr.delete(t.toString()):this.Yr.add(t.toString())})}$r(e){return 0}Zr(e,t){return wi.or([()=>wi.resolve(this.jr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.zr(e,t)])}}class th{constructor(e){this.serializer=e}B(t,e,n,r){const i=new _i("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vi,{unique:!0}),s.createObjectStore("documentMutations"),nh(t),t.createObjectStore("remoteDocuments"));let a=wi.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),nh(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:ti.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").G().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vi,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return wi.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.ei(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ti(i)))),n<7&&7<=r&&(a=a.next(()=>this.ni(i))),n<8&&8<=r&&(a=a.next(()=>this.ri(t,i))),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.ii(i))),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(e){const t=e.createObjectStore("documentOverlays",{keyPath:Zi});t.createIndex("collectionPathOverlayIndex",es,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",ts,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:ji});t.createIndex("documentKeyIndex",Gi),t.createIndex("collectionGroupIndex",Ki)}(t)).next(()=>this.si(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.oi(t,i))),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:Wi}).createIndex("sequenceNumberIndex",Yi,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Xi}).createIndex("documentKeyIndex",Ji,{unique:!1})}(t))),a}ti(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=pc(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}ei(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.G().next(e=>wi.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.G("userMutationsIndex",e).next(e=>wi.forEach(e,e=>{Vr(e.userId===n.userId);var t=Du(this.serializer,e);return mc(r,n.userId,t).next(()=>{})}))}))}ni(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Z((e,t)=>{const n=new ri(e),r=[0,Fi(n)];s.push(a.get(r).next(e=>e?wi.resolve():(e=>a.put({targetId:0,path:Fi(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>wi.waitFor(s))})}ri(e,t){e.createObjectStore("collectionParents",{keyPath:Hi});const n=t.store("collectionParents"),r=new sc,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Fi(r)})}};return t.store("remoteDocuments").Z({Y:!0},(e,t)=>{const n=new ri(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Z({Y:!0},([,e],t)=>{const n=Pi(e);return i(n.popLast())}))}ii(e){const r=e.store("targets");return r.Z((e,t)=>{var n=Nu(t),n=ku(this.serializer,n);return r.put(n)})}si(e,a){const t=a.store("remoteDocuments"),o=[];return t.Z((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new ai(ri.fromString(s.document.name).popFirst(5)):s.noDocument?ai.fromSegments(s.noDocument.path):s.unknownDocument?ai.fromSegments(s.unknownDocument.path):Pr()).path.toArray(),i={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};var s;o.push(n.put(i))}).next(()=>wi.waitFor(o))}oi(e,s){const t=s.store("mutations"),a=Fc(this.serializer),o=new Jc(eh.Jr,this.serializer.ht);return t.G().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:Ya();Du(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),wi.forEach(r,(e,t)=>{var n=new Dr(t),r=Bu.Pt(this.serializer,n),i=o.getIndexManager(n),n=yc.Pt(n,this.serializer,i,o.referenceDelegate);return new Gc(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new os(s,ki.ae),e).next()})})}}function nh(e){e.createObjectStore("targetDocuments",{keyPath:$i}).createIndex("documentTargetsIndex",Qi,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",zi,{unique:!0}),e.createObjectStore("targetGlobal")}const rh="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 ih{constructor(e,t,n,r,i,s,a,o,u,c,h=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this._i=i,this.window=s,this.document=a,this.ai=u,this.ui=c,this.ci=h,this.qr=null,this.Qr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.li=null,this.inForeground=!1,this.hi=null,this.Pi=null,this.Ii=Number.NEGATIVE_INFINITY,this.di=e=>Promise.resolve(),!ih.C())throw new Ur(Br.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new kc(this,r),this.Ti=t+"main",this.serializer=new Tu(o),this.Ei=new bi(this.Ti,this.ci,new th(this.serializer)),this.Kr=new Ec(this.referenceDelegate,this.serializer),this.remoteDocumentCache=Fc(this.serializer),this.Ur=new Lu,this.window&&this.window.localStorage?this.Ai=this.window.localStorage:(this.Ai=null,!1===c&&Mr("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.Ri().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new Ur(Br.FAILED_PRECONDITION,rh);return this.Vi(),this.mi(),this.fi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Kr.getHighestSequenceNumber(e))}).then(e=>{this.qr=new ki(e,this.ai)}).then(()=>{this.Qr=!0}).catch(e=>(this.Ei&&this.Ei.close(),Promise.reject(e)))}gi(t){return this.di=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ei.k(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this._i.enqueueAndForget(async()=>{this.started&&await this.Ri()}))}Ri(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>ah(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.pi(t).next(e=>{e||(this.isPrimary=!1,this._i.enqueueRetryable(()=>this.di(!1)))})}).next(()=>this.yi(t)).next(e=>this.isPrimary&&!e?this.wi(t).next(()=>!1):!!e&&this.Si(t).next(()=>!0))).catch(e=>{if(Ti(e))return Or("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Or("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this._i.enqueueRetryable(()=>this.di(e)),this.isPrimary=e})}pi(e){return sh(e).get("owner").next(e=>wi.resolve(this.bi(e)))}Di(e){return ah(e).delete(this.clientId)}async Ci(){if(this.isPrimary&&!this.vi(this.Ii,18e5)){this.Ii=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=us(e,"clientMetadata");return r.G().next(e=>{const t=this.Fi(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return wi.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Ai)for(const t of e)this.Ai.removeItem(this.Mi(t.clientId))}}fi(){this.Pi=this._i.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ri().then(()=>this.Ci()).then(()=>this.fi()))}bi(e){return!!e&&e.ownerId===this.clientId}yi(t){return this.ui?wi.resolve(!0):sh(t).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.xi(e.ownerId)){if(this.bi(e)&&this.networkEnabled)return!0;if(!this.bi(e)){if(!e.allowTabSynchronization)throw new Ur(Br.FAILED_PRECONDITION,rh);return!1}}return!(!this.networkEnabled||!this.inForeground)||ah(t).G().next(e=>void 0===this.Fi(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&&Or("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Qr=!1,this.Oi(),this.Pi&&(this.Pi.cancel(),this.Pi=null),this.Ni(),this.Bi(),await this.Ei.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new os(e,ki.ae);return this.wi(t).next(()=>this.Di(t))}),this.Ei.close(),this.Li()}Fi(e,t){return e.filter(e=>this.vi(e.updateTimeMs,t)&&!this.xi(e.clientId))}ki(){return this.runTransaction("getActiveClients","readonly",e=>ah(e).G().next(e=>this.Fi(e,18e5).map(e=>e.clientId)))}get started(){return this.Qr}getMutationQueue(e,t){return yc.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Kr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new oc(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return Bu.Pt(this.serializer,e)}getBundleCache(){return this.Ur}runTransaction(t,n,r){Or("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=15===(e=this.ci)?as:14===e?ss:13===e?is:12===e?rs:11===e?ns:void Pr();let a;return this.Ei.runTransaction(t,i,s,e=>(a=new os(e,this.qr?this.qr.next():ki.ae),"readwrite-primary"===n?this.pi(a).next(e=>!!e||this.yi(a)).next(e=>{if(!e)throw Mr(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this._i.enqueueRetryable(()=>this.di(!1)),new Ur(Br.FAILED_PRECONDITION,pi);return r(a)}).next(e=>this.Si(a).next(()=>e)):this.qi(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}qi(e){return sh(e).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.xi(e.ownerId)&&!this.bi(e)&&!(this.ui||this.allowTabSynchronization&&e.allowTabSynchronization))throw new Ur(Br.FAILED_PRECONDITION,rh)})}Si(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return sh(e).put("owner",t)}static C(){return bi.C()}wi(e){const t=sh(e);return t.get("owner").next(e=>this.bi(e)?(Or("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):wi.resolve())}vi(e,t){var n=Date.now();return!(e<n-t||n<e&&(Mr(`Detected an update time that is in the future: ${e} > ${n}`),1))}Vi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.hi=()=>{this._i.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ri()))},this.document.addEventListener("visibilitychange",this.hi),this.inForeground="visible"===this.document.visibilityState)}Ni(){this.hi&&(this.document.removeEventListener("visibilitychange",this.hi),this.hi=null)}mi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.li=()=>{this.Oi();var e=/(?:Version|Mobile)\/1[456]/;h()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this._i.enterRestrictedMode(!0),this._i.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.li))}Bi(){this.li&&(this.window.removeEventListener("pagehide",this.li),this.li=null)}xi(e){var t;try{var n=null!==(null===(t=this.Ai)||void 0===t?void 0:t.getItem(this.Mi(e)));return Or("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return Mr("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Oi(){if(this.Ai)try{this.Ai.setItem(this.Mi(this.clientId),String(Date.now()))}catch(e){Mr("Failed to set zombie client id.",e)}}Li(){if(this.Ai)try{this.Ai.removeItem(this.Mi(this.clientId))}catch(e){}}Mi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function sh(e){return us(e,"owner")}function ah(e){return us(e,"clientMetadata")}function oh(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class uh{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Qi=n,this.Ki=r}static $i(e,t){let n=Ya(),r=Ya();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 uh(e,t.fromCache,n,r)}}class ch{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class hh{constructor(){this.Ui=!1,this.Wi=!1,this.Gi=100,this.zi=2}initialize(e,t){this.ji=e,this.indexManager=t,this.Ui=!0}getDocumentsMatchingQuery(n,r,e,t){const i={result:null};return this.Hi(n,r).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.Ji(n,r,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){const t=new ch;return this.Yi(n,r,t).next(e=>{if(i.result=e,this.Wi)return this.Zi(n,r,t,e.size)})}}).next(()=>i.result)}Zi(e,t,n,r){return n.documentReadCount<this.Gi?(Rr()<=l.DEBUG&&Or("QueryEngine","SDK will not create cache indexes for query:",Va(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Gi,"documents"),wi.resolve()):(Rr()<=l.DEBUG&&Or("QueryEngine","Query:",Va(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.zi*r?(Rr()<=l.DEBUG&&Or("QueryEngine","The SDK decides to create cache indexes for query:",Va(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,Oa(t))):wi.resolve())}Hi(i,s){if(Aa(s))return wi.resolve(null);let t=Oa(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=Fa(s,null,"F"),t=Oa(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=Ya(...e);return this.ji.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.Xi(s,n);return this.es(s,t,r,e.readTime)?this.Hi(i,Fa(s,null,"F")):this.ts(i,t,s,e)}))})))}Ji(n,r,i,s){return Aa(r)||s.isEqual(ti.min())?wi.resolve(null):this.ji.getDocuments(n,i).next(e=>{var t=this.Xi(r,e);return this.es(r,t,i,s)?wi.resolve(null):(Rr()<=l.DEBUG&&Or("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Va(r)),this.ts(n,t,r,di(s,-1)).next(e=>e))})}Xi(n,e){let r=new ms(qa(n));return e.forEach((e,t)=>{Ba(n,t)&&(r=r.add(t))}),r}es(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Yi(e,t,n){return Rr()<=l.DEBUG&&Or("QueryEngine","Using full collection scan to execute query:",Va(t)),this.ji.getDocumentsMatchingQuery(e,t,gi.min(),n)}ts(e,n,t,r){return this.ji.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class lh{constructor(e,t,n,r){this.persistence=e,this.ns=t,this.serializer=r,this.rs=new ds(Xr),this.ss=new ja(e=>wa(e),_a),this.os=new Map,this._s=e.getRemoteDocumentCache(),this.Kr=e.getTargetCache(),this.Ur=e.getBundleCache(),this.us(n)}us(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new Gc(this._s,this.mutationQueue,this.documentOverlayCache,this.indexManager),this._s.setIndexManager(this.indexManager),this.ns.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.rs))}}function dh(e,t,n,r){return new lh(e,t,n,r)}async function fh(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a.us(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Ya();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({cs:e,removedBatchIds:t,addedBatchIds:n}))})})}function gh(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Kr.getLastRemoteSnapshotVersion(e))}function mh(e,c){const h=e,l=c.snapshotVersion;let d=h.rs;return h.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=h._s.newChangeBuffer({trackRemovals:!0});d=h.rs;const u=[];c.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){u.push(h.Kr.removeMatchingKeys(o,t.removedDocuments,n).next(()=>h.Kr.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==c.targetMismatches.get(n)?e=e.withResumeToken(_s.EMPTY_BYTE_STRING,ti.min()).withLastLimboFreeSnapshotVersion(ti.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,l)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||u.push(h.Kr.updateTargetData(o,e))}});let t=Ga,n=Ya();if(c.documentUpdates.forEach(e=>{c.resolvedLimboDocuments.has(e)&&u.push(h.persistence.referenceDelegate.updateLimboDocument(o,e))}),u.push(ph(o,e,c.documentUpdates).next(e=>{t=e.ls,n=e.hs})),!l.isEqual(ti.min())){const c=h.Kr.getLastRemoteSnapshotVersion(o).next(e=>h.Kr.setTargetsMetadata(o,o.currentSequenceNumber,l));u.push(c)}return wi.waitFor(u).next(()=>e.apply(o)).next(()=>h.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(h.rs=d,e))}function ph(e,s,t){let n=Ya(),a=Ya();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=Ga;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(ti.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):Or("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{ls:i,hs:a}})}function yh(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Kr.getTargetData(t,r).next(e=>e?(n=e,wi.resolve(n)):i.Kr.allocateTargetId(t).next(e=>(n=new Eu(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Kr.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.rs.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.rs=i.rs.insert(e.targetId,e),i.ss.set(r,e.targetId)),e})}async function vh(e,t,n){const r=e,i=r.rs.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!Ti(e))throw e;Or("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.rs=r.rs.remove(t),r.ss.delete(i.target)}function wh(e,n,r){const i=e;let s=ti.min(),a=Ya();return i.persistence.runTransaction("Execute query","readwrite",t=>function(e,t,n){const r=e,i=r.ss.get(n);return void 0!==i?wi.resolve(r.rs.get(i)):r.Kr.getTargetData(t,n)}(i,t,Oa(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Kr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.ns.getDocumentsMatchingQuery(t,n,r?s:ti.min(),r?a:Ya())).next(e=>(Ih(i,Ua(n),e),{documents:e,Ps:a})))}function _h(e,t){const n=e,r=n.Kr,i=n.rs.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.lt(e,t).next(e=>e?e.target:null))}function bh(e,t){const n=e,r=n.os.get(t)||ti.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n._s.getAllFromCollectionGroup(e,t,di(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(Ih(n,t,e),e))}function Ih(e,t,n){let r=e.os.get(t)||ti.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.os.set(t,r)}function Eh(e,t){return`firestore_clients_${e}_${t}`}function Th(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Sh(e,t){return`firestore_targets_${e}_${t}`}class xh{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Es(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new Ur(r.error.code,r.error.message))),s?new xh(e,t,r.state,i):(Mr("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}As(){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 Ch{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Es(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new Ur(n.error.code,n.error.message))),i?new Ch(e,n.state,r):(Mr("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}As(){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 Ah{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Es(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=Xa;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=Mi(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new Ah(e,i):(Mr("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class Dh{constructor(e,t){this.clientId=e,this.onlineState=t}static Es(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Dh(t.clientId,t.onlineState):(Mr("SharedClientState",`Failed to parse online state: ${e}`),null)}}class Nh{constructor(){this.activeTargetIds=Xa}Rs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Vs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}As(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class kh{constructor(e,t,n,r,i){this.window=e,this._i=t,this.persistenceKey=n,this.fs=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.gs=this.ps.bind(this),this.ys=new ds(Xr),this.started=!1,this.ws=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Ss=Eh(this.persistenceKey,this.fs),this.bs=`firestore_sequence_number_${this.persistenceKey}`,this.ys=this.ys.insert(this.fs,new Nh),this.Ds=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Cs=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.vs=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Fs=`firestore_online_state_${this.persistenceKey}`,this.Ms=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.gs)}static C(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.ki();for(const n of e)if(n!==this.fs){const e=this.getItem(Eh(this.persistenceKey,n));var t;!e||(t=Ah.Es(n,e))&&(this.ys=this.ys.insert(t.clientId,t))}this.xs();const n=this.storage.getItem(this.Fs);if(n){const e=this.Os(n);e&&this.Ns(e)}for(const e of this.ws)this.ps(e);this.ws=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.bs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Bs(this.ys)}isActiveQueryTarget(n){let r=!1;return this.ys.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Ls(e,"pending")}updateMutationState(e,t,n){this.Ls(e,t,n),this.ks(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Sh(this.persistenceKey,e)))||(n=Ch.Es(e,n))&&(t=n.state)),this.qs.Rs(e),this.xs(),t}removeLocalQueryTarget(e){this.qs.Vs(e),this.xs()}isLocalQueryTarget(e){return this.qs.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Sh(this.persistenceKey,e))}updateQueryState(e,t,n){this.Qs(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.ks(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ks(e)}notifyBundleLoaded(e){this.$s(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.gs),this.removeItem(this.Ss),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Or("SharedClientState","READ",e,t),t}setItem(e,t){Or("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Or("SharedClientState","REMOVE",e),this.storage.removeItem(e)}ps(e){const i=e;i.storageArea===this.storage&&(Or("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.Ss?this._i.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.Ds.test(i.key)){if(null==i.newValue){var e=this.Us(i.key);return this.Ws(e,null)}e=this.Gs(i.key,i.newValue);if(e)return this.Ws(e.clientId,e)}else if(this.Cs.test(i.key)){if(null!==i.newValue){var t=this.zs(i.key,i.newValue);if(t)return this.js(t)}}else if(this.vs.test(i.key)){if(null!==i.newValue){t=this.Hs(i.key,i.newValue);if(t)return this.Js(t)}}else if(i.key===this.Fs){if(null!==i.newValue){var n=this.Os(i.newValue);if(n)return this.Ns(n)}}else if(i.key===this.bs){n=function(e){let t=ki.ae;if(null!=e)try{var n=JSON.parse(e);Vr("number"==typeof n),t=n}catch(e){Mr("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==ki.ae&&this.sequenceNumberHandler(n)}else if(i.key===this.Ms){const r=this.Ys(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Zs(e)))}}else this.ws.push(i)}):Mr("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get qs(){return this.ys.get(this.fs)}xs(){this.setItem(this.Ss,this.qs.As())}Ls(e,t,n){const r=new xh(this.currentUser,e,t,n),i=Th(this.persistenceKey,this.currentUser,e);this.setItem(i,r.As())}ks(e){var t=Th(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ks(e){var t={clientId:this.fs,onlineState:e};this.storage.setItem(this.Fs,JSON.stringify(t))}Qs(e,t,n){const r=Sh(this.persistenceKey,e),i=new Ch(e,t,n);this.setItem(r,i.As())}$s(e){var t=JSON.stringify(Array.from(e));this.setItem(this.Ms,t)}Us(e){var t=this.Ds.exec(e);return t?t[1]:null}Gs(e,t){var n=this.Us(e);return Ah.Es(n,t)}zs(e,t){var n=this.Cs.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return xh.Es(new Dr(n),r,t)}Hs(e,t){var n=this.vs.exec(e),n=Number(n[1]);return Ch.Es(n,t)}Os(e){return Dh.Es(e)}Ys(e){return JSON.parse(e)}async js(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Xs(e.batchId,e.state,e.error);Or("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Js(e){return this.syncEngine.eo(e.targetId,e.state,e.error)}Ws(e,t){const n=t?this.ys.insert(e,t):this.ys.remove(e),r=this.Bs(this.ys),i=this.Bs(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.no(s,a).then(()=>{this.ys=n})}Ns(e){this.ys.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Bs(e){let n=Xa;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Rh{constructor(){this.ro=new Nh,this.io={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.ro.Rs(e),this.io[e]||"not-current"}updateQueryState(e,t,n){this.io[e]=t}removeLocalQueryTarget(e){this.ro.Vs(e)}isLocalQueryTarget(e){return this.ro.activeTargetIds.has(e)}clearQueryState(e){delete this.io[e]}getAllActiveQueryTargets(){return this.ro.activeTargetIds}isActiveQueryTarget(e){return this.ro.activeTargetIds.has(e)}start(){return this.ro=new Nh,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class Oh{so(e){}shutdown(){}}class Mh{constructor(){this.oo=()=>this._o(),this.ao=()=>this.uo(),this.co=[],this.lo()}so(e){this.co.push(e)}shutdown(){window.removeEventListener("online",this.oo),window.removeEventListener("offline",this.ao)}lo(){window.addEventListener("online",this.oo),window.addEventListener("offline",this.ao)}_o(){Or("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.co)e(0)}uo(){Or("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.co)e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let Fh=null;function Lh(){return null===Fh?Fh=268435456+Math.round(2147483648*Math.random()):Fh++,"0x"+Fh.toString(16)}const Ph={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class Vh{constructor(e){this.ho=e.ho,this.Po=e.Po}Io(e){this.To=e}Eo(e){this.Ao=e}onMessage(e){this.Ro=e}close(){this.Po()}send(e){this.ho(e)}Vo(){this.To()}mo(e){this.Ao(e)}fo(e){this.Ro(e)}}const Bh="WebChannelConnection";class Uh extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.po=t+"://"+e.host,this.yo=`projects/${n}/databases/${r}`,this.wo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get So(){return!1}bo(t,e,n,r,i){const s=Lh(),a=this.Do(t,e);Or("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.yo,"x-goog-request-params":this.wo};return this.Co(o,r,i),this.vo(t,a,o,n).then(e=>(Or("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw Fr("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}Fo(e,t,n,r,i,s){return this.bo(e,t,n,r,i)}Co(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+Nr,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)}Do(e,t){var n=Ph[e];return`${this.po}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}vo(u,t,n,r){const c=Lh();return new Promise((s,a)=>{const o=new Sr;o.setWithCredentials(!0),o.listenOnce(_r.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case wr.NO_ERROR:var e=o.getResponseJson();Or(Bh,`XHR for RPC '${u}' ${c} received:`,JSON.stringify(e)),s(e);break;case wr.TIMEOUT:Or(Bh,`RPC '${u}' ${c} timed out`),a(new Ur(Br.DEADLINE_EXCEEDED,"Request time out"));break;case wr.HTTP_ERROR:var t=o.getStatus();if(Or(Bh,`RPC '${u}' ${c} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const u=(r=n.status,i=r.toLowerCase().replace(/_/g,"-"),0<=Object.values(Br).indexOf(i)?i:Br.UNKNOWN);a(new Ur(u,n.message))}else a(new Ur(Br.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new Ur(Br.UNAVAILABLE,"Connection failed."));break;default:Pr()}}finally{Or(Bh,`RPC '${u}' ${c} completed.`)}var r,i});var e=JSON.stringify(r);Or(Bh,`RPC '${u}' ${c} sending request:`,r),o.send(t,"POST",e,n,15)})}Mo(i,e,t){const s=Lh(),n=[this.po,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=new Qn,a=vr(),o={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},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(o.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(o.useFetchStreams=!0),this.Co(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var c=n.join("");Or(Bh,`Creating RPC '${i}' stream ${s}: ${c}`,o);const h=r.createWebChannel(c,o);let l=!1,d=!1;const f=new Vh({ho:e=>{d?Or(Bh,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(l||(Or(Bh,`Opening RPC '${i}' stream ${s} transport.`),h.open(),l=!0),Or(Bh,`RPC '${i}' stream ${s} sending:`,e),h.send(e))},Po:()=>h.close()}),g=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return g(h,Tr.EventType.OPEN,()=>{d||Or(Bh,`RPC '${i}' stream ${s} transport opened.`)}),g(h,Tr.EventType.CLOSE,()=>{d||(d=!0,Or(Bh,`RPC '${i}' stream ${s} transport closed`),f.mo())}),g(h,Tr.EventType.ERROR,e=>{d||(d=!0,Fr(Bh,`RPC '${i}' stream ${s} transport errored:`,e),f.mo(new Ur(Br.UNAVAILABLE,"The operation could not be completed")))}),g(h,Tr.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];Vr(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Or(Bh,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=yr[e];if(void 0!==t)return Oo(t)}(n),t=r.message;void 0===e&&(e=Br.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,f.mo(new Ur(e,t)),h.close()}else Or(Bh,`RPC '${i}' stream ${s} received:`,e),f.fo(e)}}),g(a,br.STAT_EVENT,e=>{e.stat===Ir?Or(Bh,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===Er&&Or(Bh,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{f.Vo()},0),f}}function qh(){return"undefined"!=typeof window?window:null}function jh(){return"undefined"!=typeof document?document:null}function Gh(e){return new Jo(e,!0)}class Kh{constructor(e,t,n=1e3,r=1.5,i=6e4){this._i=e,this.timerId=t,this.xo=n,this.Oo=r,this.No=i,this.Bo=0,this.Lo=null,this.ko=Date.now(),this.reset()}reset(){this.Bo=0}qo(){this.Bo=this.No}Qo(e){this.cancel();var t=Math.floor(this.Bo+this.Ko()),n=Math.max(0,Date.now()-this.ko),r=Math.max(0,t-n);0<r&&Or("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Bo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Lo=this._i.enqueueAfterDelay(this.timerId,r,()=>(this.ko=Date.now(),e())),this.Bo*=this.Oo,this.Bo<this.xo&&(this.Bo=this.xo),this.Bo>this.No&&(this.Bo=this.No)}$o(){null!==this.Lo&&(this.Lo.skipDelay(),this.Lo=null)}cancel(){null!==this.Lo&&(this.Lo.cancel(),this.Lo=null)}Ko(){return(Math.random()-.5)*this.Bo}}class zh{constructor(e,t,n,r,i,s,a,o){this._i=e,this.Uo=n,this.Wo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Go=0,this.zo=null,this.jo=null,this.stream=null,this.Ho=new Kh(e,t)}Jo(){return 1===this.state||5===this.state||this.Yo()}Yo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Zo()}async stop(){this.Jo()&&await this.close(0)}Xo(){this.state=0,this.Ho.reset()}e_(){this.Yo()&&null===this.zo&&(this.zo=this._i.enqueueAfterDelay(this.Uo,6e4,()=>this.t_()))}n_(e){this.r_(),this.stream.send(e)}async t_(){if(this.Yo())return this.close(0)}r_(){this.zo&&(this.zo.cancel(),this.zo=null)}i_(){this.jo&&(this.jo.cancel(),this.jo=null)}async close(e,t){this.r_(),this.i_(),this.Ho.cancel(),this.Go++,4!==e?this.Ho.reset():t&&t.code===Br.RESOURCE_EXHAUSTED?(Mr(t.toString()),Mr("Using maximum backoff delay to prevent overloading the backend."),this.Ho.qo()):t&&t.code===Br.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.s_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Eo(t)}s_(){}auth(){this.state=1;const e=this.o_(this.Go),n=this.Go;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Go===n&&this.__(e,t)},t=>{e(()=>{var e=new Ur(Br.UNKNOWN,"Fetching auth token failed: "+t.message);return this.a_(e)})})}__(e,t){const n=this.o_(this.Go);this.stream=this.u_(e,t),this.stream.Io(()=>{n(()=>(this.state=2,this.jo=this._i.enqueueAfterDelay(this.Wo,1e4,()=>(this.Yo()&&(this.state=3),Promise.resolve())),this.listener.Io()))}),this.stream.Eo(e=>{n(()=>this.a_(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Zo(){this.state=5,this.Ho.Qo(async()=>{this.state=0,this.start()})}a_(e){return Or("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}o_(t){return e=>{this._i.enqueueAndForget(()=>this.Go===t?e():(Or("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class $h extends zh{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}u_(e,t){return this.connection.Mo("Listen",e,t)}onMessage(e){this.Ho.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:Pr(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.useProto3Json?(Vr(void 0===f||"string"==typeof f),_s.fromBase64String(f||"")):(Vr(void 0===f||f instanceof Uint8Array),_s.fromUint8Array(f||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(f=a).code?Br.UNKNOWN:Oo(f.code),new Ur(o,f.message||""));n=new Ko(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var u=t.documentChange;u.document,u.document.name,u.document.updateTime;var s=au(e,u.document.name),o=nu(u.document.updateTime),c=u.document.createTime?nu(u.document.createTime):ti.min(),h=new Hs({mapValue:{fields:u.document.fields}}),c=Ws.newFoundDocument(s,o,c,h),h=u.targetIds||[],u=u.removedTargetIds||[];n=new jo(h,u,c.key,c)}else if("documentDelete"in t){t.documentDelete;h=t.documentDelete;h.document;u=au(e,h.document),c=h.readTime?nu(h.readTime):ti.min(),c=Ws.newNoDocument(u,c),h=h.removedTargetIds||[];n=new jo([],h,c.key,c)}else if("documentRemove"in t){t.documentRemove;var l=t.documentRemove;l.document;var d=au(e,l.document),l=l.removedTargetIds||[];n=new jo([],l,d,null)}else{if(!("filter"in t))return Pr();{t.filter;const e=t.filter;e.targetId;var{count:l=0,unchangedNames:d}=e,l=new ko(l,d),d=e.targetId;n=new Go(d,l)}}var o,f;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return ti.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?nu(t.readTime):ti.min()}(e);return this.listener.c_(t,n)}l_(e){const t={};t.database=cu(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=ba(r)?{documents:mu(e,r)}:{query:pu(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=tu(e,t.resumeToken);const r=Zo(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(ti.min())){n.readTime=eu(e,t.snapshotVersion.toTimestamp());const r=Zo(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);var n,n=(this.serializer,e,null==(n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return Pr()}}(e.purpose))?null:{"goog-listen-tags":n});n&&(t.labels=n),this.n_(t)}h_(e){const t={};t.database=cu(this.serializer),t.removeTarget=e,this.n_(t)}}class Qh extends zh{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.P_=!1}get I_(){return this.P_}start(){this.P_=!1,this.lastStreamToken=void 0,super.start()}s_(){this.P_&&this.d_([])}u_(e,t){return this.connection.Mo("Write",e,t)}onMessage(e){if(Vr(!!e.streamToken),this.lastStreamToken=e.streamToken,this.P_){this.Ho.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(Vr(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?nu(e.updateTime):nu(t);return n.isEqual(ti.min())&&(n=nu(t)),new fo(n,e.transformResults||[])}(e,i))):[]),n=nu(e.commitTime);return this.listener.T_(n,t)}var r,i;return Vr(!e.writeResults||0===e.writeResults.length),this.P_=!0,this.listener.E_()}A_(){const e={};e.database=cu(this.serializer),this.n_(e)}d_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>fu(this.serializer,e))};this.n_(t)}}class Hh extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.R_=!1}V_(){if(this.R_)throw new Ur(Br.FAILED_PRECONDITION,"The client has already been terminated.")}bo(n,r,i){return this.V_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.bo(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Br.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Ur(Br.UNKNOWN,e.toString())})}Fo(n,r,i,s){return this.V_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Fo(n,r,i,e,t,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===Br.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new Ur(Br.UNKNOWN,e.toString())})}terminate(){this.R_=!0}}class Wh{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.f_=0,this.g_=null,this.p_=!0}y_(){0===this.f_&&(this.w_("Unknown"),this.g_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.g_=null,this.S_("Backend didn't respond within 10 seconds."),this.w_("Offline"),Promise.resolve())))}b_(e){"Online"===this.state?this.w_("Unknown"):(this.f_++,1<=this.f_&&(this.D_(),this.S_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.w_("Offline")))}set(e){this.D_(),this.f_=0,"Online"===e&&(this.p_=!1),this.w_(e)}w_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}S_(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.p_?(Mr(t),this.p_=!1):Or("OnlineStateTracker",t)}D_(){null!==this.g_&&(this.g_.cancel(),this.g_=null)}}class Yh{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.C_=[],this.v_=new Map,this.F_=new Set,this.M_=[],this.x_=i,this.x_.so(e=>{n.enqueueAndForget(async()=>{sl(this)&&(Or("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.F_.add(4),await Jh(t),t.O_.set("Unknown"),t.F_.delete(4),await Xh(t)}(this))})}),this.O_=new Wh(n,r)}}async function Xh(e){if(sl(e))for(const t of e.M_)await t(!0)}async function Jh(e){for(const t of e.M_)await t(!1)}function Zh(e,t){const n=e;n.v_.has(t.targetId)||(n.v_.set(t.targetId,t),il(n)?rl(n):ml(n).Yo()&&tl(n,t))}function el(e,t){const n=e,r=ml(n);n.v_.delete(t),r.Yo()&&nl(n,t),0===n.v_.size&&(r.Yo()?r.e_():sl(n)&&n.O_.set("Unknown"))}function tl(e,t){var n;e.N_.Le(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(ti.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),ml(e).l_(t)}function nl(e,t){e.N_.Le(t),ml(e).h_(t)}function rl(t){t.N_=new $o({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>t.v_.get(e)||null,st:()=>t.datastore.serializer.databaseId}),ml(t).start(),t.O_.y_()}function il(e){return sl(e)&&!ml(e).Jo()&&0<e.v_.size}function sl(e){return 0===e.F_.size}function al(e){e.N_=void 0}async function ol(e,t,n){if(!Ti(t))throw t;e.F_.add(1),await Jh(e),e.O_.set("Offline"),n=n||(()=>gh(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Or("RemoteStore","Retrying IndexedDB access"),await n(),e.F_.delete(1),await Xh(e)})}function ul(t,n){return n().catch(e=>ol(t,e,n))}async function cl(e){const t=e,n=pl(t);let r=0<t.C_.length?t.C_[t.C_.length-1].batchId:-1;for(;sl(i=t)&&i.C_.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.C_.length&&n.e_();break}r=e.batchId,function(e,t){e.C_.push(t);const n=pl(e);n.Yo()&&n.I_&&n.d_(t.mutations)}(t,e)}catch(e){await ol(t,e)}var i;hl(t)&&ll(t)}function hl(e){return sl(e)&&!pl(e).Jo()&&0<e.C_.length}function ll(e){pl(e).start()}async function dl(e,t){t&&pl(e).I_&&await async function(e,t){if(Ro(n=t.code)&&n!==Br.ABORTED){const r=e.C_.shift();pl(e).Xo(),await ul(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await cl(e)}var n}(e,t),hl(e)&&ll(e)}async function fl(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Or("RemoteStore","RemoteStore received new credentials");var r=sl(n);n.F_.add(3),await Jh(n),r&&n.O_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.F_.delete(3),await Xh(n)}async function gl(e,t){const n=e;t?(n.F_.delete(2),await Xh(n)):(n.F_.add(2),await Jh(n),n.O_.set("Unknown"))}function ml(t){return t.B_||(t.B_=function(e,t,n){const r=e;return r.V_(),new $h(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Io:(async function(n){n.v_.forEach((e,t)=>{tl(n,e)})}).bind(null,t),Eo:(async function(e,t){al(e),il(e)?(e.O_.b_(t),rl(e)):e.O_.set("Unknown")}).bind(null,t),c_:(async function(e,t,n){if(e.O_.set("Online"),t instanceof Ko&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.v_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.v_.delete(r),e.N_.removeTarget(r))}(e,t)}catch(n){Or("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await ol(e,n)}else if(t instanceof jo?e.N_.Ge(t):t instanceof Go?e.N_.Xe(t):e.N_.He(t),!n.isEqual(ti.min()))try{const t=await gh(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.N_._t(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.v_.get(t);n&&i.v_.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.v_.get(e);var r;n&&(i.v_.set(e,n.withResumeToken(_s.EMPTY_BYTE_STRING,n.snapshotVersion)),nl(i,e),r=new Eu(n.target,e,t,n.sequenceNumber),tl(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){Or("RemoteStore","Failed to raise snapshot:",t),await ol(e,t)}}).bind(null,t)}),t.M_.push(async e=>{e?(t.B_.Xo(),il(t)?rl(t):t.O_.set("Unknown")):(await t.B_.stop(),al(t))})),t.B_}function pl(t){return t.L_||(t.L_=function(e,t,n){const r=e;return r.V_(),new Qh(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Io:(async function(e){pl(e).A_()}).bind(null,t),Eo:dl.bind(null,t),E_:(async function(e){const t=pl(e);for(const n of e.C_)t.d_(n.mutations)}).bind(null,t),T_:(async function(e,t,n){const r=e.C_.shift(),i=Do.from(r,t,n);await ul(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await cl(e)}).bind(null,t)}),t.M_.push(async e=>{e?(t.L_.Xo(),await cl(t)):(await t.L_.stop(),0<t.C_.length&&(Or("RemoteStore",`Stopping write stream with ${t.C_.length} pending writes`),t.C_=[]))})),t.L_}class yl{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new qr,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new yl(e,t,s,r,i);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 Ur(Br.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 vl(e,t){if(Mr("AsyncQueue",`${t}: ${e}`),Ti(e))return new Ur(Br.UNAVAILABLE,`${t}: ${e}`);throw e}class wl{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ai.comparator(e.key,t.key):(e,t)=>ai.comparator(e.key,t.key),this.keyedMap=za(),this.sortedSet=new ds(this.comparator)}static emptySet(e){return new wl(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 wl))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 wl;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class _l{constructor(){this.k_=new ds(ai.comparator)}track(e){var t=e.doc.key,n=this.k_.get(t);!n||0!==e.type&&3===n.type?this.k_=this.k_.insert(t,e):3===e.type&&1!==n.type?this.k_=this.k_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.k_=this.k_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.k_=this.k_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.k_=this.k_.remove(t):1===e.type&&2===n.type?this.k_=this.k_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.k_=this.k_.insert(t,{type:2,doc:e.doc}):Pr()}q_(){const n=[];return this.k_.inorderTraversal((e,t)=>{n.push(t)}),n}}class bl{constructor(e,t,n,r,i,s,a,o,u){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=u}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new bl(e,t,wl.emptySet(t),s,n,r,!0,!1,i)}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)&&La(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 Il{constructor(){this.Q_=void 0,this.listeners=[]}}class El{constructor(){this.queries=new ja(e=>Pa(e),La),this.onlineState="Unknown",this.K_=new Set}}async function Tl(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new Il),i)try{s.Q_=await n.onListen(r)}catch(e){const n=vl(e,`Initialization of query '${Va(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.U_(n.onlineState),!s.Q_||t.W_(s.Q_)&&xl(n)}async function Sl(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function xl(e){e.K_.forEach(e=>{e.next()})}class Cl{constructor(e,t,n){this.query=e,this.G_=t,this.z_=!1,this.j_=null,this.onlineState="Unknown",this.options=n||{}}W_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new bl(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.z_?this.H_(e)&&(this.G_.next(e),t=!0):this.J_(e,this.onlineState)&&(this.Y_(e),t=!0),this.j_=e,t}onError(e){this.G_.error(e)}U_(e){this.onlineState=e;let t=!1;return this.j_&&!this.z_&&this.J_(this.j_,e)&&(this.Y_(this.j_),t=!0),t}J_(e,t){return!e.fromCache||(!this.options.Z_||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}H_(e){if(0<e.docChanges.length)return!0;var t=this.j_&&this.j_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Y_(e){e=bl.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.z_=!0,this.G_.next(e)}}class Al{constructor(e,t){this.X_=e,this.byteLength=t}ea(){return"metadata"in this.X_}}class Dl{constructor(e){this.serializer=e}Is(e){return au(this.serializer,e)}ds(e){return e.metadata.exists?du(this.serializer,e.document,!1):Ws.newNoDocument(this.Is(e.metadata.name),this.Ts(e.metadata.readTime))}Ts(e){return nu(e)}}class Nl{constructor(e,t,n){this.ta=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=kl(e)}na(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.X_.namedQuery)this.queries.push(e.X_.namedQuery);else if(e.X_.documentMetadata){this.documents.push({metadata:e.X_.documentMetadata}),e.X_.documentMetadata.exists||++t;const n=ri.fromString(e.X_.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.X_.document&&(this.documents[this.documents.length-1].document=e.X_.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}ra(e){const t=new Map,n=new Dl(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.Is(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||Ya()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=Ya(),a=Ga;for(const e of n){const n=t.Is(e.metadata.name);e.document&&(s=s.add(n));const c=t.ds(e);c.setReadTime(t.Ts(e.metadata.readTime)),a=a.insert(n,c)}const o=i._s.newChangeBuffer({trackRemovals:!0}),u=await yh(i,(r=r,Oa(Ca(ri.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>ph(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Kr.removeMatchingKeysForTargetId(t,u.targetId).next(()=>i.Kr.addMatchingKeys(t,s,u.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.ls,e.hs)).next(()=>e.ls)))}(this.localStore,new Dl(this.serializer),this.documents,this.ta.id),t=this.ra(this.documents);for(const e of this.queries)await async function(e,n,r=Ya()){const i=await yh(e,Oa(Ru(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=nu(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Ur.saveNamedQuery(e,n);t=i.withResumeToken(_s.EMPTY_BYTE_STRING,t);return s.rs=s.rs.insert(t.targetId,t),s.Kr.updateTargetData(e,t).next(()=>s.Kr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Kr.addMatchingKeys(e,r,i.targetId)).next(()=>s.Ur.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,ia:this.collectionGroups,sa:e}}}function kl(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Rl{constructor(e){this.key=e}}class Ol{constructor(e){this.key=e}}class Ml{constructor(e,t){this.query=e,this.oa=t,this._a=null,this.hasCachedResults=!1,this.current=!1,this.aa=Ya(),this.mutatedKeys=Ya(),this.ua=qa(e),this.ca=new wl(this.ua)}get la(){return this.oa}ha(e,t){const o=t?t.Pa:new _l,u=(t||this).ca;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=Ba(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.Ia(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.ua(r,d)||f&&this.ua(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),s?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{ca:h,Pa:o,es:l,mutatedKeys:c}}Ia(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.ca;this.ca=e.ca,this.mutatedKeys=e.mutatedKeys;const i=e.Pa.q_();i.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 Pr()}};return n(e)-n(t)}(e.type,t.type)||this.ua(e.doc,t.doc)),this.da(n);var s=t?this.Ta():[],a=0===this.aa.size&&this.current?1:0,o=a!==this._a;return this._a=a,0!==i.length||o?{snapshot:new bl(this.query,e.ca,r,i,e.mutatedKeys,0==a,o,!1,!!n&&0<n.resumeToken.approximateByteSize()),Ea:s}:{Ea:s}}U_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ca:this.ca,Pa:new _l,mutatedKeys:this.mutatedKeys,es:!1},!1)):{Ea:[]}}Aa(e){return!this.oa.has(e)&&!!this.ca.has(e)&&!this.ca.get(e).hasLocalMutations}da(e){e&&(e.addedDocuments.forEach(e=>this.oa=this.oa.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.oa=this.oa.delete(e)),this.current=e.current)}Ta(){if(!this.current)return[];const t=this.aa;this.aa=Ya(),this.ca.forEach(e=>{this.Aa(e.key)&&(this.aa=this.aa.add(e.key))});const n=[];return t.forEach(e=>{this.aa.has(e)||n.push(new Ol(e))}),this.aa.forEach(e=>{t.has(e)||n.push(new Rl(e))}),n}Ra(e){this.oa=e.Ps,this.aa=Ya();var t=this.ha(e.documents);return this.applyChanges(t,!0)}Va(){return bl.fromInitialDocuments(this.query,this.ca,this.mutatedKeys,0===this._a,this.hasCachedResults)}}class Fl{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Ll{constructor(e){this.key=e,this.ma=!1}}class Pl{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.fa={},this.ga=new ja(e=>Pa(e),La),this.pa=new Map,this.ya=new Set,this.wa=new ds(ai.comparator),this.Sa=new Map,this.ba=new $c,this.Da={},this.Ca=new Map,this.va=Ic.Ln(),this.onlineState="Unknown",this.Fa=void 0}get isPrimaryClient(){return!0===this.Fa}}async function Vl(r,e,t,n,i){r.Ma=(e,t,n)=>async function(e,t,n,r){let i=t.view.ha(n);i.es&&(i=await wh(e.localStore,t.query,!1).then(({documents:e})=>t.view.ha(e,i)));var s=r&&r.targetChanges.get(t.targetId),s=t.view.applyChanges(i,e.isPrimaryClient,s);return Ql(e,t.targetId,s.Ea),s.snapshot}(r,e,t,n);const s=await wh(r.localStore,e,!0),a=new Ml(e,s.Ps),o=a.ha(s.documents),u=qo.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),c=a.applyChanges(o,r.isPrimaryClient,u);Ql(r,t,c.Ea);var h=new Fl(e,t,a);return r.ga.set(e,h),r.pa.has(t)?r.pa.get(t).push(e):r.pa.set(t,[e]),c.snapshot}async function Bl(e,t,n){const r=ed(e);try{const e=await function(e,i){const s=e,a=ei.now(),o=i.reduce((e,t)=>e.add(t.key),Ya());let u,c;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=Ga,r=Ya();return s._s.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{u=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=no(r.transform,e||null);null!=i&&(null===n&&(n=Hs.empty()),n.set(r.field,i))}return n||null}(n,u.get(n.key).overlayedDocument);null!=i&&t.push(new Io(n.key,i,function r(e){const i=[];return hs(e.fields,(e,t)=>{const n=new si([e]);if(Gs(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new vs(i)}(i.value.mapValue),go.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(c=e).applyToLocalDocumentSet(u,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:c.batchId,changes:$a(u)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Da[e.currentUser.toKey()];r=r||new ds(Xr),r=r.insert(t,n),e.Da[e.currentUser.toKey()]=r}(r,e.batchId,n),await Wl(r,e.changes),await cl(r.remoteStore)}catch(e){const t=vl(e,"Failed to persist write");n.reject(t)}}async function Ul(e,t){const r=e;try{const e=await mh(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Sa.get(t);n&&(Vr(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.ma=!0:0<e.modifiedDocuments.size?Vr(n.ma):0<e.removedDocuments.size&&(Vr(n.ma),n.ma=!1))}),await Wl(r,e,t)}catch(e){await vi(e)}}function ql(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ga.forEach((e,t)=>{var n=t.view.U_(i);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.U_(n)&&(r=!0)}),r&&xl(t)}(t.eventManager,i),r.length&&t.fa.c_(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function jl(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i._s.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=wi.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Vr(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=Ya();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(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);Kl(n,r,null),Gl(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Wl(n,e)}catch(e){await vi(e)}}function Gl(e,t){(e.Ca.get(t)||[]).forEach(e=>{e.resolve()}),e.Ca.delete(t)}function Kl(e,t,n){const r=e;let i=r.Da[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Da[r.currentUser.toKey()]=i}}function zl(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.pa.get(e))t.ga.delete(r),n&&t.fa.xa(r,n);t.pa.delete(e),t.isPrimaryClient&&t.ba.mr(e).forEach(e=>{t.ba.containsKey(e)||$l(t,e)})}function $l(e,t){e.ya.delete(t.path.canonicalString());var n=e.wa.get(t);null!==n&&(el(e.remoteStore,n),e.wa=e.wa.remove(t),e.Sa.delete(n),Hl(e))}function Ql(e,t,n){for(const r of n)r instanceof Rl?(e.ba.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.wa.get(n)||e.ya.has(r)||(Or("SyncEngine","New document in limbo: "+n),e.ya.add(r),Hl(e))}(e,r)):r instanceof Ol?(Or("SyncEngine","Document no longer in limbo: "+r.key),e.ba.removeReference(r.key,t),e.ba.containsKey(r.key)||$l(e,r.key)):Pr()}function Hl(e){for(;0<e.ya.size&&e.wa.size<e.maxConcurrentLimboResolutions;){var t=e.ya.values().next().value;e.ya.delete(t);var n=new ai(ri.fromString(t)),t=e.va.next();e.Sa.set(t,new Ll(n)),e.wa=e.wa.insert(n,t),Zh(e.remoteStore,new Eu(Oa(Ca(n.path)),t,"TargetPurposeLimboResolution",ki.ae))}}async function Wl(e,t,r){const i=e,s=[],a=[],o=[];i.ga.isEmpty()||(i.ga.forEach((e,n)=>{o.push(i.Ma(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=uh.$i(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.fa.c_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>wi.forEach(t,t=>wi.forEach(t.Qi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>wi.forEach(t.Ki,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!Ti(e))throw e;Or("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.rs.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.rs=r.rs.insert(t,i)}}}(i.localStore,a))}async function Yl(r,e){const i=r;if(Zl(i),ed(i),!0===e&&!0!==i.Fa){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await Xl(i,r.toArray());i.Fa=!0,await gl(i.remoteStore,!0);for(const r of e)Zh(i.remoteStore,r)}else if(!1===e&&!1!==i.Fa){const r=[];let n=Promise.resolve();i.pa.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(zl(i,t),vh(i.localStore,t,!0))),el(i.remoteStore,t)}),await n,await Xl(i,r),function(e){const n=e;n.Sa.forEach((e,t)=>{el(n.remoteStore,t)}),n.ba.gr(),n.Sa=new Map,n.wa=new ds(ai.comparator)}(i),i.Fa=!1,await gl(i.remoteStore,!1)}}async function Xl(t,n){const r=t,i=[],s=[];for(const t of n){let e;const h=r.pa.get(t);if(h&&0!==h.length){e=await yh(r.localStore,Oa(h[0]));for(const t of h){const n=r.ga.get(t),h=(a=r,o=n,c=u=void 0,c=await wh((u=a).localStore,o.query,!0),c=o.view.Ra(c),u.isPrimaryClient&&Ql(u,o.targetId,c.Ea),await c);h.snapshot&&s.push(h.snapshot)}}else{const h=await _h(r.localStore,t);e=await yh(r.localStore,h),await Vl(r,Jl(h),t,!1,e.resumeToken)}i.push(e)}var a,o,u,c;return r.fa.c_(s),i}function Jl(e){return xa(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Zl(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=Ul.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Sa.get(t);if(r&&r.ma)return Ya().add(r.key);{let e=Ya();const r=n.pa.get(t);if(!r)return e;for(const t of r){const r=n.ga.get(t);e=e.unionWith(r.view.la)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Sa.get(t),s=i&&i.key;if(s){let e=new ds(ai.comparator);e=e.insert(s,Ws.newNoDocument(s,ti.min()));const n=Ya().add(s),i=new Uo(ti.min(),new Map,new ds(Xr),e,n);await Ul(r,i),r.wa=r.wa.remove(s),r.Sa.delete(t),Hl(r)}else await vh(r.localStore,t,!1).then(()=>zl(r,t,n)).catch(vi)}).bind(null,t),t.fa.c_=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.W_(e)&&(r=!0);i.Q_=e}}r&&xl(n)}).bind(null,t.eventManager),t.fa.xa=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function ed(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=jl.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(Vr(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);Kl(r,t,n),Gl(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Wl(r,e)}catch(n){await vi(n)}}).bind(null,t),t}class td{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=Gh(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return dh(this.persistence,new hh,e.initialUser,this.serializer)}createPersistence(e){return new Jc(eh.Jr,this.serializer)}createSharedClientState(e){return new Rh}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class nd extends td{constructor(e,t,n){super(),this.Na=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Na.initialize(this,e),await ed(this.Na.syncEngine),await cl(this.Na.remoteStore),await this.persistence.gi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return dh(this.persistence,new hh,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new Dc(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new Ni(t,this.persistence);return new Di(e.asyncQueue,n)}createPersistence(e){var t=oh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?gc.withCacheSize(this.cacheSizeBytes):gc.DEFAULT;return new ih(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,qh(),jh(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new Rh}}class rd extends nd{constructor(e,t){super(e,t,!1),this.Na=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Na.syncEngine;this.sharedClientState instanceof kh&&(this.sharedClientState.syncEngine={Xs:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Fn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):wi.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await cl(i.remoteStore):"acknowledged"===n||"rejected"===n?(Kl(i,t,r||null),Gl(i,t),i.localStore.mutationQueue.xn(t)):Pr(),await Wl(i,s)):Or("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),eo:(async function(e,t,n,r){const i=e;if(i.Fa)Or("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.pa.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await bh(i.localStore,Ua(s[0])),r=Uo.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,_s.EMPTY_BYTE_STRING);await Wl(i,e,r);break}case"rejected":await vh(i.localStore,t,!0),zl(i,t,r);break;default:Pr()}}}).bind(null,t),no:(async function(e,t,n){const r=Zl(e);if(r.Fa){for(const e of t)if(r.pa.has(e))Or("SyncEngine","Adding an already active target "+e);else{const t=await _h(r.localStore,e),n=await yh(r.localStore,t);await Vl(r,Jl(t),n.targetId,!1,n.resumeToken),Zh(r.remoteStore,n)}for(const e of n)r.pa.has(e)&&await vh(r.localStore,e,!1).then(()=>{el(r.remoteStore,e),zl(r,e)}).catch(vi)}}).bind(null,t),ki:(function(e){return e.localStore.persistence.ki()}).bind(null,t),Zs:(async function(e,t){const n=e;return bh(n.localStore,t).then(e=>Wl(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.gi(async e=>{await Yl(this.Na.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())})}createSharedClientState(e){var t=qh();if(!kh.C(t))throw new Ur(Br.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=oh(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new kh(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class id{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=>ql(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){Or("SyncEngine","User change. New user:",t.toKey());const i=await fh(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.Ca.forEach(e=>{e.forEach(e=>{e.reject(new Ur(Br.CANCELLED,r))})}),e.Ca.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await Wl(n,i.cs)}var r}).bind(null,this.syncEngine),await gl(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new El}createDatastore(e){var t,n,r,i=Gh(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new Uh(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new Hh(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>ql(this.syncEngine,e,0),e=new(Mh.C()?Mh:Oh),new Yh(t,n,r,i,e);var t,n,r,i}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Pl(e,t,n,r,i,s);return a&&(o.Fa=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;Or("RemoteStore","RemoteStore shutting down."),t.F_.add(5),await Jh(t),t.x_.shutdown(),t.O_.set("Unknown")}(this.remoteStore)}}function sd(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.resolve()}}class ad{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Ba(this.observer.next,e)}error(e){this.observer.error?this.Ba(this.observer.error,e):Mr("Uncaught Error in snapshot listener:",e.toString())}La(){this.muted=!0}Ba(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class od{constructor(e,t){this.ka=e,this.serializer=t,this.metadata=new qr,this.buffer=new Uint8Array,this.qa=new TextDecoder("utf-8"),this.Qa().then(e=>{e&&e.ea()?this.metadata.resolve(e.X_.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.X_)}`))},e=>this.metadata.reject(e))}close(){return this.ka.cancel()}async getMetadata(){return this.metadata.promise}async Oa(){return await this.getMetadata(),this.Qa()}async Qa(){var e=await this.Ka();if(null===e)return null;var t=this.qa.decode(e),n=Number(t);isNaN(n)&&this.$a(`length string (${t}) is not valid number`);t=await this.Ua(n);return new Al(JSON.parse(t),e.length+n)}Wa(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Ka(){for(;this.Wa()<0&&!await this.Ga(););if(0===this.buffer.length)return null;var e=this.Wa();e<0&&this.$a("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 Ua(e){for(;this.buffer.length<e;)await this.Ga()&&this.$a("Reached the end of bundle when more is expected.");var t=this.qa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}$a(e){throw this.ka.cancel(),new Error(`Invalid bundle format: ${e}`)}async Ga(){var e=await this.ka.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 ud{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 Ur(Br.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=cu(r.serializer)+"/documents",i={documents:t.map(e=>su(r.serializer,e))},s=await r.Fo("BatchGetDocuments",n,i,t.length),a=new Map;s.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){Vr(!!t.found),t.found.name,t.found.updateTime;var n=au(e,t.found.name),r=nu(t.found.updateTime),i=t.found.createTime?nu(t.found.createTime):ti.min(),s=new Hs({mapValue:{fields:t.found.fields}});return Ws.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){Vr(!!t.missing),Vr(!!t.readTime);var n=au(e,t.missing),r=nu(t.readTime);return Ws.newNoDocument(n,r)}(n,e):Pr());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Vr(!!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 xo(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=ai.fromPath(t);this.mutations.push(new Co(n,this.precondition(n)))}),await async function(e,t){const n=e,r=cu(n.serializer)+"/documents",i={writes:t.map(e=>fu(n.serializer,e))};await n.bo("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Pr();t=ti.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new Ur(Br.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(ti.min())?go.exists(!1):go.updateTime(t):go.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return go.exists(!0);if(t.isEqual(ti.min()))throw new Ur(Br.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return go.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class cd{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.za=n.maxAttempts,this.Ho=new Kh(this.asyncQueue,"transaction_retry")}run(){--this.za,this.ja()}ja(){this.Ho.Qo(async()=>{const t=new ud(this.datastore),e=this.Ha(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Ja(e)}))}).catch(e=>{this.Ja(e)})})}Ha(e){try{var t=this.updateFunction(e);return!Ri(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}}Ja(e){0<this.za&&this.Ya(e)?(--this.za,this.asyncQueue.enqueueAndForget(()=>(this.ja(),Promise.resolve()))):this.deferred.reject(e)}Ya(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!Ro(t)}}class hd{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Dr.UNAUTHENTICATED,this.clientId=Yr.V(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Or("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Or("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 Ur(Br.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new qr;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=vl(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function ld(e,t){e.asyncQueue.verifyOperationInProgress(),Or("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await fh(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function dd(e,n){e.asyncQueue.verifyOperationInProgress();var t=await gd(e);Or("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>fl(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>fl(n.remoteStore,t)),e._onlineComponents=n}function fd(e){return"FirebaseError"===e.name?e.code===Br.FAILED_PRECONDITION||e.code===Br.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function gd(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){Or("FirestoreClient","Using user provided OfflineComponentProvider");try{await ld(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!fd(n))throw n;Fr("Error using user provided cache. Falling back to memory cache: "+n),await ld(t,new td)}}else Or("FirestoreClient","Using default OfflineComponentProvider"),await ld(t,new td);return t._offlineComponents}async function md(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Or("FirestoreClient","Using user provided OnlineComponentProvider"),await dd(e,e._uninitializedComponentsProvider._online)):(Or("FirestoreClient","Using default OnlineComponentProvider"),await dd(e,new id))),e._onlineComponents}function pd(e){return gd(e).then(e=>e.persistence)}function yd(e){return gd(e).then(e=>e.localStore)}function vd(e){return md(e).then(e=>e.remoteStore)}function wd(e){return md(e).then(e=>e.syncEngine)}async function _d(e){const t=await md(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=Zl(e);let r,i;const s=n.ga.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Va();else{const e=await yh(n.localStore,Oa(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await Vl(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&Zh(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ga.get(t),i=n.pa.get(r.targetId);if(1<i.length)return n.pa.set(r.targetId,i.filter(e=>!La(e,t))),void n.ga.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await vh(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),el(n.remoteStore,r.targetId),zl(n,r.targetId)}).catch(vi)):(zl(n,r.targetId),await vh(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function bd(e,t,n={}){const r=new qr;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new ad({next:e=>{r.enqueueAndForget(()=>Sl(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new Ur(Br.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new Ur(Br.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 Cl(Ca(i.path),e,{includeMetadataChanges:!0,Z_:!0});return Tl(n,o)}(await _d(e),e.asyncQueue,t,n,r)),r.promise}function Id(e,t,n={}){const r=new qr;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new ad({next:e=>{n.enqueueAndForget(()=>Sl(t,a)),e.fromCache&&"server"===r.source?i.reject(new Ur(Br.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.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new Cl(e,s,{includeMetadataChanges:!0,Z_:!0});return Tl(t,a)}(await _d(e),e.asyncQueue,t,n,r)),r.promise}function Ed(e,t,n,r){const i=(n=n,t=Gh(t),s="string"==typeof n?Mo().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return sd(e,t);if(e instanceof ArrayBuffer)return sd(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new od(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=nu(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ur.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(kl(i));const a=new Nl(i,t.localStore,n.serializer);let e=await n.Oa();for(;e;){const t=await a.na(e);t&&r._updateProgress(t),e=await n.Oa()}var s=await a.complete();return await Wl(t,s.sa,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ur.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.ia)}catch(t){return Fr("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await wd(e),i,r)})}function Td(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Sd=new Map;function xd(e,t,n){if(!n)throw new Ur(Br.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Cd(e,t,n,r){if(!0===t&&!0===r)throw new Ur(Br.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Ad(e){if(!ai.isDocumentKey(e))throw new Ur(Br.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Dd(e){if(ai.isDocumentKey(e))throw new Ur(Br.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Nd(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":Pr();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 kd(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new Ur(Br.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Nd(e);throw new Ur(Br.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Rd(e,t){if(t<=0)throw new Ur(Br.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Od{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new Ur(Br.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,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new Ur(Br.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}Cd("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Td(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new Ur(Br.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new Ur(Br.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new Ur(Br.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}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&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class Md{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 Od({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new Ur(Br.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 Ur(Br.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 Od(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Gr;switch(e.type){case"firstParty":return new Qr(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new Ur(Br.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=Sd.get(e);t&&(Or("ComponentProvider","Removing Datastore"),Sd.delete(e),t.terminate())}(this),Promise.resolve()}}function Fd(n,e,t,r={}){var i;const s=(n=kd(n,Md))._getSettings(),a=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&Fr("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),n._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=Dr.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,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");return i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e),[o(JSON.stringify({alg:"none",type:"JWT"})),o(JSON.stringify(i)),""].join(".")}(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new Ur(Br.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new Dr(s)}n._authCredentials=new Kr(new jr(e,t))}}class Ld{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Ld(this.firestore,e,this._query)}}class Pd{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 Vd(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Pd(this.firestore,e,this._key)}}class Vd extends Ld{constructor(e,t,n){super(e,t,Ca(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 Pd(this.firestore,null,new ai(e))}withConverter(e){return new Vd(this.firestore,e,this._path)}}function Bd(e,t,...n){if(e=m(e),xd("collection","path",t),e instanceof Md){var r=ri.fromString(t,...n);return Dd(r),new Vd(e,null,r)}if(!(e instanceof Pd||e instanceof Vd))throw new Ur(Br.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ri.fromString(t,...n));return Dd(r),new Vd(e.firestore,null,r)}function Ud(e,t,...n){if(e=m(e),xd("doc","path",t=1===arguments.length?Yr.V():t),e instanceof Md){var r=ri.fromString(t,...n);return Ad(r),new Pd(e,null,new ai(r))}if(!(e instanceof Pd||e instanceof Vd))throw new Ur(Br.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ri.fromString(t,...n));return Ad(r),new Pd(e.firestore,e instanceof Vd?e.converter:null,new ai(r))}function qd(e,t){return e=m(e),t=m(t),(e instanceof Pd||e instanceof Vd)&&(t instanceof Pd||t instanceof Vd)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function jd(e,t){return e=m(e),t=m(t),e instanceof Ld&&t instanceof Ld&&e.firestore===t.firestore&&La(e._query,t._query)&&e.converter===t.converter}class Gd{constructor(){this.Za=Promise.resolve(),this.Xa=[],this.eu=!1,this.tu=[],this.nu=null,this.ru=!1,this.iu=!1,this.su=[],this.Ho=new Kh(this,"async_queue_retry"),this.ou=()=>{var e=jh();e&&Or("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Ho.$o()};const e=jh();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.ou)}get isShuttingDown(){return this.eu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this._u(),this.au(e)}enterRestrictedMode(e){if(!this.eu){this.eu=!0,this.iu=e||!1;const t=jh();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.ou)}}enqueue(e){if(this._u(),this.eu)return new Promise(()=>{});const t=new qr;return this.au(()=>this.eu&&this.iu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Xa.push(e),this.uu()))}async uu(){if(0!==this.Xa.length){try{await this.Xa[0](),this.Xa.shift(),this.Ho.reset()}catch(e){if(!Ti(e))throw e;Or("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Xa.length&&this.Ho.Qo(()=>this.uu())}}au(e){var t=this.Za.then(()=>(this.ru=!0,e().catch(e=>{throw this.nu=e,this.ru=!1,Mr("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.ru=!1,e))));return this.Za=t}enqueueAfterDelay(e,t,n){this._u(),-1<this.su.indexOf(e)&&(t=0);var r=yl.createAndSchedule(this,e,t,n,e=>this.cu(e));return this.tu.push(r),r}_u(){this.nu&&Pr()}verifyOperationInProgress(){}async lu(){for(var e;await(e=this.Za),e!==this.Za;);}hu(e){for(const t of this.tu)if(t.timerId===e)return!0;return!1}Pu(t){return this.lu().then(()=>{this.tu.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.tu)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.lu()})}Iu(e){this.su.push(e)}cu(e){var t=this.tu.indexOf(e);this.tu.splice(t,1)}}function Kd(e){return function(e,t){if("object"==typeof e&&null!==e){var n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return 1}}(e,["next","error","complete"])}class zd{constructor(){this._progressObserver={},this._taskCompletionResolver=new qr,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 $d,Qd,Hd,Wd,Yd;class Xd extends Md{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new Gd,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||Zd(this),this._firestoreClient.terminate()}}function Jd(e){return e._firestoreClient||Zd(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Zd(e){var t,n,r,i,s,a=e._freezeSettings(),o=(n=e._databaseId,r=(null===(o=e._app)||void 0===o?void 0:o.options.appId)||"",i=e._persistenceKey,s=a,new As(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Td(s.experimentalLongPollingOptions),s.useFetchStreams));e._firestoreClient=new hd(e._authCredentials,e._appCheckCredentials,e._queue,o),null!==(o=a.localCache)&&void 0!==o&&o._offlineComponentProvider&&null!==(t=a.localCache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:a.localCache.kind,_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider})}function ef(e,t,n){const r=new qr;return e.asyncQueue.enqueue(async()=>{try{await ld(e,n),await dd(e,t),r.resolve()}catch(e){const t=e;if(!fd(t))throw t;Fr("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function tf(e){return function(e){const t=new qr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;sl(n.remoteStore)||Or("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Ca.get(e)||[];r.push(t),n.Ca.set(e,r)}catch(e){const n=vl(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await wd(e),t)),t.promise}(Jd(e=kd(e,Xd)))}function nf(e){return(n=Jd(e=kd(e,Xd))).asyncQueue.enqueue(async()=>{const e=await pd(n),t=await vd(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.F_.delete(0),Xh(t)}(t)});var n}function rf(e){return(n=Jd(e=kd(e,Xd))).asyncQueue.enqueue(async()=>{const e=await pd(n),t=await vd(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.F_.add(0),await Jh(t),t.O_.set("Offline")}(t)});var n}function sf(t,e){return n=Jd(t=kd(t,Xd)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ur.getNamedQuery(e,t))}(await yd(n),r)).then(e=>e?new Ld(t,null,e.query):null);var n,r}function af(e){if(e._initialized||e._terminated)throw new Ur(Br.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 of{constructor(e){this._byteString=e}static fromBase64String(e){try{return new of(_s.fromBase64String(e))}catch(e){throw new Ur(Br.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new of(_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 uf{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new Ur(Br.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new si(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class cf{constructor(e){this._methodName=e}}class hf{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new Ur(Br.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new Ur(Br.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 Xr(this._lat,e._lat)||Xr(this._long,e._long)}}const lf=/^__.*__$/;class df{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Io(e,this.data,this.fieldMask,t,this.fieldTransforms):new bo(e,this.data,t,this.fieldTransforms)}}class ff{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Io(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function gf(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Pr()}}class mf{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.du(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Tu(){return this.settings.Tu}Eu(e){return new mf(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Au(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Eu({path:n,Ru:!1});return r.Vu(e),r}mu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Eu({path:n,Ru:!1});return r.du(),r}fu(e){return this.Eu({path:void 0,Ru:!0})}gu(e){return Ff(e,this.settings.methodName,this.settings.pu||!1,this.path,this.settings.yu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}du(){if(this.path)for(let e=0;e<this.path.length;e++)this.Vu(this.path.get(e))}Vu(e){if(0===e.length)throw this.gu("Document fields must not be empty");if(gf(this.Tu)&&lf.test(e))throw this.gu('Document fields cannot begin and end with "__"')}}class pf{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||Gh(e)}wu(e,t,n,r=!1){return new mf({Tu:e,methodName:t,yu:n,path:si.emptyPath(),Ru:!1,pu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function yf(e){var t=e._freezeSettings(),n=Gh(e._databaseId);return new pf(e._databaseId,!!t.ignoreUndefinedProperties,n)}function vf(e,t,n,r,i,s={}){const a=e.wu(s.merge||s.mergeFields?2:0,t,n,i);kf("Data must be an object, but it was:",a,r);var o=Df(r,a);let u,c;if(s.merge)u=new vs(a.fieldMask),c=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Rf(t,r,n);if(!a.contains(i))throw new Ur(Br.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Lf(e,i)||e.push(i)}u=new vs(e),c=a.fieldTransforms.filter(e=>u.covers(e.field))}else u=null,c=a.fieldTransforms;return new df(new Hs(o),u,c)}class wf extends cf{_toFieldTransform(e){if(2!==e.Tu)throw 1===e.Tu?e.gu(`${this._methodName}() can only appear at the top level of your update data`):e.gu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof wf}}function _f(e,t,n){return new mf({Tu:3,yu:t.settings.yu,methodName:e._methodName,Ru:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class bf extends cf{_toFieldTransform(e){return new lo(e.path,new ro)}isEqual(e){return e instanceof bf}}class If extends cf{constructor(e,t){super(e),this.Su=t}_toFieldTransform(e){const t=_f(this,e,!0),n=this.Su.map(e=>Af(e,t)),r=new io(n);return new lo(e.path,r)}isEqual(e){return this===e}}class Ef extends cf{constructor(e,t){super(e),this.Su=t}_toFieldTransform(e){const t=_f(this,e,!0),n=this.Su.map(e=>Af(e,t)),r=new ao(n);return new lo(e.path,r)}isEqual(e){return this===e}}class Tf extends cf{constructor(e,t){super(e),this.bu=t}_toFieldTransform(e){var t=new uo(e.serializer,eo(e.serializer,this.bu));return new lo(e.path,t)}isEqual(e){return this===e}}function Sf(e,i,s,t){const a=e.wu(1,i,s);kf("Data must be an object, but it was:",a,t);const o=[],u=Hs.empty();hs(t,(e,t)=>{var n=Mf(i,e,s);t=m(t);var r=a.mu(n);if(t instanceof wf)o.push(n);else{const e=Af(t,r);null!=e&&(o.push(n),u.set(n,e))}});var n=new vs(o);return new ff(u,n,a.fieldTransforms)}function xf(e,t,n,r,i,s){const a=e.wu(1,t,n),o=[Rf(t,r,n)],u=[i];if(s.length%2!=0)throw new Ur(Br.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<s.length;f+=2)o.push(Rf(t,s[f])),u.push(s[f+1]);const c=[],h=Hs.empty();for(let g=o.length-1;0<=g;--g)if(!Lf(c,o[g])){const t=o[g];var l=m(l=u[g]);const r=a.mu(t);if(l instanceof wf)c.push(t);else{const e=Af(l,r);null!=e&&(c.push(t),h.set(t,e))}}var d=new vs(c);return new ff(h,d,a.fieldTransforms)}function Cf(e,t,n,r=!1){return Af(n,e.wu(r?4:3,t))}function Af(e,t){if(Nf(e=m(e)))return kf("Unsupported field value:",t,e),Df(e,t);if(e instanceof cf)return function(e,t){if(!gf(t.Tu))throw t.gu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.gu(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Ru&&4!==t.Tu)throw t.gu("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=Af(i,t.fu(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=m(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return eo(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=ei.fromDate(e);return{timestampValue:eu(t.serializer,n)}}if(e instanceof ei){n=new ei(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:eu(t.serializer,n)}}if(e instanceof hf)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof of)return{bytesValue:tu(t.serializer,e._byteString)};if(e instanceof Pd){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.gu(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:ru(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.gu(`Unsupported field value: ${Nd(e)}`)}(e,t)}function Df(e,r){const i={};return ls(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):hs(e,(e,t)=>{var n=Af(t,r.Au(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function Nf(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ei||e instanceof hf||e instanceof of||e instanceof Pd||e instanceof cf)}function kf(e,t,n){if(!Nf(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=Nd(n);throw"an object"===r?t.gu(e+" a custom object"):t.gu(e+" "+r)}var i}function Rf(e,t,n){if((t=m(t))instanceof uf)return t._internalPath;if("string"==typeof t)return Mf(e,t);throw Ff("Field path arguments must be of type string or ",e,!1,void 0,n)}const Of=new RegExp("[~\\*/\\[\\]]");function Mf(t,n,r){if(0<=n.search(Of))throw Ff(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new uf(...n.split("."))._internalPath}catch(e){throw Ff(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function Ff(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let u="";return(s||a)&&(u+=" (found",s&&(u+=` in field ${r}`),a&&(u+=` in document ${i}`),u+=")"),new Ur(Br.INVALID_ARGUMENT,o+e+u)}function Lf(e,t){return e.some(e=>e.isEqual(t))}class Pf{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Pd(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new Vf(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(Bf("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Vf extends Pf{data(){return super.data()}}function Bf(e,t){return"string"==typeof t?Mf(e,t):(t instanceof uf?t:t._delegate)._internalPath}function Uf(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new Ur(Br.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class qf{}class jf extends qf{}function Gf(e,t,...n){let r=[];t instanceof qf&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof zf).length,n=e.filter(e=>e instanceof Kf).length;if(1<t||0<t&&0<n)throw new Ur(Br.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 Kf extends jf{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Kf(e,t,n)}_apply(e){var t=this._parse(e);return Zf(e._query,t),new Ld(e.firestore,e.converter,Ma(e._query,t))}_parse(e){var t=yf(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new Ur(Br.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){Jf(a,s);const t=[];for(const n of a)t.push(Xf(r,e,n));o={arrayValue:{values:t}}}else o=Xf(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||Jf(a,s),o=Cf(n,t,a,"in"===s||"not-in"===s);return ta.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class zf extends qf{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new zf(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]:na.create(e,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(const e of t.getFlattenedFilters())Zf(n,e),n=Ma(n,e)}(e._query,t),new Ld(e.firestore,e.converter,Ma(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class $f extends jf{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new $f(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new Ur(Br.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new Ur(Br.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new Zs(t,n);return n=i,null!==Da(e=e)||null!==(r=Na(e))&&eg(0,r,n.field),i}(e._query,this._field,this._direction);return new Ld(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new Sa(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class Qf extends jf{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new Qf(e,t,n)}_apply(e){return new Ld(e.firestore,e.converter,Fa(e._query,this._limit,this._limitType))}}class Hf extends jf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Hf(e,t,n)}_apply(e){var t,n=Yf(e,this.type,this._docOrFields,this._inclusive);return new Ld(e.firestore,e.converter,(t=e._query,e=n,new Sa(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class Wf extends jf{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Wf(e,t,n)}_apply(e){var t,n=Yf(e,this.type,this._docOrFields,this._inclusive);return new Ld(e.firestore,e.converter,(t=e._query,e=n,new Sa(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function Yf(e,t,n,r){if(n[0]=m(n[0]),n[0]instanceof Pf)return function(e,t,n,r,i){if(!r)throw new Ur(Br.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Ra(e))if(n.field.isKeyField())s.push(Vs(t,r.key));else{const e=r.data.field(n.field);if(Ss(e))throw new Ur(Br.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 Ur(Br.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.`)}s.push(e)}return new Ys(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=yf(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new Ur(Br.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<i.length;u++){const c=i[u];if(a[u].field.isKeyField()){if("string"!=typeof c)throw new Ur(Br.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!ka(e)&&-1!==c.indexOf("/"))throw new Ur(Br.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(ri.fromString(c));if(!ai.isDocumentKey(n))throw new Ur(Br.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 i=new ai(n);o.push(Vs(t,i))}else{const e=Cf(n,r,c);o.push(e)}}return new Ys(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function Xf(e,t,n){if("string"==typeof(n=m(n))){if(""===n)throw new Ur(Br.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!ka(t)&&-1!==n.indexOf("/"))throw new Ur(Br.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(ri.fromString(n));if(!ai.isDocumentKey(r))throw new Ur(Br.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 Vs(e,new ai(r))}if(n instanceof Pd)return Vs(e,n._key);throw new Ur(Br.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Nd(n)}.`)}function Jf(e,t){if(!Array.isArray(e)||0===e.length)throw new Ur(Br.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Zf(e,t){if(t.isInequality()){const r=Na(e),i=t.field;if(null!==r&&!r.isEqual(i))throw new Ur(Br.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 '${i.toString()}'`);var n=Da(e);null!==n&&eg(0,i,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(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==r)throw r===t.op?new Ur(Br.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new Ur(Br.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function eg(e,t,n){if(!n.isEqual(t))throw new Ur(Br.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 tg{convertValue(e,t="none"){switch(Rs(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Es(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(Ts(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 Pr()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return hs(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new hf(Es(e.latitude),Es(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=xs(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Cs(e));default:return null}}convertTimestamp(e){var t=Is(e);return new ei(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=ri.fromString(e);Vr(Iu(n));const r=new Ds(n.get(1),n.get(3)),i=new ai(n.popFirst(5));return r.isEqual(t)||Mr(`Document ${i} 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.`),i}}function ng(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class rg extends tg{constructor(e){super(),this.firestore=e}convertBytes(e){return new of(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Pd(this.firestore,null,t)}}class ig{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class sg extends Pf{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new ag(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(Bf("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class ag extends sg{data(e={}){return super.data(e)}}class og{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new ig(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 ag(this._firestore,this._userDataWriter,e.key,e,new ig(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 Ur(Br.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(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new ag(s._firestore,s._userDataWriter,e.doc.key,e.doc,new ig(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new ag(s._firestore,s._userDataWriter,e.doc.key,e.doc,new ig(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.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 Pr()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function ug(e,t){return e instanceof sg&&t instanceof sg?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 og&&t instanceof og&&e._firestore===t._firestore&&jd(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class cg extends tg{constructor(e){super(),this.firestore=e}convertBytes(e){return new of(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Pd(this.firestore,null,t)}}function hg(t){t=kd(t,Pd);const n=kd(t.firestore,Xd),e=Jd(n),r=new cg(n);return function(e,t){const n=new qr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(e,t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new Ur(Br.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=vl(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await yd(e),t,n)),n.promise}(e,t._key).then(e=>new sg(n,r,t._key,e,new ig(null!==e&&e.hasLocalMutations,!0),t.converter))}function lg(t){t=kd(t,Ld);const n=kd(t.firestore,Xd),e=Jd(n),r=new cg(n);return function(e,t){const n=new qr;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await wh(e,t,!0),s=new Ml(t,i.Ps),a=s.ha(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=vl(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await yd(e),t,n)),n.promise}(e,t._query).then(e=>new og(n,r,t,e))}function dg(e,t,n){e=kd(e,Pd);var r=kd(e.firestore,Xd),i=ng(e.converter,t,n);return pg(r,[vf(yf(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,go.none())])}function fg(e,t,n,...r){e=kd(e,Pd);var i=kd(e.firestore,Xd),s=yf(i);let a;return a="string"==typeof(t=m(t))||t instanceof uf?xf(s,"updateDoc",e._key,t,n,r):Sf(s,"updateDoc",e._key,t),pg(i,[a.toMutation(e._key,go.exists(!0))])}function gg(t,...n){var e;t=m(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||Kd(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(Kd(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,u;if(t instanceof Pd)o=kd(t.firestore,Xd),u=Ca(t._key.path),a={next:e=>{n[i]&&n[i](yg(o,t,e))},error:n[i+1],complete:n[i+2]};else{const c=kd(t,Ld);o=kd(c.firestore,Xd),u=c._query;const h=new cg(o);a={next:e=>{n[i]&&n[i](new og(o,h,c,e))},error:n[i+1],complete:n[i+2]},Uf(t._query)}return function(e,t,n,r){const i=new ad(r),s=new Cl(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Tl(await _d(e),s)),()=>{i.La(),e.asyncQueue.enqueueAndForget(async()=>Sl(await _d(e),s))}}(Jd(o),u,s,a)}function mg(e,t){return function(e,t){const n=new ad(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.K_.add(t),t.next()}(await _d(e),n)),()=>{n.La(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.K_.delete(t)}(await _d(e),n))}}(Jd(e=kd(e,Xd)),Kd(t)?t:{next:t})}function pg(e,t){return function(e,t){const n=new qr;return e.asyncQueue.enqueueAndForget(async()=>Bl(await wd(e),t,n)),n.promise}(Jd(e),t)}function yg(e,t,n){var r=n.docs.get(t._key),i=new cg(e);return new sg(e,i,t._key,r,new ig(n.hasPendingWrites,n.fromCache),t.converter)}const vg={maxAttempts:5};class wg{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=yf(e)}set(e,t,n){this._verifyNotCommitted();const r=_g(e,this._firestore),i=ng(r.converter,t,n),s=vf(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,go.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=_g(e,this._firestore);let s;return s="string"==typeof(t=m(t))||t instanceof uf?xf(this._dataReader,"WriteBatch.update",i._key,t,n,r):Sf(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,go.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=_g(e,this._firestore);return this._mutations=this._mutations.concat(new xo(t._key,go.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 Ur(Br.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function _g(e,t){if((e=m(e)).firestore!==t)throw new Ur(Br.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class bg extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=yf(e)}get(e){const n=_g(e,this._firestore),r=new rg(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return Pr();const t=e[0];if(t.isFoundDocument())return new Pf(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new Pf(this._firestore,r,n._key,null,n.converter);throw Pr()})}set(e,t,n){var r=_g(e,this._firestore),i=ng(r.converter,t,n),i=vf(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=_g(e,this._firestore),s="string"==typeof(t=m(t))||t instanceof uf?xf(this._dataReader,"Transaction.update",i._key,t,n,r):Sf(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=_g(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=_g(e,this._firestore),n=new cg(this._firestore);return super.get(e).then(e=>new sg(this._firestore,n,t._key,e._document,new ig(!1,!1),t.converter))}}function Ig(t,n,e){t=kd(t,Xd);var r=Object.assign(Object.assign({},vg),e);return function(e){if(e.maxAttempts<1)throw new Ur(Br.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new qr;return t.asyncQueue.enqueueAndForget(async()=>{var e=await md(t).then(e=>e.datastore);new cd(t.asyncQueue,e,r,n,i).run()}),i.promise}(Jd(t),e=>n(new bg(t,e)),r)}Qd=!0,Hd=Wg.SDK_VERSION,Nr=Hd,Wg._registerComponent(new p("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new Xd(new zr(e.getProvider("auth-internal")),new Wr(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new Ur(Br.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Ds(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:Qd},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),Wg.registerVersion(Ar,"4.1.3",$d),Wg.registerVersion(Ar,"4.1.3","esm2017");function Eg(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new Ur("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function Tg(){if("undefined"==typeof Uint8Array)throw new Ur("unimplemented","Uint8Arrays are not available in this environment.")}function Sg(){if("undefined"==typeof atob)throw new Ur("unimplemented","Blobs are unavailable in Firestore in this environment.")}class xg{constructor(e){this._delegate=e}static fromBase64String(e){return Sg(),new xg(of.fromBase64String(e))}static fromUint8Array(e){return Tg(),new xg(of.fromUint8Array(e))}toBase64(){return Sg(),this._delegate.toBase64()}toUint8Array(){return Tg(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function Cg(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 Ag{enableIndexedDbPersistence(e,t){return function(e,t){af(e=kd(e,Xd));var n=Jd(e);if(n._uninitializedComponentsProvider)throw new Ur(Br.FAILED_PRECONDITION,"SDK cache is already specified.");Fr("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new id;return ef(n,i,new nd(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){af(e=kd(e,Xd));var t=Jd(e);if(t._uninitializedComponentsProvider)throw new Ur(Br.FAILED_PRECONDITION,"SDK cache is already specified.");Fr("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new id;return ef(t,r,new rd(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new Ur(Br.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new qr;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!bi.C())return Promise.resolve();var t=e+"main";await bi.delete(t)}(oh(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class Dg{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Ds||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Fr("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={}){Fd(this._delegate,e,t,n)}enableNetwork(){return nf(this._delegate)}disableNetwork(){return rf(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Cd("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 tf(this._delegate)}onSnapshotsInSync(e){return mg(this._delegate,e)}get app(){if(!this._appCompat)throw new Ur("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new Gg(this,Bd(this._delegate,e))}catch(e){throw Fg(e,"collection()","Firestore.collection()")}}doc(e){try{return new Mg(this,Ud(this._delegate,e))}catch(e){throw Fg(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new Ug(this,function(e,t){if(e=kd(e,Md),xd("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new Ur(Br.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ld(e,null,(t=t,new Sa(ri.emptyPath(),t)))}(this._delegate,e))}catch(e){throw Fg(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return Ig(this._delegate,e=>t(new kg(this,e)))}batch(){return Jd(this._delegate),new Rg(new wg(this._delegate,e=>pg(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=Jd(t=kd(t,Xd)),r=new zd,Ed(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return sf(this._delegate,e).then(e=>e?new Ug(this,e):null)}}class Ng extends tg{constructor(e){super(),this.firestore=e}convertBytes(e){return new xg(new of(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return Mg.forKey(t,this.firestore,null)}}class kg{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new Ng(e)}get(e){const t=Kg(e);return this._delegate.get(t).then(e=>new Vg(this._firestore,new sg(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=Kg(e);return n?(Eg("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=Kg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=Kg(e);return this._delegate.delete(t),this}}class Rg{constructor(e){this._delegate=e}set(e,t,n){var r=Kg(e);return n?(Eg("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=Kg(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=Kg(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class Og{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new ag(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new Bg(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=Og.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new Og(e,new Ng(e),t),r.set(t,i)),i}}Og.INSTANCES=new WeakMap;class Mg{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Ng(e)}static forPath(e,t,n){if(e.length%2!=0)throw new Ur("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new Mg(t,new Pd(t._delegate,n,new ai(e)))}static forKey(e,t,n){return new Mg(t,new Pd(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new Gg(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new Gg(this.firestore,Bd(this._delegate,e))}catch(e){throw Fg(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=m(e))instanceof Pd&&qd(this._delegate,e)}set(e,t){t=Eg("DocumentReference.set",t);try{return t?dg(this._delegate,e,t):dg(this._delegate,e)}catch(e){throw Fg(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?fg(this._delegate,e):fg(this._delegate,e,t,...n)}catch(e){throw Fg(e,"updateDoc()","DocumentReference.update()")}}delete(){return pg(kd((e=this._delegate).firestore,Xd),[new xo(e._key,go.none())]);var e}onSnapshot(...e){var t=Lg(e),n=Pg(e,e=>new Vg(this.firestore,new sg(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return gg(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?hg:"server"===(null==e?void 0:e.source)?function(t){t=kd(t,Pd);const n=kd(t.firestore,Xd);return bd(Jd(n),t._key,{source:"server"}).then(e=>yg(n,t,e))}:function(t){t=kd(t,Pd);const n=kd(t.firestore,Xd);return bd(Jd(n),t._key).then(e=>yg(n,t,e))})(this._delegate),t.then(e=>new Vg(this.firestore,new sg(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new Mg(this.firestore,e?this._delegate.withConverter(Og.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Fg(e,t,n){return e.message=e.message.replace(t,n),e}function Lg(e){for(const t of e)if("object"==typeof t&&!Cg(t))return t;return{}}function Pg(e,t){var n;let r;return r=Cg(e[0])?e[0]:Cg(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 Vg{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new Mg(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 ug(this._delegate,e._delegate)}}class Bg extends Vg{data(e){var t=this._delegate.data(e);return void 0!==t||Pr(),t}}class Ug{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new Ng(e)}where(e,t,n){try{return new Ug(this.firestore,Gf(this._delegate,(r=n,i=t,s=Bf("where",e),Kf._create(s,i,r))))}catch(e){throw Fg(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new Ug(this.firestore,Gf(this._delegate,([n,r="asc"]=[e,t],i=r,s=Bf("orderBy",n),$f._create(s,i))))}catch(e){throw Fg(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new Ug(this.firestore,Gf(this._delegate,(Rd("limit",t=e),Qf._create("limit",t,"F"))))}catch(e){throw Fg(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new Ug(this.firestore,Gf(this._delegate,(Rd("limitToLast",t=e),Qf._create("limitToLast",t,"L"))))}catch(e){throw Fg(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new Ug(this.firestore,Gf(this._delegate,function(...e){return Hf._create("startAt",e,!0)}(...e)))}catch(e){throw Fg(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new Ug(this.firestore,Gf(this._delegate,function(...e){return Hf._create("startAfter",e,!1)}(...e)))}catch(e){throw Fg(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new Ug(this.firestore,Gf(this._delegate,function(...e){return Wf._create("endBefore",e,!1)}(...e)))}catch(e){throw Fg(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new Ug(this.firestore,Gf(this._delegate,function(...e){return Wf._create("endAt",e,!0)}(...e)))}catch(e){throw Fg(e,"endAt()","Query.endAt()")}}isEqual(e){return jd(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?lg:"server"===(null==e?void 0:e.source)?function(t){t=kd(t,Ld);const n=kd(t.firestore,Xd),e=Jd(n),r=new cg(n);return Id(e,t._query,{source:"server"}).then(e=>new og(n,r,t,e))}:function(t){t=kd(t,Ld);const n=kd(t.firestore,Xd),e=Jd(n),r=new cg(n);return Uf(t._query),Id(e,t._query).then(e=>new og(n,r,t,e))})(this._delegate),t.then(e=>new jg(this.firestore,new og(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=Lg(e),n=Pg(e,e=>new jg(this.firestore,new og(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return gg(this._delegate,t,n)}withConverter(e){return new Ug(this.firestore,e?this._delegate.withConverter(Og.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class qg{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new Bg(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class jg{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new Ug(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 Bg(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new qg(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new Bg(this._firestore,e))})}isEqual(e){return ug(this._delegate,e._delegate)}}class Gg extends Ug{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 Mg(this.firestore,e):null}doc(e){try{return void 0===e?new Mg(this.firestore,Ud(this._delegate)):new Mg(this.firestore,Ud(this._delegate,e))}catch(e){throw Fg(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=kd(e.firestore,Xd),r=Ud(e),i=ng(e.converter,t);return pg(n,[vf(yf(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,go.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new Mg(this.firestore,e))}isEqual(e){return qd(this._delegate,e._delegate)}withConverter(e){return new Gg(this.firestore,e?this._delegate.withConverter(Og.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function Kg(e){return kd(e,Pd)}const zg={Firestore:Dg,GeoPoint:hf,Timestamp:ei,Blob:xg,Transaction:kg,WriteBatch:Rg,DocumentReference:Mg,DocumentSnapshot:Vg,Query:Ug,QueryDocumentSnapshot:Bg,QuerySnapshot:jg,CollectionReference:Gg,FieldPath:class $g{constructor(...e){this._delegate=new uf(...e)}static documentId(){return new $g(si.keyField().canonicalString())}isEqual(e){return(e=m(e))instanceof uf&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Qg{constructor(e){this._delegate=e}static serverTimestamp(){const e=new bf("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Qg(e)}static delete(){const e=new wf("deleteField");return e._methodName="FieldValue.delete",new Qg(e)}static arrayUnion(...e){const t=function(...e){return new If("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Qg(t)}static arrayRemove(...e){const t=function(...e){return new Ef("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Qg(t)}static increment(e){const t=new Tf("increment",e);return t._methodName="FieldValue.increment",new Qg(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,kr.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};Wd=t.default,Yd=(e,t)=>new Dg(e,t,new Ag),Wd.INTERNAL.registerComponent(new p("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return Yd(t,n)},"PUBLIC").setServiceProps(Object.assign({},zg))),Wd.registerVersion("@firebase/firestore-compat","0.3.17")}).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
2
|
//# sourceMappingURL=firebase-firestore-compat.js.map
|